react-semaphor 0.1.340 → 0.1.341

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/analytics-protocol/index.cjs +1 -1
  2. package/dist/analytics-protocol/index.js +1 -1
  3. package/dist/chunks/{calendar-preferences-dialog-8-KE5sVX.js → calendar-preferences-dialog-_u4Xm011.js} +1 -1
  4. package/dist/chunks/{calendar-preferences-dialog-2IbYrrP1.js → calendar-preferences-dialog-hS6POgEs.js} +1 -1
  5. package/dist/chunks/{dashboard-briefing-launcher-CcqDPVke.js → dashboard-briefing-launcher-D18qNhwa.js} +1 -1
  6. package/dist/chunks/{dashboard-briefing-launcher-DtxDRAiu.js → dashboard-briefing-launcher-DHzIiaKF.js} +3 -3
  7. package/dist/chunks/{dashboard-controls-By7aKmDj.js → dashboard-controls-CilLVS_Q.js} +1 -1
  8. package/dist/chunks/{dashboard-controls-Bi98DhYD.js → dashboard-controls-g1OcteYf.js} +3 -3
  9. package/dist/chunks/{dashboard-json-CGxIsTEP.js → dashboard-json-BjnGSaxC.js} +1 -1
  10. package/dist/chunks/{dashboard-json-BOyLuhS6.js → dashboard-json-ClH0kTga.js} +1 -1
  11. package/dist/chunks/{edit-dashboard-visual-BuXlHmJH.js → edit-dashboard-visual-C_3NYnPz.js} +1 -1
  12. package/dist/chunks/{edit-dashboard-visual-Ba8LenNc.js → edit-dashboard-visual-DbVMVMKM.js} +3 -3
  13. package/dist/chunks/{index-DT9osgRT.js → index-BNZjkxPH.js} +3 -3
  14. package/dist/chunks/{index-DVPvpd8u.js → index-CuSvSh86.js} +7 -6
  15. package/dist/chunks/{resource-management-panel-98Hy6SYB.js → resource-management-panel-DxjN2uw4.js} +2 -2
  16. package/dist/chunks/{resource-management-panel-ByR-FD3h.js → resource-management-panel-N5iUOE89.js} +1 -1
  17. package/dist/chunks/{use-create-flow-overlay-state-uNxArZdj.js → use-create-flow-overlay-state-CSjc7cXZ.js} +1 -1
  18. package/dist/chunks/{use-create-flow-overlay-state-D5uvjbwY.js → use-create-flow-overlay-state-CXPnnXh1.js} +2 -2
  19. package/dist/chunks/{use-visual-utils-CpaqIHoc.js → use-visual-utils-C3MRLrHu.js} +1 -1
  20. package/dist/chunks/{use-visual-utils-BLh9mKic.js → use-visual-utils-DsoGoqPF.js} +1 -1
  21. package/dist/chunks/validators-Caj7EMd1.js +1 -0
  22. package/dist/chunks/{validators-CPEQojnV.js → validators-YtnkRA1G.js} +66 -43
  23. package/dist/dashboard/index.cjs +1 -1
  24. package/dist/dashboard/index.js +1 -1
  25. package/dist/dashboard-authoring/index.cjs +1 -1
  26. package/dist/dashboard-authoring/index.js +1 -1
  27. package/dist/data-app-builder/index.cjs +1 -1
  28. package/dist/data-app-builder/index.js +1 -1
  29. package/dist/data-app-sdk/index.cjs +1 -1
  30. package/dist/data-app-sdk/index.js +120 -113
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.js +5 -5
  33. package/dist/surfboard/index.cjs +1 -1
  34. package/dist/surfboard/index.js +2 -2
  35. package/dist/types/analytics-protocol.d.ts +12 -1
  36. package/dist/types/dashboard-authoring.d.ts +4 -0
  37. package/dist/types/dashboard.d.ts +2 -0
  38. package/dist/types/data-app-builder.d.ts +3 -0
  39. package/dist/types/data-app-sdk.d.ts +3 -0
  40. package/dist/types/main.d.ts +5 -0
  41. package/dist/types/shared.d.ts +1 -0
  42. package/dist/types/surfboard.d.ts +2 -0
  43. package/dist/types/types.d.ts +2 -0
  44. package/package.json +1 -1
  45. package/dist/chunks/validators-CfP-49k9.js +0 -1
@@ -811,7 +811,7 @@ Valid keys: `+JSON.stringify(Object.keys(O),null," "));var Z=X(V,W,G,L,$+"."+W,
811
811
  */class fEe{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,n,r,s){const o=n.listeners[s],i=n.duration;o.forEach(a=>a({chart:t,initial:n.initial,numSteps:i,currentStep:Math.min(r-n.start,i)}))}_refresh(){this._request||(this._running=!0,this._request=tQ.call(window,()=>{this._update(),this._request=null,this._running&&this._refresh()}))}_update(t=Date.now()){let n=0;this._charts.forEach((r,s)=>{if(!r.running||!r.items.length)return;const o=r.items;let i=o.length-1,a=!1,c;for(;i>=0;--i)c=o[i],c._active?(c._total>r.duration&&(r.duration=c._total),c.tick(t),a=!0):(o[i]=o[o.length-1],o.pop());a&&(s.draw(),this._notify(s,r,t,"progress")),o.length||(r.running=!1,this._notify(s,r,t,"complete"),r.initial=!1),n+=o.length}),this._lastDate=t,n===0&&(this._running=!1)}_getAnims(t){const n=this._charts;let r=n.get(t);return r||(r={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},n.set(t,r)),r}listen(t,n,r){this._getAnims(t).listeners[n].push(r)}add(t,n){!n||!n.length||this._getAnims(t).items.push(...n)}has(t){return this._getAnims(t).items.length>0}start(t){const n=this._charts.get(t);n&&(n.running=!0,n.start=Date.now(),n.duration=n.items.reduce((r,s)=>Math.max(r,s._duration),0),this._refresh())}running(t){if(!this._running)return!1;const n=this._charts.get(t);return!(!n||!n.running||!n.items.length)}stop(t){const n=this._charts.get(t);if(!n||!n.items.length)return;const r=n.items;let s=r.length-1;for(;s>=0;--s)r[s].cancel();n.items=[],this._notify(t,n,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var Ql=new fEe;const _z="transparent",hEe={boolean(e,t,n){return n>.5?t:e},color(e,t,n){const r=gz(e||_z),s=r.valid&&gz(t||_z);return s&&s.valid?s.mix(r,n).hexString():t},number(e,t,n){return e+(t-e)*n}};let pEe=class{constructor(t,n,r,s){const o=n[r];s=Er([t.to,s,o,t.from]);const i=Er([t.from,o,s]);this._active=!0,this._fn=t.fn||hEe[t.type||typeof i],this._easing=Zx[t.easing]||Zx.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=n,this._prop=r,this._from=i,this._to=s,this._promises=void 0}active(){return this._active}update(t,n,r){if(this._active){this._notify(!1);const s=this._target[this._prop],o=r-this._start,i=this._duration-o;this._start=r,this._duration=Math.floor(Math.max(i,t.duration)),this._total+=o,this._loop=!!t.loop,this._to=Er([t.to,n,s,t.from]),this._from=Er([t.from,s,n])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const n=t-this._start,r=this._duration,s=this._prop,o=this._from,i=this._loop,a=this._to;let c;if(this._active=o!==a&&(i||n<r),!this._active){this._target[s]=a,this._notify(!0);return}if(n<0){this._target[s]=o;return}c=n/r%2,c=i&&c>1?2-c:c,c=this._easing(Math.min(1,Math.max(0,c))),this._target[s]=this._fn(o,a,c)}wait(){const t=this._promises||(this._promises=[]);return new Promise((n,r)=>{t.push({res:n,rej:r})})}_notify(t){const n=t?"res":"rej",r=this._promises||[];for(let s=0;s<r.length;s++)r[s][n]()}};class yQ{constructor(t,n){this._chart=t,this._properties=new Map,this.configure(n)}configure(t){if(!pn(t))return;const n=Object.keys(Ir.animation),r=this._properties;Object.getOwnPropertyNames(t).forEach(s=>{const o=t[s];if(!pn(o))return;const i={};for(const a of n)i[a]=o[a];(ur(o.properties)&&o.properties||[s]).forEach(a=>{(a===s||!r.has(a))&&r.set(a,i)})})}_animateOptions(t,n){const r=n.options,s=gEe(t,r);if(!s)return[];const o=this._createAnimations(s,r);return r.$shared&&mEe(t.options.$animations,r).then(()=>{t.options=r},()=>{}),o}_createAnimations(t,n){const r=this._properties,s=[],o=t.$animations||(t.$animations={}),i=Object.keys(n),a=Date.now();let c;for(c=i.length-1;c>=0;--c){const u=i[c];if(u.charAt(0)==="$")continue;if(u==="options"){s.push(...this._animateOptions(t,n));continue}const d=n[u];let f=o[u];const h=r.get(u);if(f)if(h&&f.active()){f.update(h,d,a);continue}else f.cancel();if(!h||!h.duration){t[u]=d;continue}o[u]=f=new pEe(h,t,u,d),s.push(f)}return s}update(t,n){if(this._properties.size===0){Object.assign(t,n);return}const r=this._createAnimations(t,n);if(r.length)return Ql.add(this._chart,r),!0}}function mEe(e,t){const n=[],r=Object.keys(t);for(let s=0;s<r.length;s++){const o=e[r[s]];o&&o.active()&&n.push(o.wait())}return Promise.all(n)}function gEe(e,t){if(!t)return;let n=e.options;if(!n){e.options=t;return}return n.$shared&&(e.options=n=Object.assign({},n,{$shared:!1,$animations:{}})),n}function jz(e,t){const n=e&&e.options||{},r=n.reverse,s=n.min===void 0?t:0,o=n.max===void 0?t:0;return{start:r?o:s,end:r?s:o}}function bEe(e,t,n){if(n===!1)return!1;const r=jz(e,n),s=jz(t,n);return{top:s.end,right:r.end,bottom:s.start,left:r.start}}function xEe(e){let t,n,r,s;return pn(e)?(t=e.top,n=e.right,r=e.bottom,s=e.left):t=n=r=s=e,{top:t,right:n,bottom:r,left:s,disabled:e===!1}}function vQ(e,t){const n=[],r=e._getSortedDatasetMetas(t);let s,o;for(s=0,o=r.length;s<o;++s)n.push(r[s].index);return n}function Ez(e,t,n,r={}){const s=e.keys,o=r.mode==="single";let i,a,c,u;if(t===null)return;let d=!1;for(i=0,a=s.length;i<a;++i){if(c=+s[i],c===n){if(d=!0,r.all)continue;break}u=e.values[c],Zr(u)&&(o||t===0||cl(t)===cl(u))&&(t+=u)}return!d&&!r.all?0:t}function yEe(e,t){const{iScale:n,vScale:r}=t,s=n.axis==="x"?"x":"y",o=r.axis==="x"?"x":"y",i=Object.keys(e),a=new Array(i.length);let c,u,d;for(c=0,u=i.length;c<u;++c)d=i[c],a[c]={[s]:d,[o]:e[d]};return a}function gD(e,t){const n=e&&e.options.stacked;return n||n===void 0&&t.stack!==void 0}function vEe(e,t,n){return`${e.id}.${t.id}.${n.stack||n.type}`}function wEe(e){const{min:t,max:n,minDefined:r,maxDefined:s}=e.getUserBounds();return{min:r?t:Number.NEGATIVE_INFINITY,max:s?n:Number.POSITIVE_INFINITY}}function SEe(e,t,n){const r=e[t]||(e[t]={});return r[n]||(r[n]={})}function Dz(e,t,n,r){for(const s of t.getMatchingVisibleMetas(r).reverse()){const o=e[s.index];if(n&&o>0||!n&&o<0)return s.index}return null}function Iz(e,t){const{chart:n,_cachedMeta:r}=e,s=n._stacks||(n._stacks={}),{iScale:o,vScale:i,index:a}=r,c=o.axis,u=i.axis,d=vEe(o,i,r),f=t.length;let h;for(let p=0;p<f;++p){const g=t[p],{[c]:b,[u]:x}=g,y=g._stacks||(g._stacks={});h=y[u]=SEe(s,d,b),h[a]=x,h._top=Dz(h,i,!0,r.type),h._bottom=Dz(h,i,!1,r.type);const S=h._visualValues||(h._visualValues={});S[a]=x}}function bD(e,t){const n=e.scales;return Object.keys(n).filter(r=>n[r].axis===t).shift()}function CEe(e,t){return jd(e,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function NEe(e,t,n){return jd(e,{active:!1,dataIndex:t,parsed:void 0,raw:void 0,element:n,index:t,mode:"default",type:"data"})}function Rb(e,t){const n=e.controller.index,r=e.vScale&&e.vScale.axis;if(r){t=t||e._parsed;for(const s of t){const o=s._stacks;if(!o||o[r]===void 0||o[r][n]===void 0)return;delete o[r][n],o[r]._visualValues!==void 0&&o[r]._visualValues[n]!==void 0&&delete o[r]._visualValues[n]}}}const xD=e=>e==="reset"||e==="none",Tz=(e,t)=>t?e:Object.assign({},e),kEe=(e,t,n)=>e&&!t.hidden&&t._stacked&&{keys:vQ(n,!0),values:null};class ti{constructor(t,n){this.chart=t,this._ctx=t.ctx,this.index=n,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=gD(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Rb(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,n=this._cachedMeta,r=this.getDataset(),s=(f,h,p,g)=>f==="x"?h:f==="r"?g:p,o=n.xAxisID=Yt(r.xAxisID,bD(t,"x")),i=n.yAxisID=Yt(r.yAxisID,bD(t,"y")),a=n.rAxisID=Yt(r.rAxisID,bD(t,"r")),c=n.indexAxis,u=n.iAxisID=s(c,o,i,a),d=n.vAxisID=s(c,i,o,a);n.xScale=this.getScaleForId(o),n.yScale=this.getScaleForId(i),n.rScale=this.getScaleForId(a),n.iScale=this.getScaleForId(u),n.vScale=this.getScaleForId(d)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const n=this._cachedMeta;return t===n.iScale?n.vScale:n.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&hz(this._data,this),t._stacked&&Rb(t)}_dataCheck(){const t=this.getDataset(),n=t.data||(t.data=[]),r=this._data;if(pn(n)){const s=this._cachedMeta;this._data=yEe(n,s)}else if(r!==n){if(r){hz(r,this);const s=this._cachedMeta;Rb(s),s._parsed=[]}n&&Object.isExtensible(n)&&cje(n,this),this._syncList=[],this._data=n}}addElements(){const t=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(t.dataset=new this.datasetElementType)}buildOrUpdateElements(t){const n=this._cachedMeta,r=this.getDataset();let s=!1;this._dataCheck();const o=n._stacked;n._stacked=gD(n.vScale,n),n.stack!==r.stack&&(s=!0,Rb(n),n.stack=r.stack),this._resyncElements(t),(s||o!==n._stacked)&&(Iz(this,n._parsed),n._stacked=gD(n.vScale,n))}configure(){const t=this.chart.config,n=t.datasetScopeKeys(this._type),r=t.getOptionScopes(this.getDataset(),n,!0);this.options=t.createResolver(r,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,n){const{_cachedMeta:r,_data:s}=this,{iScale:o,_stacked:i}=r,a=o.axis;let c=t===0&&n===s.length?!0:r._sorted,u=t>0&&r._parsed[t-1],d,f,h;if(this._parsing===!1)r._parsed=s,r._sorted=!0,h=s;else{ur(s[t])?h=this.parseArrayData(r,s,t,n):pn(s[t])?h=this.parseObjectData(r,s,t,n):h=this.parsePrimitiveData(r,s,t,n);const p=()=>f[a]===null||u&&f[a]<u[a];for(d=0;d<n;++d)r._parsed[d+t]=f=h[d],c&&(p()&&(c=!1),u=f);r._sorted=c}i&&Iz(this,h)}parsePrimitiveData(t,n,r,s){const{iScale:o,vScale:i}=t,a=o.axis,c=i.axis,u=o.getLabels(),d=o===i,f=new Array(s);let h,p,g;for(h=0,p=s;h<p;++h)g=h+r,f[h]={[a]:d||o.parse(u[g],g),[c]:i.parse(n[g],g)};return f}parseArrayData(t,n,r,s){const{xScale:o,yScale:i}=t,a=new Array(s);let c,u,d,f;for(c=0,u=s;c<u;++c)d=c+r,f=n[d],a[c]={x:o.parse(f[0],d),y:i.parse(f[1],d)};return a}parseObjectData(t,n,r,s){const{xScale:o,yScale:i}=t,{xAxisKey:a="x",yAxisKey:c="y"}=this._parsing,u=new Array(s);let d,f,h,p;for(d=0,f=s;d<f;++d)h=d+r,p=n[h],u[d]={x:o.parse(nd(p,a),h),y:i.parse(nd(p,c),h)};return u}getParsed(t){return this._cachedMeta._parsed[t]}getDataElement(t){return this._cachedMeta.data[t]}applyStack(t,n,r){const s=this.chart,o=this._cachedMeta,i=n[t.axis],a={keys:vQ(s,!0),values:n._stacks[t.axis]._visualValues};return Ez(a,i,o.index,{mode:r})}updateRangeFromParsed(t,n,r,s){const o=r[n.axis];let i=o===null?NaN:o;const a=s&&r._stacks[n.axis];s&&a&&(s.values=a,i=Ez(s,o,this._cachedMeta.index)),t.min=Math.min(t.min,i),t.max=Math.max(t.max,i)}getMinMax(t,n){const r=this._cachedMeta,s=r._parsed,o=r._sorted&&t===r.iScale,i=s.length,a=this._getOtherScale(t),c=kEe(n,r,this.chart),u={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:d,max:f}=wEe(a);let h,p;function g(){p=s[h];const b=p[a.axis];return!Zr(p[t.axis])||d>b||f<b}for(h=0;h<i&&!(!g()&&(this.updateRangeFromParsed(u,t,p,c),o));++h);if(o){for(h=i-1;h>=0;--h)if(!g()){this.updateRangeFromParsed(u,t,p,c);break}}return u}getAllParsedValues(t){const n=this._cachedMeta._parsed,r=[];let s,o,i;for(s=0,o=n.length;s<o;++s)i=n[s][t.axis],Zr(i)&&r.push(i);return r}getMaxOverflow(){return!1}getLabelAndValue(t){const n=this._cachedMeta,r=n.iScale,s=n.vScale,o=this.getParsed(t);return{label:r?""+r.getLabelForValue(o[r.axis]):"",value:s?""+s.getLabelForValue(o[s.axis]):""}}_update(t){const n=this._cachedMeta;this.update(t||"default"),n._clip=xEe(Yt(this.options.clip,bEe(n.xScale,n.yScale,this.getMaxOverflow())))}update(t){}draw(){const t=this._ctx,n=this.chart,r=this._cachedMeta,s=r.data||[],o=n.chartArea,i=[],a=this._drawStart||0,c=this._drawCount||s.length-a,u=this.options.drawActiveElementsOnTop;let d;for(r.dataset&&r.dataset.draw(t,o,a,c),d=a;d<a+c;++d){const f=s[d];f.hidden||(f.active&&u?i.push(f):f.draw(t,o))}for(d=0;d<i.length;++d)i[d].draw(t,o)}getStyle(t,n){const r=n?"active":"default";return t===void 0&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(r):this.resolveDataElementOptions(t||0,r)}getContext(t,n,r){const s=this.getDataset();let o;if(t>=0&&t<this._cachedMeta.data.length){const i=this._cachedMeta.data[t];o=i.$context||(i.$context=NEe(this.getContext(),t,i)),o.parsed=this.getParsed(t),o.raw=s.data[t],o.index=o.dataIndex=t}else o=this.$context||(this.$context=CEe(this.chart.getContext(),this.index)),o.dataset=s,o.index=o.datasetIndex=this.index;return o.active=!!n,o.mode=r,o}resolveDatasetElementOptions(t){return this._resolveElementOptions(this.datasetElementType.id,t)}resolveDataElementOptions(t,n){return this._resolveElementOptions(this.dataElementType.id,n,t)}_resolveElementOptions(t,n="default",r){const s=n==="active",o=this._cachedDataOpts,i=t+"-"+n,a=o[i],c=this.enableOptionSharing&&Um(r);if(a)return Tz(a,c);const u=this.chart.config,d=u.datasetElementScopeKeys(this._type,t),f=s?[`${t}Hover`,"hover",t,""]:[t,""],h=u.getOptionScopes(this.getDataset(),d),p=Object.keys(Ir.elements[t]),g=()=>this.getContext(r,s,n),b=u.resolveNamedOptions(h,p,g,f);return b.$shared&&(b.$shared=c,o[i]=Object.freeze(Tz(b,c))),b}_resolveAnimations(t,n,r){const s=this.chart,o=this._cachedDataOpts,i=`animation-${n}`,a=o[i];if(a)return a;let c;if(s.options.animation!==!1){const d=this.chart.config,f=d.datasetAnimationScopeKeys(this._type,n),h=d.getOptionScopes(this.getDataset(),f);c=d.createResolver(h,this.getContext(t,r,n))}const u=new yQ(s,c&&c.animations);return c&&c._cacheable&&(o[i]=Object.freeze(u)),u}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,n){return!n||xD(t)||this.chart._animationsDisabled}_getSharedOptions(t,n){const r=this.resolveDataElementOptions(t,n),s=this._sharedOptions,o=this.getSharedOptions(r),i=this.includeOptions(n,o)||o!==s;return this.updateSharedOptions(o,n,r),{sharedOptions:o,includeOptions:i}}updateElement(t,n,r,s){xD(s)?Object.assign(t,r):this._resolveAnimations(n,s).update(t,r)}updateSharedOptions(t,n,r){t&&!xD(n)&&this._resolveAnimations(void 0,n).update(t,r)}_setStyle(t,n,r,s){t.active=s;const o=this.getStyle(n,s);this._resolveAnimations(n,r,s).update(t,{options:!s&&this.getSharedOptions(o)||o})}removeHoverStyle(t,n,r){this._setStyle(t,r,"active",!1)}setHoverStyle(t,n,r){this._setStyle(t,r,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const n=this._data,r=this._cachedMeta.data;for(const[a,c,u]of this._syncList)this[a](c,u);this._syncList=[];const s=r.length,o=n.length,i=Math.min(o,s);i&&this.parse(0,i),o>s?this._insertElements(s,o-s,t):o<s&&this._removeElements(o,s-o)}_insertElements(t,n,r=!0){const s=this._cachedMeta,o=s.data,i=t+n;let a;const c=u=>{for(u.length+=n,a=u.length-1;a>=i;a--)u[a]=u[a-n]};for(c(o),a=t;a<i;++a)o[a]=new this.dataElementType;this._parsing&&c(s._parsed),this.parse(t,n),r&&this.updateElements(o,t,n,"reset")}updateElements(t,n,r,s){}_removeElements(t,n){const r=this._cachedMeta;if(this._parsing){const s=r._parsed.splice(t,n);r._stacked&&Rb(r,s)}r.data.splice(t,n)}_sync(t){if(this._parsing)this._syncList.push(t);else{const[n,r,s]=t;this[n](r,s)}this.chart._dataChanges.push([this.index,...t])}_onDataPush(){const t=arguments.length;this._sync(["_insertElements",this.getDataset().data.length-t,t])}_onDataPop(){this._sync(["_removeElements",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync(["_removeElements",0,1])}_onDataSplice(t,n){n&&this._sync(["_removeElements",t,n]);const r=arguments.length-2;r&&this._sync(["_insertElements",t,r])}_onDataUnshift(){this._sync(["_insertElements",0,arguments.length])}}Ne(ti,"defaults",{}),Ne(ti,"datasetElementType",null),Ne(ti,"dataElementType",null);function _Ee(e,t){if(!e._cache.$bar){const n=e.getMatchingVisibleMetas(t);let r=[];for(let s=0,o=n.length;s<o;s++)r=r.concat(n[s].controller.getAllParsedValues(e));e._cache.$bar=eQ(r.sort((s,o)=>s-o))}return e._cache.$bar}function jEe(e){const t=e.iScale,n=_Ee(t,e.type);let r=t._length,s,o,i,a;const c=()=>{i===32767||i===-32768||(Um(a)&&(r=Math.min(r,Math.abs(i-a)||r)),a=i)};for(s=0,o=n.length;s<o;++s)i=t.getPixelForValue(n[s]),c();for(a=void 0,s=0,o=t.ticks.length;s<o;++s)i=t.getPixelForTick(s),c();return r}function EEe(e,t,n,r){const s=n.barThickness;let o,i;return cn(s)?(o=t.min*n.categoryPercentage,i=n.barPercentage):(o=s*r,i=1),{chunk:o/r,ratio:i,start:t.pixels[e]-o/2}}function DEe(e,t,n,r){const s=t.pixels,o=s[e];let i=e>0?s[e-1]:null,a=e<s.length-1?s[e+1]:null;const c=n.categoryPercentage;i===null&&(i=o-(a===null?t.end-t.start:a-o)),a===null&&(a=o+o-i);const u=o-(o-Math.min(i,a))/2*c;return{chunk:Math.abs(a-i)/2*c/r,ratio:n.barPercentage,start:u}}function IEe(e,t,n,r){const s=n.parse(e[0],r),o=n.parse(e[1],r),i=Math.min(s,o),a=Math.max(s,o);let c=i,u=a;Math.abs(i)>Math.abs(a)&&(c=a,u=i),t[n.axis]=u,t._custom={barStart:c,barEnd:u,start:s,end:o,min:i,max:a}}function wQ(e,t,n,r){return ur(e)?IEe(e,t,n,r):t[n.axis]=n.parse(e,r),t}function Mz(e,t,n,r){const s=e.iScale,o=e.vScale,i=s.getLabels(),a=s===o,c=[];let u,d,f,h;for(u=n,d=n+r;u<d;++u)h=t[u],f={},f[s.axis]=a||s.parse(i[u],u),c.push(wQ(h,f,o,u));return c}function yD(e){return e&&e.barStart!==void 0&&e.barEnd!==void 0}function TEe(e,t,n){return e!==0?cl(e):(t.isHorizontal()?1:-1)*(t.min>=n?1:-1)}function MEe(e){let t,n,r,s,o;return e.horizontal?(t=e.base>e.x,n="left",r="right"):(t=e.base<e.y,n="bottom",r="top"),t?(s="end",o="start"):(s="start",o="end"),{start:n,end:r,reverse:t,top:s,bottom:o}}function AEe(e,t,n,r){let s=t.borderSkipped;const o={};if(!s){e.borderSkipped=o;return}if(s===!0){e.borderSkipped={top:!0,right:!0,bottom:!0,left:!0};return}const{start:i,end:a,reverse:c,top:u,bottom:d}=MEe(e);s==="middle"&&n&&(e.enableBorderRadius=!0,(n._top||0)===r?s=u:(n._bottom||0)===r?s=d:(o[Az(d,i,a,c)]=!0,s=u)),o[Az(s,i,a,c)]=!0,e.borderSkipped=o}function Az(e,t,n,r){return r?(e=REe(e,t,n),e=Rz(e,n,t)):e=Rz(e,t,n),e}function REe(e,t,n){return e===t?n:e===n?t:e}function Rz(e,t,n){return e==="start"?t:e==="end"?n:e}function FEe(e,{inflateAmount:t},n){e.inflateAmount=t==="auto"?n===1?.33:0:t}class qf extends ti{parsePrimitiveData(t,n,r,s){return Mz(t,n,r,s)}parseArrayData(t,n,r,s){return Mz(t,n,r,s)}parseObjectData(t,n,r,s){const{iScale:o,vScale:i}=t,{xAxisKey:a="x",yAxisKey:c="y"}=this._parsing,u=o.axis==="x"?a:c,d=i.axis==="x"?a:c,f=[];let h,p,g,b;for(h=r,p=r+s;h<p;++h)b=n[h],g={},g[o.axis]=o.parse(nd(b,u),h),f.push(wQ(nd(b,d),g,i,h));return f}updateRangeFromParsed(t,n,r,s){super.updateRangeFromParsed(t,n,r,s);const o=r._custom;o&&n===this._cachedMeta.vScale&&(t.min=Math.min(t.min,o.min),t.max=Math.max(t.max,o.max))}getMaxOverflow(){return 0}getLabelAndValue(t){const n=this._cachedMeta,{iScale:r,vScale:s}=n,o=this.getParsed(t),i=o._custom,a=yD(i)?"["+i.start+", "+i.end+"]":""+s.getLabelForValue(o[s.axis]);return{label:""+r.getLabelForValue(o[r.axis]),value:a}}initialize(){this.enableOptionSharing=!0,super.initialize();const t=this._cachedMeta;t.stack=this.getDataset().stack}update(t){const n=this._cachedMeta;this.updateElements(n.data,0,n.data.length,t)}updateElements(t,n,r,s){const o=s==="reset",{index:i,_cachedMeta:{vScale:a}}=this,c=a.getBasePixel(),u=a.isHorizontal(),d=this._getRuler(),{sharedOptions:f,includeOptions:h}=this._getSharedOptions(n,s);for(let p=n;p<n+r;p++){const g=this.getParsed(p),b=o||cn(g[a.axis])?{base:c,head:c}:this._calculateBarValuePixels(p),x=this._calculateBarIndexPixels(p,d),y=(g._stacks||{})[a.axis],S={horizontal:u,base:b.base,enableBorderRadius:!y||yD(g._custom)||i===y._top||i===y._bottom,x:u?b.head:x.center,y:u?x.center:b.head,height:u?x.size:Math.abs(b.size),width:u?Math.abs(b.size):x.size};h&&(S.options=f||this.resolveDataElementOptions(p,t[p].active?"active":s));const w=S.options||t[p].options;AEe(S,w,y,i),FEe(S,w,d.ratio),this.updateElement(t[p],p,S,s)}}_getStacks(t,n){const{iScale:r}=this._cachedMeta,s=r.getMatchingVisibleMetas(this._type).filter(d=>d.controller.options.grouped),o=r.options.stacked,i=[],a=this._cachedMeta.controller.getParsed(n),c=a&&a[r.axis],u=d=>{const f=d._parsed.find(p=>p[r.axis]===c),h=f&&f[d.vScale.axis];if(cn(h)||isNaN(h))return!0};for(const d of s)if(!(n!==void 0&&u(d))&&((o===!1||i.indexOf(d.stack)===-1||o===void 0&&d.stack===void 0)&&i.push(d.stack),d.index===t))break;return i.length||i.push(void 0),i}_getStackCount(t){return this._getStacks(void 0,t).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){const t=this.chart.scales,n=this.chart.options.indexAxis;return Object.keys(t).filter(r=>t[r].axis===n).shift()}_getAxis(){const t={},n=this.getFirstScaleIdForIndexAxis();for(const r of this.chart.data.datasets)t[Yt(this.chart.options.indexAxis==="x"?r.xAxisID:r.yAxisID,n)]=!0;return Object.keys(t)}_getStackIndex(t,n,r){const s=this._getStacks(t,r),o=n!==void 0?s.indexOf(n):-1;return o===-1?s.length-1:o}_getRuler(){const t=this.options,n=this._cachedMeta,r=n.iScale,s=[];let o,i;for(o=0,i=n.data.length;o<i;++o)s.push(r.getPixelForValue(this.getParsed(o)[r.axis],o));const a=t.barThickness;return{min:a||jEe(n),pixels:s,start:r._startPixel,end:r._endPixel,stackCount:this._getStackCount(),scale:r,grouped:t.grouped,ratio:a?1:t.categoryPercentage*t.barPercentage}}_calculateBarValuePixels(t){const{_cachedMeta:{vScale:n,_stacked:r,index:s},options:{base:o,minBarLength:i}}=this,a=o||0,c=this.getParsed(t),u=c._custom,d=yD(u);let f=c[n.axis],h=0,p=r?this.applyStack(n,c,r):f,g,b;p!==f&&(h=p-f,p=f),d&&(f=u.barStart,p=u.barEnd-u.barStart,f!==0&&cl(f)!==cl(u.barEnd)&&(h=0),h+=f);const x=!cn(o)&&!d?o:h;let y=n.getPixelForValue(x);if(this.chart.getDataVisibility(t)?g=n.getPixelForValue(h+p):g=y,b=g-y,Math.abs(b)<i){b=TEe(b,n,a)*i,f===a&&(y-=b/2);const S=n.getPixelForDecimal(0),w=n.getPixelForDecimal(1),C=Math.min(S,w),N=Math.max(S,w);y=Math.max(Math.min(y,N),C),g=y+b,r&&!d&&(c._stacks[n.axis]._visualValues[s]=n.getValueForPixel(g)-n.getValueForPixel(y))}if(y===n.getPixelForValue(a)){const S=cl(b)*n.getLineWidthForValue(a)/2;y+=S,b-=S}return{size:b,base:y,head:g,center:g+b/2}}_calculateBarIndexPixels(t,n){const r=n.scale,s=this.options,o=s.skipNull,i=Yt(s.maxBarThickness,1/0);let a,c;const u=this._getAxisCount();if(n.grouped){const d=o?this._getStackCount(t):n.stackCount,f=s.barThickness==="flex"?DEe(t,n,s,d*u):EEe(t,n,s,d*u),h=this.chart.options.indexAxis==="x"?this.getDataset().xAxisID:this.getDataset().yAxisID,p=this._getAxis().indexOf(Yt(h,this.getFirstScaleIdForIndexAxis())),g=this._getStackIndex(this.index,this._cachedMeta.stack,o?t:void 0)+p;a=f.start+f.chunk*g+f.chunk/2,c=Math.min(i,f.chunk*f.ratio)}else a=r.getPixelForValue(this.getParsed(t)[r.axis],t),c=Math.min(i,n.min*n.ratio);return{base:a-c/2,head:a+c/2,center:a,size:c}}draw(){const t=this._cachedMeta,n=t.vScale,r=t.data,s=r.length;let o=0;for(;o<s;++o)this.getParsed(o)[n.axis]!==null&&!r[o].hidden&&r[o].draw(this._ctx)}}Ne(qf,"id","bar"),Ne(qf,"defaults",{datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}}),Ne(qf,"overrides",{scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}});class IS extends ti{initialize(){this.enableOptionSharing=!0,super.initialize()}parsePrimitiveData(t,n,r,s){const o=super.parsePrimitiveData(t,n,r,s);for(let i=0;i<o.length;i++)o[i]._custom=this.resolveDataElementOptions(i+r).radius;return o}parseArrayData(t,n,r,s){const o=super.parseArrayData(t,n,r,s);for(let i=0;i<o.length;i++){const a=n[r+i];o[i]._custom=Yt(a[2],this.resolveDataElementOptions(i+r).radius)}return o}parseObjectData(t,n,r,s){const o=super.parseObjectData(t,n,r,s);for(let i=0;i<o.length;i++){const a=n[r+i];o[i]._custom=Yt(a&&a.r&&+a.r,this.resolveDataElementOptions(i+r).radius)}return o}getMaxOverflow(){const t=this._cachedMeta.data;let n=0;for(let r=t.length-1;r>=0;--r)n=Math.max(n,t[r].size(this.resolveDataElementOptions(r))/2);return n>0&&n}getLabelAndValue(t){const n=this._cachedMeta,r=this.chart.data.labels||[],{xScale:s,yScale:o}=n,i=this.getParsed(t),a=s.getLabelForValue(i.x),c=o.getLabelForValue(i.y),u=i._custom;return{label:r[t]||"",value:"("+a+", "+c+(u?", "+u:"")+")"}}update(t){const n=this._cachedMeta.data;this.updateElements(n,0,n.length,t)}updateElements(t,n,r,s){const o=s==="reset",{iScale:i,vScale:a}=this._cachedMeta,{sharedOptions:c,includeOptions:u}=this._getSharedOptions(n,s),d=i.axis,f=a.axis;for(let h=n;h<n+r;h++){const p=t[h],g=!o&&this.getParsed(h),b={},x=b[d]=o?i.getPixelForDecimal(.5):i.getPixelForValue(g[d]),y=b[f]=o?a.getBasePixel():a.getPixelForValue(g[f]);b.skip=isNaN(x)||isNaN(y),u&&(b.options=c||this.resolveDataElementOptions(h,p.active?"active":s),o&&(b.options.radius=0)),this.updateElement(p,h,b,s)}}resolveDataElementOptions(t,n){const r=this.getParsed(t);let s=super.resolveDataElementOptions(t,n);s.$shared&&(s=Object.assign({},s,{$shared:!1}));const o=s.radius;return n!=="active"&&(s.radius=0),s.radius+=Yt(r&&r._custom,o),s}}Ne(IS,"id","bubble"),Ne(IS,"defaults",{datasetElementType:!1,dataElementType:"point",animations:{numbers:{type:"number",properties:["x","y","borderWidth","radius"]}}}),Ne(IS,"overrides",{scales:{x:{type:"linear"},y:{type:"linear"}}});function PEe(e,t,n){let r=1,s=1,o=0,i=0;if(t<Dr){const a=e,c=a+t,u=Math.cos(a),d=Math.sin(a),f=Math.cos(c),h=Math.sin(c),p=(w,C,N)=>Hy(w,a,c,!0)?1:Math.max(C,C*n,N,N*n),g=(w,C,N)=>Hy(w,a,c,!0)?-1:Math.min(C,C*n,N,N*n),b=p(0,u,f),x=p(ts,d,h),y=g(Vn,u,f),S=g(Vn+ts,d,h);r=(b-y)/2,s=(x-S)/2,o=-(b+y)/2,i=-(x+S)/2}return{ratioX:r,ratioY:s,offsetX:o,offsetY:i}}class wf extends ti{constructor(t,n){super(t,n),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,n){const r=this.getDataset().data,s=this._cachedMeta;if(this._parsing===!1)s._parsed=r;else{let o=c=>+r[c];if(pn(r[t])){const{key:c="value"}=this._parsing;o=u=>+nd(r[u],c)}let i,a;for(i=t,a=t+n;i<a;++i)s._parsed[i]=o(i)}}_getRotation(){return ma(this.options.rotation-90)}_getCircumference(){return ma(this.options.circumference)}_getRotationExtents(){let t=Dr,n=-Dr;for(let r=0;r<this.chart.data.datasets.length;++r)if(this.chart.isDatasetVisible(r)&&this.chart.getDatasetMeta(r).type===this._type){const s=this.chart.getDatasetMeta(r).controller,o=s._getRotation(),i=s._getCircumference();t=Math.min(t,o),n=Math.max(n,o+i)}return{rotation:t,circumference:n-t}}update(t){const n=this.chart,{chartArea:r}=n,s=this._cachedMeta,o=s.data,i=this.getMaxBorderWidth()+this.getMaxOffset(o)+this.options.spacing,a=Math.max((Math.min(r.width,r.height)-i)/2,0),c=Math.min(G_e(this.options.cutout,a),1),u=this._getRingWeight(this.index),{circumference:d,rotation:f}=this._getRotationExtents(),{ratioX:h,ratioY:p,offsetX:g,offsetY:b}=PEe(f,d,c),x=(r.width-i)/h,y=(r.height-i)/p,S=Math.max(Math.min(x,y)/2,0),w=KX(this.options.radius,S),C=Math.max(w*c,0),N=(w-C)/this._getVisibleDatasetWeightTotal();this.offsetX=g*w,this.offsetY=b*w,s.total=this.calculateTotal(),this.outerRadius=w-N*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-N*u,0),this.updateElements(o,0,o.length,t)}_circumference(t,n){const r=this.options,s=this._cachedMeta,o=this._getCircumference();return n&&r.animation.animateRotate||!this.chart.getDataVisibility(t)||s._parsed[t]===null||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*o/Dr)}updateElements(t,n,r,s){const o=s==="reset",i=this.chart,a=i.chartArea,u=i.options.animation,d=(a.left+a.right)/2,f=(a.top+a.bottom)/2,h=o&&u.animateScale,p=h?0:this.innerRadius,g=h?0:this.outerRadius,{sharedOptions:b,includeOptions:x}=this._getSharedOptions(n,s);let y=this._getRotation(),S;for(S=0;S<n;++S)y+=this._circumference(S,o);for(S=n;S<n+r;++S){const w=this._circumference(S,o),C=t[S],N={x:d+this.offsetX,y:f+this.offsetY,startAngle:y,endAngle:y+w,circumference:w,outerRadius:g,innerRadius:p};x&&(N.options=b||this.resolveDataElementOptions(S,C.active?"active":s)),y+=w,this.updateElement(C,S,N,s)}}calculateTotal(){const t=this._cachedMeta,n=t.data;let r=0,s;for(s=0;s<n.length;s++){const o=t._parsed[s];o!==null&&!isNaN(o)&&this.chart.getDataVisibility(s)&&!n[s].hidden&&(r+=Math.abs(o))}return r}calculateCircumference(t){const n=this._cachedMeta.total;return n>0&&!isNaN(t)?Dr*(Math.abs(t)/n):0}getLabelAndValue(t){const n=this._cachedMeta,r=this.chart,s=r.data.labels||[],o=Sv(n._parsed[t],r.options.locale);return{label:s[t]||"",value:o}}getMaxBorderWidth(t){let n=0;const r=this.chart;let s,o,i,a,c;if(!t){for(s=0,o=r.data.datasets.length;s<o;++s)if(r.isDatasetVisible(s)){i=r.getDatasetMeta(s),t=i.data,a=i.controller;break}}if(!t)return 0;for(s=0,o=t.length;s<o;++s)c=a.resolveDataElementOptions(s),c.borderAlign!=="inner"&&(n=Math.max(n,c.borderWidth||0,c.hoverBorderWidth||0));return n}getMaxOffset(t){let n=0;for(let r=0,s=t.length;r<s;++r){const o=this.resolveDataElementOptions(r);n=Math.max(n,o.offset||0,o.hoverOffset||0)}return n}_getRingWeightOffset(t){let n=0;for(let r=0;r<t;++r)this.chart.isDatasetVisible(r)&&(n+=this._getRingWeight(r));return n}_getRingWeight(t){return Math.max(Yt(this.chart.data.datasets[t].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}Ne(wf,"id","doughnut"),Ne(wf,"defaults",{datasetElementType:!1,dataElementType:"arc",animation:{animateRotate:!0,animateScale:!1},animations:{numbers:{type:"number",properties:["circumference","endAngle","innerRadius","outerRadius","startAngle","x","y","offset","borderWidth","spacing"]}},cutout:"50%",rotation:0,circumference:360,radius:"100%",spacing:0,indexAxis:"r"}),Ne(wf,"descriptors",{_scriptable:t=>t!=="spacing",_indexable:t=>t!=="spacing"&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")}),Ne(wf,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const n=t.data,{labels:{pointStyle:r,textAlign:s,color:o,useBorderRadius:i,borderRadius:a}}=t.legend.options;return n.labels.length&&n.datasets.length?n.labels.map((c,u)=>{const f=t.getDatasetMeta(0).controller.getStyle(u);return{text:c,fillStyle:f.backgroundColor,fontColor:o,hidden:!t.getDataVisibility(u),lineDash:f.borderDash,lineDashOffset:f.borderDashOffset,lineJoin:f.borderJoinStyle,lineWidth:f.borderWidth,strokeStyle:f.borderColor,textAlign:s,pointStyle:r,borderRadius:i&&(a||f.borderRadius),index:u}}):[]}},onClick(t,n,r){r.chart.toggleDataVisibility(n.index),r.chart.update()}}}});class TS extends ti{initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){const n=this._cachedMeta,{dataset:r,data:s=[],_dataset:o}=n,i=this.chart._animationsDisabled;let{start:a,count:c}=rQ(n,s,i);this._drawStart=a,this._drawCount=c,sQ(n)&&(a=0,c=s.length),r._chart=this.chart,r._datasetIndex=this.index,r._decimated=!!o._decimated,r.points=s;const u=this.resolveDatasetElementOptions(t);this.options.showLine||(u.borderWidth=0),u.segment=this.options.segment,this.updateElement(r,void 0,{animated:!i,options:u},t),this.updateElements(s,a,c,t)}updateElements(t,n,r,s){const o=s==="reset",{iScale:i,vScale:a,_stacked:c,_dataset:u}=this._cachedMeta,{sharedOptions:d,includeOptions:f}=this._getSharedOptions(n,s),h=i.axis,p=a.axis,{spanGaps:g,segment:b}=this.options,x=fh(g)?g:Number.POSITIVE_INFINITY,y=this.chart._animationsDisabled||o||s==="none",S=n+r,w=t.length;let C=n>0&&this.getParsed(n-1);for(let N=0;N<w;++N){const k=t[N],_=y?k:{};if(N<n||N>=S){_.skip=!0;continue}const E=this.getParsed(N),D=cn(E[p]),j=_[h]=i.getPixelForValue(E[h],N),I=_[p]=o||D?a.getBasePixel():a.getPixelForValue(c?this.applyStack(a,E,c):E[p],N);_.skip=isNaN(j)||isNaN(I)||D,_.stop=N>0&&Math.abs(E[h]-C[h])>x,b&&(_.parsed=E,_.raw=u.data[N]),f&&(_.options=d||this.resolveDataElementOptions(N,k.active?"active":s)),y||this.updateElement(k,N,_,s),C=E}}getMaxOverflow(){const t=this._cachedMeta,n=t.dataset,r=n.options&&n.options.borderWidth||0,s=t.data||[];if(!s.length)return r;const o=s[0].size(this.resolveDataElementOptions(0)),i=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(r,o,i)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}}Ne(TS,"id","line"),Ne(TS,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),Ne(TS,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});class Qx extends ti{constructor(t,n){super(t,n),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const n=this._cachedMeta,r=this.chart,s=r.data.labels||[],o=Sv(n._parsed[t].r,r.options.locale);return{label:s[t]||"",value:o}}parseObjectData(t,n,r,s){return dQ.bind(this)(t,n,r,s)}update(t){const n=this._cachedMeta.data;this._updateRadius(),this.updateElements(n,0,n.length,t)}getMinMax(){const t=this._cachedMeta,n={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach((r,s)=>{const o=this.getParsed(s).r;!isNaN(o)&&this.chart.getDataVisibility(s)&&(o<n.min&&(n.min=o),o>n.max&&(n.max=o))}),n}_updateRadius(){const t=this.chart,n=t.chartArea,r=t.options,s=Math.min(n.right-n.left,n.bottom-n.top),o=Math.max(s/2,0),i=Math.max(r.cutoutPercentage?o/100*r.cutoutPercentage:1,0),a=(o-i)/t.getVisibleDatasetCount();this.outerRadius=o-a*this.index,this.innerRadius=this.outerRadius-a}updateElements(t,n,r,s){const o=s==="reset",i=this.chart,c=i.options.animation,u=this._cachedMeta.rScale,d=u.xCenter,f=u.yCenter,h=u.getIndexAngle(0)-.5*Vn;let p=h,g;const b=360/this.countVisibleElements();for(g=0;g<n;++g)p+=this._computeAngle(g,s,b);for(g=n;g<n+r;g++){const x=t[g];let y=p,S=p+this._computeAngle(g,s,b),w=i.getDataVisibility(g)?u.getDistanceFromCenterForValue(this.getParsed(g).r):0;p=S,o&&(c.animateScale&&(w=0),c.animateRotate&&(y=S=h));const C={x:d,y:f,innerRadius:0,outerRadius:w,startAngle:y,endAngle:S,options:this.resolveDataElementOptions(g,x.active?"active":s)};this.updateElement(x,g,C,s)}}countVisibleElements(){const t=this._cachedMeta;let n=0;return t.data.forEach((r,s)=>{!isNaN(this.getParsed(s).r)&&this.chart.getDataVisibility(s)&&n++}),n}_computeAngle(t,n,r){return this.chart.getDataVisibility(t)?ma(this.resolveDataElementOptions(t,n).angle||r):0}}Ne(Qx,"id","polarArea"),Ne(Qx,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),Ne(Qx,"overrides",{aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const n=t.data;if(n.labels.length&&n.datasets.length){const{labels:{pointStyle:r,color:s}}=t.legend.options;return n.labels.map((o,i)=>{const c=t.getDatasetMeta(0).controller.getStyle(i);return{text:o,fillStyle:c.backgroundColor,strokeStyle:c.borderColor,fontColor:s,lineWidth:c.borderWidth,pointStyle:r,hidden:!t.getDataVisibility(i),index:i}})}return[]}},onClick(t,n,r){r.chart.toggleDataVisibility(n.index),r.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}});class xM extends wf{}Ne(xM,"id","pie"),Ne(xM,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});class MS extends ti{getLabelAndValue(t){const n=this._cachedMeta.vScale,r=this.getParsed(t);return{label:n.getLabels()[t],value:""+n.getLabelForValue(r[n.axis])}}parseObjectData(t,n,r,s){return dQ.bind(this)(t,n,r,s)}update(t){const n=this._cachedMeta,r=n.dataset,s=n.data||[],o=n.iScale.getLabels();if(r.points=s,t!=="resize"){const i=this.resolveDatasetElementOptions(t);this.options.showLine||(i.borderWidth=0);const a={_loop:!0,_fullLoop:o.length===s.length,options:i};this.updateElement(r,void 0,a,t)}this.updateElements(s,0,s.length,t)}updateElements(t,n,r,s){const o=this._cachedMeta.rScale,i=s==="reset";for(let a=n;a<n+r;a++){const c=t[a],u=this.resolveDataElementOptions(a,c.active?"active":s),d=o.getPointPositionForValue(a,this.getParsed(a).r),f=i?o.xCenter:d.x,h=i?o.yCenter:d.y,p={x:f,y:h,angle:d.angle,skip:isNaN(f)||isNaN(h),options:u};this.updateElement(c,a,p,s)}}}Ne(MS,"id","radar"),Ne(MS,"defaults",{datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}}),Ne(MS,"overrides",{aspectRatio:1,scales:{r:{type:"radialLinear"}}});class AS extends ti{getLabelAndValue(t){const n=this._cachedMeta,r=this.chart.data.labels||[],{xScale:s,yScale:o}=n,i=this.getParsed(t),a=s.getLabelForValue(i.x),c=o.getLabelForValue(i.y);return{label:r[t]||"",value:"("+a+", "+c+")"}}update(t){const n=this._cachedMeta,{data:r=[]}=n,s=this.chart._animationsDisabled;let{start:o,count:i}=rQ(n,r,s);if(this._drawStart=o,this._drawCount=i,sQ(n)&&(o=0,i=r.length),this.options.showLine){this.datasetElementType||this.addElements();const{dataset:a,_dataset:c}=n;a._chart=this.chart,a._datasetIndex=this.index,a._decimated=!!c._decimated,a.points=r;const u=this.resolveDatasetElementOptions(t);u.segment=this.options.segment,this.updateElement(a,void 0,{animated:!s,options:u},t)}else this.datasetElementType&&(delete n.dataset,this.datasetElementType=!1);this.updateElements(r,o,i,t)}addElements(){const{showLine:t}=this.options;!this.datasetElementType&&t&&(this.datasetElementType=this.chart.registry.getElement("line")),super.addElements()}updateElements(t,n,r,s){const o=s==="reset",{iScale:i,vScale:a,_stacked:c,_dataset:u}=this._cachedMeta,d=this.resolveDataElementOptions(n,s),f=this.getSharedOptions(d),h=this.includeOptions(s,f),p=i.axis,g=a.axis,{spanGaps:b,segment:x}=this.options,y=fh(b)?b:Number.POSITIVE_INFINITY,S=this.chart._animationsDisabled||o||s==="none";let w=n>0&&this.getParsed(n-1);for(let C=n;C<n+r;++C){const N=t[C],k=this.getParsed(C),_=S?N:{},E=cn(k[g]),D=_[p]=i.getPixelForValue(k[p],C),j=_[g]=o||E?a.getBasePixel():a.getPixelForValue(c?this.applyStack(a,k,c):k[g],C);_.skip=isNaN(D)||isNaN(j)||E,_.stop=C>0&&Math.abs(k[p]-w[p])>y,x&&(_.parsed=k,_.raw=u.data[C]),h&&(_.options=f||this.resolveDataElementOptions(C,N.active?"active":s)),S||this.updateElement(N,C,_,s),w=k}this.updateSharedOptions(f,s,d)}getMaxOverflow(){const t=this._cachedMeta,n=t.data||[];if(!this.options.showLine){let a=0;for(let c=n.length-1;c>=0;--c)a=Math.max(a,n[c].size(this.resolveDataElementOptions(c))/2);return a>0&&a}const r=t.dataset,s=r.options&&r.options.borderWidth||0;if(!n.length)return s;const o=n[0].size(this.resolveDataElementOptions(0)),i=n[n.length-1].size(this.resolveDataElementOptions(n.length-1));return Math.max(s,o,i)/2}}Ne(AS,"id","scatter"),Ne(AS,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),Ne(AS,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});var OEe=Object.freeze({__proto__:null,BarController:qf,BubbleController:IS,DoughnutController:wf,LineController:TS,PieController:xM,PolarAreaController:Qx,RadarController:MS,ScatterController:AS});function Hd(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class fO{constructor(t){Ne(this,"options");this.options=t||{}}static override(t){Object.assign(fO.prototype,t)}init(){}formats(){return Hd()}parse(){return Hd()}format(){return Hd()}add(){return Hd()}diff(){return Hd()}startOf(){return Hd()}endOf(){return Hd()}}var LEe={_date:fO};function $Ee(e,t,n,r){const{controller:s,data:o,_sorted:i}=e,a=s._cachedMeta.iScale,c=e.dataset&&e.dataset.options?e.dataset.options.spanGaps:null;if(a&&t===a.axis&&t!=="r"&&i&&o.length){const u=a._reversePixels?aje:bc;if(r){if(s._sharedOptions){const d=o[0],f=typeof d.getRange=="function"&&d.getRange(t);if(f){const h=u(o,t,n-f),p=u(o,t,n+f);return{lo:h.lo,hi:p.hi}}}}else{const d=u(o,t,n);if(c){const{vScale:f}=s._cachedMeta,{_parsed:h}=e,p=h.slice(0,d.lo+1).reverse().findIndex(b=>!cn(b[f.axis]));d.lo-=Math.max(0,p);const g=h.slice(d.hi).findIndex(b=>!cn(b[f.axis]));d.hi+=Math.max(0,g)}return d}}return{lo:0,hi:o.length-1}}function C_(e,t,n,r,s){const o=e.getSortedVisibleDatasetMetas(),i=n[t];for(let a=0,c=o.length;a<c;++a){const{index:u,data:d}=o[a],{lo:f,hi:h}=$Ee(o[a],t,i,s);for(let p=f;p<=h;++p){const g=d[p];g.skip||r(g,u,p)}}}function zEe(e){const t=e.indexOf("x")!==-1,n=e.indexOf("y")!==-1;return function(r,s){const o=t?Math.abs(r.x-s.x):0,i=n?Math.abs(r.y-s.y):0;return Math.sqrt(Math.pow(o,2)+Math.pow(i,2))}}function vD(e,t,n,r,s){const o=[];return!s&&!e.isPointInArea(t)||C_(e,n,t,function(a,c,u){!s&&!xc(a,e.chartArea,0)||a.inRange(t.x,t.y,r)&&o.push({element:a,datasetIndex:c,index:u})},!0),o}function BEe(e,t,n,r){let s=[];function o(i,a,c){const{startAngle:u,endAngle:d}=i.getProps(["startAngle","endAngle"],r),{angle:f}=QX(i,{x:t.x,y:t.y});Hy(f,u,d)&&s.push({element:i,datasetIndex:a,index:c})}return C_(e,n,t,o),s}function VEe(e,t,n,r,s,o){let i=[];const a=zEe(n);let c=Number.POSITIVE_INFINITY;function u(d,f,h){const p=d.inRange(t.x,t.y,s);if(r&&!p)return;const g=d.getCenterPoint(s);if(!(!!o||e.isPointInArea(g))&&!p)return;const x=a(t,g);x<c?(i=[{element:d,datasetIndex:f,index:h}],c=x):x===c&&i.push({element:d,datasetIndex:f,index:h})}return C_(e,n,t,u),i}function wD(e,t,n,r,s,o){return!o&&!e.isPointInArea(t)?[]:n==="r"&&!r?BEe(e,t,n,s):VEe(e,t,n,r,s,o)}function Fz(e,t,n,r,s){const o=[],i=n==="x"?"inXRange":"inYRange";let a=!1;return C_(e,n,t,(c,u,d)=>{c[i]&&c[i](t[n],s)&&(o.push({element:c,datasetIndex:u,index:d}),a=a||c.inRange(t.x,t.y,s))}),r&&!a?[]:o}var HEe={modes:{index(e,t,n,r){const s=ef(t,e),o=n.axis||"x",i=n.includeInvisible||!1,a=n.intersect?vD(e,s,o,r,i):wD(e,s,o,!1,r,i),c=[];return a.length?(e.getSortedVisibleDatasetMetas().forEach(u=>{const d=a[0].index,f=u.data[d];f&&!f.skip&&c.push({element:f,datasetIndex:u.index,index:d})}),c):[]},dataset(e,t,n,r){const s=ef(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;let a=n.intersect?vD(e,s,o,r,i):wD(e,s,o,!1,r,i);if(a.length>0){const c=a[0].datasetIndex,u=e.getDatasetMeta(c).data;a=[];for(let d=0;d<u.length;++d)a.push({element:u[d],datasetIndex:c,index:d})}return a},point(e,t,n,r){const s=ef(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;return vD(e,s,o,r,i)},nearest(e,t,n,r){const s=ef(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;return wD(e,s,o,n.intersect,r,i)},x(e,t,n,r){const s=ef(t,e);return Fz(e,s,"x",n.intersect,r)},y(e,t,n,r){const s=ef(t,e);return Fz(e,s,"y",n.intersect,r)}}};const SQ=["left","top","right","bottom"];function Fb(e,t){return e.filter(n=>n.pos===t)}function Pz(e,t){return e.filter(n=>SQ.indexOf(n.pos)===-1&&n.box.axis===t)}function Pb(e,t){return e.sort((n,r)=>{const s=t?r:n,o=t?n:r;return s.weight===o.weight?s.index-o.index:s.weight-o.weight})}function UEe(e){const t=[];let n,r,s,o,i,a;for(n=0,r=(e||[]).length;n<r;++n)s=e[n],{position:o,options:{stack:i,stackWeight:a=1}}=s,t.push({index:n,box:s,pos:o,horizontal:s.isHorizontal(),weight:s.weight,stack:i&&o+i,stackWeight:a});return t}function WEe(e){const t={};for(const n of e){const{stack:r,pos:s,stackWeight:o}=n;if(!r||!SQ.includes(s))continue;const i=t[r]||(t[r]={count:0,placed:0,weight:0,size:0});i.count++,i.weight+=o}return t}function qEe(e,t){const n=WEe(e),{vBoxMaxWidth:r,hBoxMaxHeight:s}=t;let o,i,a;for(o=0,i=e.length;o<i;++o){a=e[o];const{fullSize:c}=a.box,u=n[a.stack],d=u&&a.stackWeight/u.weight;a.horizontal?(a.width=d?d*r:c&&t.availableWidth,a.height=s):(a.width=r,a.height=d?d*s:c&&t.availableHeight)}return n}function YEe(e){const t=UEe(e),n=Pb(t.filter(u=>u.box.fullSize),!0),r=Pb(Fb(t,"left"),!0),s=Pb(Fb(t,"right")),o=Pb(Fb(t,"top"),!0),i=Pb(Fb(t,"bottom")),a=Pz(t,"x"),c=Pz(t,"y");return{fullSize:n,leftAndTop:r.concat(o),rightAndBottom:s.concat(c).concat(i).concat(a),chartArea:Fb(t,"chartArea"),vertical:r.concat(s).concat(c),horizontal:o.concat(i).concat(a)}}function Oz(e,t,n,r){return Math.max(e[n],t[n])+Math.max(e[r],t[r])}function CQ(e,t){e.top=Math.max(e.top,t.top),e.left=Math.max(e.left,t.left),e.bottom=Math.max(e.bottom,t.bottom),e.right=Math.max(e.right,t.right)}function GEe(e,t,n,r){const{pos:s,box:o}=n,i=e.maxPadding;if(!pn(s)){n.size&&(e[s]-=n.size);const f=r[n.stack]||{size:0,count:1};f.size=Math.max(f.size,n.horizontal?o.height:o.width),n.size=f.size/f.count,e[s]+=n.size}o.getPadding&&CQ(i,o.getPadding());const a=Math.max(0,t.outerWidth-Oz(i,e,"left","right")),c=Math.max(0,t.outerHeight-Oz(i,e,"top","bottom")),u=a!==e.w,d=c!==e.h;return e.w=a,e.h=c,n.horizontal?{same:u,other:d}:{same:d,other:u}}function KEe(e){const t=e.maxPadding;function n(r){const s=Math.max(t[r]-e[r],0);return e[r]+=s,s}e.y+=n("top"),e.x+=n("left"),n("right"),n("bottom")}function ZEe(e,t){const n=t.maxPadding;function r(s){const o={left:0,top:0,right:0,bottom:0};return s.forEach(i=>{o[i]=Math.max(t[i],n[i])}),o}return r(e?["left","right"]:["top","bottom"])}function Nx(e,t,n,r){const s=[];let o,i,a,c,u,d;for(o=0,i=e.length,u=0;o<i;++o){a=e[o],c=a.box,c.update(a.width||t.w,a.height||t.h,ZEe(a.horizontal,t));const{same:f,other:h}=GEe(t,n,a,r);u|=f&&s.length,d=d||h,c.fullSize||s.push(a)}return u&&Nx(s,t,n,r)||d}function Qw(e,t,n,r,s){e.top=n,e.left=t,e.right=t+r,e.bottom=n+s,e.width=r,e.height=s}function Lz(e,t,n,r){const s=n.padding;let{x:o,y:i}=t;for(const a of e){const c=a.box,u=r[a.stack]||{placed:0,weight:1},d=a.stackWeight/u.weight||1;if(a.horizontal){const f=t.w*d,h=u.size||c.height;Um(u.start)&&(i=u.start),c.fullSize?Qw(c,s.left,i,n.outerWidth-s.right-s.left,h):Qw(c,t.left+u.placed,i,f,h),u.start=i,u.placed+=f,i=c.bottom}else{const f=t.h*d,h=u.size||c.width;Um(u.start)&&(o=u.start),c.fullSize?Qw(c,o,s.top,h,n.outerHeight-s.bottom-s.top):Qw(c,o,t.top+u.placed,h,f),u.start=o,u.placed+=f,o=c.right}}t.x=o,t.y=i}var oo={addBox(e,t){e.boxes||(e.boxes=[]),t.fullSize=t.fullSize||!1,t.position=t.position||"top",t.weight=t.weight||0,t._layers=t._layers||function(){return[{z:0,draw(n){t.draw(n)}}]},e.boxes.push(t)},removeBox(e,t){const n=e.boxes?e.boxes.indexOf(t):-1;n!==-1&&e.boxes.splice(n,1)},configure(e,t,n){t.fullSize=n.fullSize,t.position=n.position,t.weight=n.weight},update(e,t,n,r){if(!e)return;const s=Hs(e.options.layout.padding),o=Math.max(t-s.width,0),i=Math.max(n-s.height,0),a=YEe(e.boxes),c=a.vertical,u=a.horizontal;Zn(e.boxes,b=>{typeof b.beforeLayout=="function"&&b.beforeLayout()});const d=c.reduce((b,x)=>x.box.options&&x.box.options.display===!1?b:b+1,0)||1,f=Object.freeze({outerWidth:t,outerHeight:n,padding:s,availableWidth:o,availableHeight:i,vBoxMaxWidth:o/2/d,hBoxMaxHeight:i/2}),h=Object.assign({},s);CQ(h,Hs(r));const p=Object.assign({maxPadding:h,w:o,h:i,x:s.left,y:s.top},s),g=qEe(c.concat(u),f);Nx(a.fullSize,p,f,g),Nx(c,p,f,g),Nx(u,p,f,g)&&Nx(c,p,f,g),KEe(p),Lz(a.leftAndTop,p,f,g),p.x+=p.w,p.y+=p.h,Lz(a.rightAndBottom,p,f,g),e.chartArea={left:p.left,top:p.top,right:p.left+p.w,bottom:p.top+p.h,height:p.h,width:p.w},Zn(a.chartArea,b=>{const x=b.box;Object.assign(x,e.chartArea),x.update(p.w,p.h,{left:0,top:0,right:0,bottom:0})})}};class NQ{acquireContext(t,n){}releaseContext(t){return!1}addEventListener(t,n,r){}removeEventListener(t,n,r){}getDevicePixelRatio(){return 1}getMaximumSize(t,n,r,s){return n=Math.max(0,n||t.width),r=r||t.height,{width:n,height:Math.max(0,s?Math.floor(n/s):r)}}isAttached(t){return!0}updateConfig(t){}}class XEe extends NQ{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const RS="$chartjs",QEe={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},$z=e=>e===null||e==="";function JEe(e,t){const n=e.style,r=e.getAttribute("height"),s=e.getAttribute("width");if(e[RS]={initial:{height:r,width:s,style:{display:n.display,height:n.height,width:n.width}}},n.display=n.display||"block",n.boxSizing=n.boxSizing||"border-box",$z(s)){const o=Sz(e,"width");o!==void 0&&(e.width=o)}if($z(r))if(e.style.height==="")e.height=e.width/(t||2);else{const o=Sz(e,"height");o!==void 0&&(e.height=o)}return e}const kQ=eEe?{passive:!0}:!1;function eDe(e,t,n){e&&e.addEventListener(t,n,kQ)}function tDe(e,t,n){e&&e.canvas&&e.canvas.removeEventListener(t,n,kQ)}function nDe(e,t){const n=QEe[e.type]||e.type,{x:r,y:s}=ef(e,t);return{type:n,chart:t,native:e,x:r!==void 0?r:null,y:s!==void 0?s:null}}function VC(e,t){for(const n of e)if(n===t||n.contains(t))return!0}function rDe(e,t,n){const r=e.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||VC(a.addedNodes,r),i=i&&!VC(a.removedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}function sDe(e,t,n){const r=e.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||VC(a.removedNodes,r),i=i&&!VC(a.addedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}const Uy=new Map;let zz=0;function _Q(){const e=window.devicePixelRatio;e!==zz&&(zz=e,Uy.forEach((t,n)=>{n.currentDevicePixelRatio!==e&&t()}))}function oDe(e,t){Uy.size||window.addEventListener("resize",_Q),Uy.set(e,t)}function iDe(e){Uy.delete(e),Uy.size||window.removeEventListener("resize",_Q)}function aDe(e,t,n){const r=e.canvas,s=r&&dO(r);if(!s)return;const o=nQ((a,c)=>{const u=s.clientWidth;n(a,c),u<s.clientWidth&&n()},window),i=new ResizeObserver(a=>{const c=a[0],u=c.contentRect.width,d=c.contentRect.height;u===0&&d===0||o(u,d)});return i.observe(s),oDe(e,o),i}function SD(e,t,n){n&&n.disconnect(),t==="resize"&&iDe(e)}function lDe(e,t,n){const r=e.canvas,s=nQ(o=>{e.ctx!==null&&n(nDe(o,e))},e);return eDe(r,t,s),s}class cDe extends NQ{acquireContext(t,n){const r=t&&t.getContext&&t.getContext("2d");return r&&r.canvas===t?(JEe(t,n),r):null}releaseContext(t){const n=t.canvas;if(!n[RS])return!1;const r=n[RS].initial;["height","width"].forEach(o=>{const i=r[o];cn(i)?n.removeAttribute(o):n.setAttribute(o,i)});const s=r.style||{};return Object.keys(s).forEach(o=>{n.style[o]=s[o]}),n.width=n.width,delete n[RS],!0}addEventListener(t,n,r){this.removeEventListener(t,n);const s=t.$proxies||(t.$proxies={}),i={attach:rDe,detach:sDe,resize:aDe}[n]||lDe;s[n]=i(t,n,r)}removeEventListener(t,n){const r=t.$proxies||(t.$proxies={}),s=r[n];if(!s)return;({attach:SD,detach:SD,resize:SD}[n]||tDe)(t,n,s),r[n]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,n,r,s){return Jje(t,n,r,s)}isAttached(t){const n=t&&dO(t);return!!(n&&n.isConnected)}}function uDe(e){return!uO()||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas?XEe:cDe}var vS;let ra=(vS=class{constructor(){Ne(this,"x");Ne(this,"y");Ne(this,"active",!1);Ne(this,"options");Ne(this,"$animations")}tooltipPosition(t){const{x:n,y:r}=this.getProps(["x","y"],t);return{x:n,y:r}}hasValue(){return fh(this.x)&&fh(this.y)}getProps(t,n){const r=this.$animations;if(!n||!r)return this;const s={};return t.forEach(o=>{s[o]=r[o]&&r[o].active()?r[o]._to:this[o]}),s}},Ne(vS,"defaults",{}),Ne(vS,"defaultRoutes"),vS);function dDe(e,t){const n=e.options.ticks,r=fDe(e),s=Math.min(n.maxTicksLimit||r,r),o=n.major.enabled?pDe(t):[],i=o.length,a=o[0],c=o[i-1],u=[];if(i>s)return mDe(t,u,o,i/s),u;const d=hDe(o,t,s);if(i>0){let f,h;const p=i>1?Math.round((c-a)/(i-1)):null;for(Jw(t,u,d,cn(p)?0:a-p,a),f=0,h=i-1;f<h;f++)Jw(t,u,d,o[f],o[f+1]);return Jw(t,u,d,c,cn(p)?t.length:c+p),u}return Jw(t,u,d),u}function fDe(e){const t=e.options.offset,n=e._tickSize(),r=e._length/n+(t?0:1),s=e._maxLength/n;return Math.floor(Math.min(r,s))}function hDe(e,t,n){const r=gDe(e),s=t.length/n;if(!r)return Math.max(s,1);const o=nje(r);for(let i=0,a=o.length-1;i<a;i++){const c=o[i];if(c>s)return c}return Math.max(s,1)}function pDe(e){const t=[];let n,r;for(n=0,r=e.length;n<r;n++)e[n].major&&t.push(n);return t}function mDe(e,t,n,r){let s=0,o=n[0],i;for(r=Math.ceil(r),i=0;i<e.length;i++)i===o&&(t.push(e[i]),s++,o=n[s*r])}function Jw(e,t,n,r,s){const o=Yt(r,0),i=Math.min(Yt(s,e.length),e.length);let a=0,c,u,d;for(n=Math.ceil(n),s&&(c=s-r,n=c/Math.floor(c/n)),d=o;d<0;)a++,d=Math.round(o+a*n);for(u=Math.max(o,0);u<i;u++)u===d&&(t.push(e[u]),a++,d=Math.round(o+a*n))}function gDe(e){const t=e.length;let n,r;if(t<2)return!1;for(r=e[0],n=1;n<t;++n)if(e[n]-e[n-1]!==r)return!1;return r}const bDe=e=>e==="left"?"right":e==="right"?"left":e,Bz=(e,t,n)=>t==="top"||t==="left"?e[t]+n:e[t]-n,Vz=(e,t)=>Math.min(t||e,e);function Hz(e,t){const n=[],r=e.length/t,s=e.length;let o=0;for(;o<s;o+=r)n.push(e[Math.floor(o)]);return n}function xDe(e,t,n){const r=e.ticks.length,s=Math.min(t,r-1),o=e._startPixel,i=e._endPixel,a=1e-6;let c=e.getPixelForTick(s),u;if(!(n&&(r===1?u=Math.max(c-o,i-c):t===0?u=(e.getPixelForTick(1)-c)/2:u=(c-e.getPixelForTick(s-1))/2,c+=s<t?u:-u,c<o-a||c>i+a)))return c}function yDe(e,t){Zn(e,n=>{const r=n.gc,s=r.length/2;let o;if(s>t){for(o=0;o<s;++o)delete n.data[r[o]];r.splice(0,s)}})}function Ob(e){return e.drawTicks?e.tickLength:0}function Uz(e,t){if(!e.display)return 0;const n=Nr(e.font,t),r=Hs(e.padding);return(ur(e.text)?e.text.length:1)*n.lineHeight+r.height}function vDe(e,t){return jd(e,{scale:t,type:"scale"})}function wDe(e,t,n){return jd(e,{tick:n,index:t,type:"tick"})}function SDe(e,t,n){let r=rO(e);return(n&&t!=="right"||!n&&t==="right")&&(r=bDe(r)),r}function CDe(e,t,n,r){const{top:s,left:o,bottom:i,right:a,chart:c}=e,{chartArea:u,scales:d}=c;let f=0,h,p,g;const b=i-s,x=a-o;if(e.isHorizontal()){if(p=Zs(r,o,a),pn(n)){const y=Object.keys(n)[0],S=n[y];g=d[y].getPixelForValue(S)+b-t}else n==="center"?g=(u.bottom+u.top)/2+b-t:g=Bz(e,n,t);h=a-o}else{if(pn(n)){const y=Object.keys(n)[0],S=n[y];p=d[y].getPixelForValue(S)-x+t}else n==="center"?p=(u.left+u.right)/2-x+t:p=Bz(e,n,t);g=Zs(r,i,s),f=n==="left"?-ts:ts}return{titleX:p,titleY:g,maxWidth:h,rotation:f}}class Ed extends ra{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,n){return t}getUserBounds(){let{_userMin:t,_userMax:n,_suggestedMin:r,_suggestedMax:s}=this;return t=di(t,Number.POSITIVE_INFINITY),n=di(n,Number.NEGATIVE_INFINITY),r=di(r,Number.POSITIVE_INFINITY),s=di(s,Number.NEGATIVE_INFINITY),{min:di(t,r),max:di(n,s),minDefined:Zr(t),maxDefined:Zr(n)}}getMinMax(t){let{min:n,max:r,minDefined:s,maxDefined:o}=this.getUserBounds(),i;if(s&&o)return{min:n,max:r};const a=this.getMatchingVisibleMetas();for(let c=0,u=a.length;c<u;++c)i=a[c].controller.getMinMax(this,t),s||(n=Math.min(n,i.min)),o||(r=Math.max(r,i.max));return n=o&&n>r?r:n,r=s&&n>r?n:r,{min:di(n,di(r,n)),max:di(r,di(n,r))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){lr(this.options.beforeUpdate,[this])}update(t,n,r){const{beginAtZero:s,grace:o,ticks:i}=this.options,a=i.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=n,this._margins=r=Object.assign({left:0,right:0,top:0,bottom:0},r),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+r.left+r.right:this.height+r.top+r.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Tje(this,o,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const c=a<this.ticks.length;this._convertTicksToLabels(c?Hz(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),i.display&&(i.autoSkip||i.source==="auto")&&(this.ticks=dDe(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),c&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let t=this.options.reverse,n,r;this.isHorizontal()?(n=this.left,r=this.right):(n=this.top,r=this.bottom,t=!t),this._startPixel=n,this._endPixel=r,this._reversePixels=t,this._length=r-n,this._alignToPixels=this.options.alignToPixels}afterUpdate(){lr(this.options.afterUpdate,[this])}beforeSetDimensions(){lr(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){lr(this.options.afterSetDimensions,[this])}_callHooks(t){this.chart.notifyPlugins(t,this.getContext()),lr(this.options[t],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){lr(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(t){const n=this.options.ticks;let r,s,o;for(r=0,s=t.length;r<s;r++)o=t[r],o.label=lr(n.callback,[o.value,r,t],this)}afterTickToLabelConversion(){lr(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){lr(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const t=this.options,n=t.ticks,r=Vz(this.ticks.length,t.ticks.maxTicksLimit),s=n.minRotation||0,o=n.maxRotation;let i=s,a,c,u;if(!this._isVisible()||!n.display||s>=o||r<=1||!this.isHorizontal()){this.labelRotation=s;return}const d=this._getLabelSizes(),f=d.widest.width,h=d.highest.height,p=Es(this.chart.width-f,0,this.maxWidth);a=t.offset?this.maxWidth/r:p/(r-1),f+6>a&&(a=p/(r-(t.offset?.5:1)),c=this.maxHeight-Ob(t.grid)-n.padding-Uz(t.title,this.chart.options.font),u=Math.sqrt(f*f+h*h),i=tO(Math.min(Math.asin(Es((d.highest.height+6)/a,-1,1)),Math.asin(Es(c/u,-1,1))-Math.asin(Es(h/u,-1,1)))),i=Math.max(s,Math.min(o,i))),this.labelRotation=i}afterCalculateLabelRotation(){lr(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){lr(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:n,options:{ticks:r,title:s,grid:o}}=this,i=this._isVisible(),a=this.isHorizontal();if(i){const c=Uz(s,n.options.font);if(a?(t.width=this.maxWidth,t.height=Ob(o)+c):(t.height=this.maxHeight,t.width=Ob(o)+c),r.display&&this.ticks.length){const{first:u,last:d,widest:f,highest:h}=this._getLabelSizes(),p=r.padding*2,g=ma(this.labelRotation),b=Math.cos(g),x=Math.sin(g);if(a){const y=r.mirror?0:x*f.width+b*h.height;t.height=Math.min(this.maxHeight,t.height+y+p)}else{const y=r.mirror?0:b*f.width+x*h.height;t.width=Math.min(this.maxWidth,t.width+y+p)}this._calculatePadding(u,d,x,b)}}this._handleMargins(),a?(this.width=this._length=n.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=n.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,n,r,s){const{ticks:{align:o,padding:i},position:a}=this.options,c=this.labelRotation!==0,u=a!=="top"&&this.axis==="x";if(this.isHorizontal()){const d=this.getPixelForTick(0)-this.left,f=this.right-this.getPixelForTick(this.ticks.length-1);let h=0,p=0;c?u?(h=s*t.width,p=r*n.height):(h=r*t.height,p=s*n.width):o==="start"?p=n.width:o==="end"?h=t.width:o!=="inner"&&(h=t.width/2,p=n.width/2),this.paddingLeft=Math.max((h-d+i)*this.width/(this.width-d),0),this.paddingRight=Math.max((p-f+i)*this.width/(this.width-f),0)}else{let d=n.height/2,f=t.height/2;o==="start"?(d=0,f=t.height):o==="end"&&(d=n.height,f=0),this.paddingTop=d+i,this.paddingBottom=f+i}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){lr(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:n}=this.options;return n==="top"||n==="bottom"||t==="x"}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){this.beforeTickToLabelConversion(),this.generateTickLabels(t);let n,r;for(n=0,r=t.length;n<r;n++)cn(t[n].label)&&(t.splice(n,1),r--,n--);this.afterTickToLabelConversion()}_getLabelSizes(){let t=this._labelSizes;if(!t){const n=this.options.ticks.sampleSize;let r=this.ticks;n<r.length&&(r=Hz(r,n)),this._labelSizes=t=this._computeLabelSizes(r,r.length,this.options.ticks.maxTicksLimit)}return t}_computeLabelSizes(t,n,r){const{ctx:s,_longestTextCache:o}=this,i=[],a=[],c=Math.floor(n/Vz(n,r));let u=0,d=0,f,h,p,g,b,x,y,S,w,C,N;for(f=0;f<n;f+=c){if(g=t[f].label,b=this._resolveTickFontOptions(f),s.font=x=b.string,y=o[x]=o[x]||{data:{},gc:[]},S=b.lineHeight,w=C=0,!cn(g)&&!ur(g))w=$C(s,y.data,y.gc,w,g),C=S;else if(ur(g))for(h=0,p=g.length;h<p;++h)N=g[h],!cn(N)&&!ur(N)&&(w=$C(s,y.data,y.gc,w,N),C+=S);i.push(w),a.push(C),u=Math.max(w,u),d=Math.max(C,d)}yDe(o,n);const k=i.indexOf(u),_=a.indexOf(d),E=D=>({width:i[D]||0,height:a[D]||0});return{first:E(0),last:E(n-1),widest:E(k),highest:E(_),widths:i,heights:a}}getLabelForValue(t){return t}getPixelForValue(t,n){return NaN}getValueForPixel(t){}getPixelForTick(t){const n=this.ticks;return t<0||t>n.length-1?null:this.getPixelForValue(n[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const n=this._startPixel+t*this._length;return ije(this._alignToPixels?Vd(this.chart,n,0):n)}getDecimalForPixel(t){const n=(t-this._startPixel)/this._length;return this._reversePixels?1-n:n}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:n}=this;return t<0&&n<0?n:t>0&&n>0?t:0}getContext(t){const n=this.ticks||[];if(t>=0&&t<n.length){const r=n[t];return r.$context||(r.$context=wDe(this.getContext(),t,r))}return this.$context||(this.$context=vDe(this.chart.getContext(),this))}_tickSize(){const t=this.options.ticks,n=ma(this.labelRotation),r=Math.abs(Math.cos(n)),s=Math.abs(Math.sin(n)),o=this._getLabelSizes(),i=t.autoSkipPadding||0,a=o?o.widest.width+i:0,c=o?o.highest.height+i:0;return this.isHorizontal()?c*r>a*s?a/r:c/s:c*s<a*r?c/r:a/s}_isVisible(){const t=this.options.display;return t!=="auto"?!!t:this.getMatchingVisibleMetas().length>0}_computeGridLineItems(t){const n=this.axis,r=this.chart,s=this.options,{grid:o,position:i,border:a}=s,c=o.offset,u=this.isHorizontal(),f=this.ticks.length+(c?1:0),h=Ob(o),p=[],g=a.setContext(this.getContext()),b=g.display?g.width:0,x=b/2,y=function(B){return Vd(r,B,b)};let S,w,C,N,k,_,E,D,j,I,T,F;if(i==="top")S=y(this.bottom),_=this.bottom-h,D=S-x,I=y(t.top)+x,F=t.bottom;else if(i==="bottom")S=y(this.top),I=t.top,F=y(t.bottom)-x,_=S+x,D=this.top+h;else if(i==="left")S=y(this.right),k=this.right-h,E=S-x,j=y(t.left)+x,T=t.right;else if(i==="right")S=y(this.left),j=t.left,T=y(t.right)-x,k=S+x,E=this.left+h;else if(n==="x"){if(i==="center")S=y((t.top+t.bottom)/2+.5);else if(pn(i)){const B=Object.keys(i)[0],z=i[B];S=y(this.chart.scales[B].getPixelForValue(z))}I=t.top,F=t.bottom,_=S+x,D=_+h}else if(n==="y"){if(i==="center")S=y((t.left+t.right)/2);else if(pn(i)){const B=Object.keys(i)[0],z=i[B];S=y(this.chart.scales[B].getPixelForValue(z))}k=S-x,E=k-h,j=t.left,T=t.right}const P=Yt(s.ticks.maxTicksLimit,f),R=Math.max(1,Math.ceil(f/P));for(w=0;w<f;w+=R){const B=this.getContext(w),z=o.setContext(B),U=a.setContext(B),Y=z.lineWidth,O=z.color,K=U.dash||[],q=U.dashOffset,M=z.tickWidth,G=z.tickColor,L=z.tickBorderDash||[],$=z.tickBorderDashOffset;C=xDe(this,w,c),C!==void 0&&(N=Vd(r,C,Y),u?k=E=j=T=N:_=D=I=F=N,p.push({tx1:k,ty1:_,tx2:E,ty2:D,x1:j,y1:I,x2:T,y2:F,width:Y,color:O,borderDash:K,borderDashOffset:q,tickWidth:M,tickColor:G,tickBorderDash:L,tickBorderDashOffset:$}))}return this._ticksLength=f,this._borderValue=S,p}_computeLabelItems(t){const n=this.axis,r=this.options,{position:s,ticks:o}=r,i=this.isHorizontal(),a=this.ticks,{align:c,crossAlign:u,padding:d,mirror:f}=o,h=Ob(r.grid),p=h+d,g=f?-d:p,b=-ma(this.labelRotation),x=[];let y,S,w,C,N,k,_,E,D,j,I,T,F="middle";if(s==="top")k=this.bottom-g,_=this._getXAxisLabelAlignment();else if(s==="bottom")k=this.top+g,_=this._getXAxisLabelAlignment();else if(s==="left"){const R=this._getYAxisLabelAlignment(h);_=R.textAlign,N=R.x}else if(s==="right"){const R=this._getYAxisLabelAlignment(h);_=R.textAlign,N=R.x}else if(n==="x"){if(s==="center")k=(t.top+t.bottom)/2+p;else if(pn(s)){const R=Object.keys(s)[0],B=s[R];k=this.chart.scales[R].getPixelForValue(B)+p}_=this._getXAxisLabelAlignment()}else if(n==="y"){if(s==="center")N=(t.left+t.right)/2-p;else if(pn(s)){const R=Object.keys(s)[0],B=s[R];N=this.chart.scales[R].getPixelForValue(B)}_=this._getYAxisLabelAlignment(h).textAlign}n==="y"&&(c==="start"?F="top":c==="end"&&(F="bottom"));const P=this._getLabelSizes();for(y=0,S=a.length;y<S;++y){w=a[y],C=w.label;const R=o.setContext(this.getContext(y));E=this.getPixelForTick(y)+o.labelOffset,D=this._resolveTickFontOptions(y),j=D.lineHeight,I=ur(C)?C.length:1;const B=I/2,z=R.color,U=R.textStrokeColor,Y=R.textStrokeWidth;let O=_;i?(N=E,_==="inner"&&(y===S-1?O=this.options.reverse?"left":"right":y===0?O=this.options.reverse?"right":"left":O="center"),s==="top"?u==="near"||b!==0?T=-I*j+j/2:u==="center"?T=-P.highest.height/2-B*j+j:T=-P.highest.height+j/2:u==="near"||b!==0?T=j/2:u==="center"?T=P.highest.height/2-B*j:T=P.highest.height-I*j,f&&(T*=-1),b!==0&&!R.showLabelBackdrop&&(N+=j/2*Math.sin(b))):(k=E,T=(1-I)*j/2);let K;if(R.showLabelBackdrop){const q=Hs(R.backdropPadding),M=P.heights[y],G=P.widths[y];let L=T-q.top,$=0-q.left;switch(F){case"middle":L-=M/2;break;case"bottom":L-=M;break}switch(_){case"center":$-=G/2;break;case"right":$-=G;break;case"inner":y===S-1?$-=G:y>0&&($-=G/2);break}K={left:$,top:L,width:G+q.width,height:M+q.height,color:R.backdropColor}}x.push({label:C,font:D,textOffset:T,options:{rotation:b,color:z,strokeColor:U,strokeWidth:Y,textAlign:O,textBaseline:F,translation:[N,k],backdrop:K}})}return x}_getXAxisLabelAlignment(){const{position:t,ticks:n}=this.options;if(-ma(this.labelRotation))return t==="top"?"left":"right";let s="center";return n.align==="start"?s="left":n.align==="end"?s="right":n.align==="inner"&&(s="inner"),s}_getYAxisLabelAlignment(t){const{position:n,ticks:{crossAlign:r,mirror:s,padding:o}}=this.options,i=this._getLabelSizes(),a=t+o,c=i.widest.width;let u,d;return n==="left"?s?(d=this.right+o,r==="near"?u="left":r==="center"?(u="center",d+=c/2):(u="right",d+=c)):(d=this.right-a,r==="near"?u="right":r==="center"?(u="center",d-=c/2):(u="left",d=this.left)):n==="right"?s?(d=this.left+o,r==="near"?u="right":r==="center"?(u="center",d-=c/2):(u="left",d-=c)):(d=this.left+a,r==="near"?u="left":r==="center"?(u="center",d+=c/2):(u="right",d=this.right)):u="right",{textAlign:u,x:d}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,n=this.options.position;if(n==="left"||n==="right")return{top:0,left:this.left,bottom:t.height,right:this.right};if(n==="top"||n==="bottom")return{top:this.top,left:0,bottom:this.bottom,right:t.width}}drawBackground(){const{ctx:t,options:{backgroundColor:n},left:r,top:s,width:o,height:i}=this;n&&(t.save(),t.fillStyle=n,t.fillRect(r,s,o,i),t.restore())}getLineWidthForValue(t){const n=this.options.grid;if(!this._isVisible()||!n.display)return 0;const s=this.ticks.findIndex(o=>o.value===t);return s>=0?n.setContext(this.getContext(s)).lineWidth:0}drawGrid(t){const n=this.options.grid,r=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let o,i;const a=(c,u,d)=>{!d.width||!d.color||(r.save(),r.lineWidth=d.width,r.strokeStyle=d.color,r.setLineDash(d.borderDash||[]),r.lineDashOffset=d.borderDashOffset,r.beginPath(),r.moveTo(c.x,c.y),r.lineTo(u.x,u.y),r.stroke(),r.restore())};if(n.display)for(o=0,i=s.length;o<i;++o){const c=s[o];n.drawOnChartArea&&a({x:c.x1,y:c.y1},{x:c.x2,y:c.y2},c),n.drawTicks&&a({x:c.tx1,y:c.ty1},{x:c.tx2,y:c.ty2},{color:c.tickColor,width:c.tickWidth,borderDash:c.tickBorderDash,borderDashOffset:c.tickBorderDashOffset})}}drawBorder(){const{chart:t,ctx:n,options:{border:r,grid:s}}=this,o=r.setContext(this.getContext()),i=r.display?o.width:0;if(!i)return;const a=s.setContext(this.getContext(0)).lineWidth,c=this._borderValue;let u,d,f,h;this.isHorizontal()?(u=Vd(t,this.left,i)-i/2,d=Vd(t,this.right,a)+a/2,f=h=c):(f=Vd(t,this.top,i)-i/2,h=Vd(t,this.bottom,a)+a/2,u=d=c),n.save(),n.lineWidth=o.width,n.strokeStyle=o.color,n.beginPath(),n.moveTo(u,f),n.lineTo(d,h),n.stroke(),n.restore()}drawLabels(t){if(!this.options.ticks.display)return;const r=this.ctx,s=this._computeLabelArea();s&&Ku(r,s);const o=this.getLabelItems(t);for(const i of o){const a=i.options,c=i.font,u=i.label,d=i.textOffset;ph(r,u,0,d,c,a)}s&&Zu(r)}drawTitle(){const{ctx:t,options:{position:n,title:r,reverse:s}}=this;if(!r.display)return;const o=Nr(r.font),i=Hs(r.padding),a=r.align;let c=o.lineHeight/2;n==="bottom"||n==="center"||pn(n)?(c+=i.bottom,ur(r.text)&&(c+=o.lineHeight*(r.text.length-1))):c+=i.top;const{titleX:u,titleY:d,maxWidth:f,rotation:h}=CDe(this,c,n,a);ph(t,r.text,0,0,o,{color:r.color,maxWidth:f,rotation:h,textAlign:SDe(a,n,s),textBaseline:"middle",translation:[u,d]})}draw(t){this._isVisible()&&(this.drawBackground(),this.drawGrid(t),this.drawBorder(),this.drawTitle(),this.drawLabels(t))}_layers(){const t=this.options,n=t.ticks&&t.ticks.z||0,r=Yt(t.grid&&t.grid.z,-1),s=Yt(t.border&&t.border.z,0);return!this._isVisible()||this.draw!==Ed.prototype.draw?[{z:n,draw:o=>{this.draw(o)}}]:[{z:r,draw:o=>{this.drawBackground(),this.drawGrid(o),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:n,draw:o=>{this.drawLabels(o)}}]}getMatchingVisibleMetas(t){const n=this.chart.getSortedVisibleDatasetMetas(),r=this.axis+"AxisID",s=[];let o,i;for(o=0,i=n.length;o<i;++o){const a=n[o];a[r]===this.id&&(!t||a.type===t)&&s.push(a)}return s}_resolveTickFontOptions(t){const n=this.options.ticks.setContext(this.getContext(t));return Nr(n.font)}_maxDigits(){const t=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/t}}class e1{constructor(t,n,r){this.type=t,this.scope=n,this.override=r,this.items=Object.create(null)}isForType(t){return Object.prototype.isPrototypeOf.call(this.type.prototype,t.prototype)}register(t){const n=Object.getPrototypeOf(t);let r;_De(n)&&(r=this.register(n));const s=this.items,o=t.id,i=this.scope+"."+o;if(!o)throw new Error("class does not have id: "+t);return o in s||(s[o]=t,NDe(t,i,r),this.override&&Ir.override(t.id,t.overrides)),i}get(t){return this.items[t]}unregister(t){const n=this.items,r=t.id,s=this.scope;r in n&&delete n[r],s&&r in Ir[s]&&(delete Ir[s][r],this.override&&delete hh[r])}}function NDe(e,t,n){const r=as(Object.create(null),[n?Ir.get(n):{},Ir.get(t),e.defaults]);Ir.set(t,r),e.defaultRoutes&&kDe(t,e.defaultRoutes),e.descriptors&&Ir.describe(t,e.descriptors)}function kDe(e,t){Object.keys(t).forEach(n=>{const r=n.split("."),s=r.pop(),o=[e].concat(r).join("."),i=t[n].split("."),a=i.pop(),c=i.join(".");Ir.route(o,s,c,a)})}function _De(e){return"id"in e&&"defaults"in e}class jDe{constructor(){this.controllers=new e1(ti,"datasets",!0),this.elements=new e1(ra,"elements"),this.plugins=new e1(Object,"plugins"),this.scales=new e1(Ed,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,n,r){[...n].forEach(s=>{const o=r||this._getRegistryForType(s);r||o.isForType(s)||o===this.plugins&&s.id?this._exec(t,o,s):Zn(s,i=>{const a=r||this._getRegistryForType(i);this._exec(t,a,i)})})}_exec(t,n,r){const s=eO(t);lr(r["before"+s],[],r),n[t](r),lr(r["after"+s],[],r)}_getRegistryForType(t){for(let n=0;n<this._typedRegistries.length;n++){const r=this._typedRegistries[n];if(r.isForType(t))return r}return this.plugins}_get(t,n,r){const s=n.get(t);if(s===void 0)throw new Error('"'+t+'" is not a registered '+r+".");return s}}var Wr=new jDe;class EDe{constructor(){this._init=void 0}notify(t,n,r,s){if(n==="beforeInit"&&(this._init=this._createDescriptors(t,!0),this._notify(this._init,t,"install")),this._init===void 0)return;const o=s?this._descriptors(t).filter(s):this._descriptors(t),i=this._notify(o,t,n,r);return n==="afterDestroy"&&(this._notify(o,t,"stop"),this._notify(this._init,t,"uninstall"),this._init=void 0),i}_notify(t,n,r,s){s=s||{};for(const o of t){const i=o.plugin,a=i[r],c=[n,s,o.options];if(lr(a,c,i)===!1&&s.cancelable)return!1}return!0}invalidate(){cn(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(t){if(this._cache)return this._cache;const n=this._cache=this._createDescriptors(t);return this._notifyStateChanges(t),n}_createDescriptors(t,n){const r=t&&t.config,s=Yt(r.options&&r.options.plugins,{}),o=DDe(r);return s===!1&&!n?[]:TDe(t,o,s,n)}_notifyStateChanges(t){const n=this._oldCache||[],r=this._cache,s=(o,i)=>o.filter(a=>!i.some(c=>a.plugin.id===c.plugin.id));this._notify(s(n,r),t,"stop"),this._notify(s(r,n),t,"start")}}function DDe(e){const t={},n=[],r=Object.keys(Wr.plugins.items);for(let o=0;o<r.length;o++)n.push(Wr.getPlugin(r[o]));const s=e.plugins||[];for(let o=0;o<s.length;o++){const i=s[o];n.indexOf(i)===-1&&(n.push(i),t[i.id]=!0)}return{plugins:n,localIds:t}}function IDe(e,t){return!t&&e===!1?null:e===!0?{}:e}function TDe(e,{plugins:t,localIds:n},r,s){const o=[],i=e.getContext();for(const a of t){const c=a.id,u=IDe(r[c],s);u!==null&&o.push({plugin:a,options:MDe(e.config,{plugin:a,local:n[c]},u,i)})}return o}function MDe(e,{plugin:t,local:n},r,s){const o=e.pluginScopeKeys(t),i=e.getOptionScopes(r,o);return n&&t.defaults&&i.push(t.defaults),e.createResolver(i,s,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function yM(e,t){const n=Ir.datasets[e]||{};return((t.datasets||{})[e]||{}).indexAxis||t.indexAxis||n.indexAxis||"x"}function ADe(e,t){let n=e;return e==="_index_"?n=t:e==="_value_"&&(n=t==="x"?"y":"x"),n}function RDe(e,t){return e===t?"_index_":"_value_"}function Wz(e){if(e==="x"||e==="y"||e==="r")return e}function FDe(e){if(e==="top"||e==="bottom")return"x";if(e==="left"||e==="right")return"y"}function vM(e,...t){if(Wz(e))return e;for(const n of t){const r=n.axis||FDe(n.position)||e.length>1&&Wz(e[0].toLowerCase());if(r)return r}throw new Error(`Cannot determine type of '${e}' axis. Please provide 'axis' or 'position' option.`)}function qz(e,t,n){if(n[t+"AxisID"]===e)return{axis:t}}function PDe(e,t){if(t.data&&t.data.datasets){const n=t.data.datasets.filter(r=>r.xAxisID===e||r.yAxisID===e);if(n.length)return qz(e,"x",n[0])||qz(e,"y",n[0])}return{}}function ODe(e,t){const n=hh[e.type]||{scales:{}},r=t.scales||{},s=yM(e.type,t),o=Object.create(null);return Object.keys(r).forEach(i=>{const a=r[i];if(!pn(a))return console.error(`Invalid scale configuration for scale: ${i}`);if(a._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${i}`);const c=vM(i,a,PDe(i,e),Ir.scales[a.type]),u=RDe(c,s),d=n.scales||{};o[i]=Gx(Object.create(null),[{axis:c},a,d[c],d[u]])}),e.data.datasets.forEach(i=>{const a=i.type||e.type,c=i.indexAxis||yM(a,t),d=(hh[a]||{}).scales||{};Object.keys(d).forEach(f=>{const h=ADe(f,c),p=i[h+"AxisID"]||h;o[p]=o[p]||Object.create(null),Gx(o[p],[{axis:h},r[p],d[f]])})}),Object.keys(o).forEach(i=>{const a=o[i];Gx(a,[Ir.scales[a.type],Ir.scale])}),o}function jQ(e){const t=e.options||(e.options={});t.plugins=Yt(t.plugins,{}),t.scales=ODe(e,t)}function EQ(e){return e=e||{},e.datasets=e.datasets||[],e.labels=e.labels||[],e}function LDe(e){return e=e||{},e.data=EQ(e.data),jQ(e),e}const Yz=new Map,DQ=new Set;function t1(e,t){let n=Yz.get(e);return n||(n=t(),Yz.set(e,n),DQ.add(n)),n}const Lb=(e,t,n)=>{const r=nd(t,n);r!==void 0&&e.add(r)};class $De{constructor(t){this._config=LDe(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=EQ(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),jQ(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return t1(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,n){return t1(`${t}.transition.${n}`,()=>[[`datasets.${t}.transitions.${n}`,`transitions.${n}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,n){return t1(`${t}-${n}`,()=>[[`datasets.${t}.elements.${n}`,`datasets.${t}`,`elements.${n}`,""]])}pluginScopeKeys(t){const n=t.id,r=this.type;return t1(`${r}-plugin-${n}`,()=>[[`plugins.${n}`,...t.additionalOptionScopes||[]]])}_cachedScopes(t,n){const r=this._scopeCache;let s=r.get(t);return(!s||n)&&(s=new Map,r.set(t,s)),s}getOptionScopes(t,n,r){const{options:s,type:o}=this,i=this._cachedScopes(t,r),a=i.get(n);if(a)return a;const c=new Set;n.forEach(d=>{t&&(c.add(t),d.forEach(f=>Lb(c,t,f))),d.forEach(f=>Lb(c,s,f)),d.forEach(f=>Lb(c,hh[o]||{},f)),d.forEach(f=>Lb(c,Ir,f)),d.forEach(f=>Lb(c,bM,f))});const u=Array.from(c);return u.length===0&&u.push(Object.create(null)),DQ.has(n)&&i.set(n,u),u}chartOptionScopes(){const{options:t,type:n}=this;return[t,hh[n]||{},Ir.datasets[n]||{},{type:n},Ir,bM]}resolveNamedOptions(t,n,r,s=[""]){const o={$shared:!0},{resolver:i,subPrefixes:a}=Gz(this._resolverCache,t,s);let c=i;if(BDe(i,n)){o.$shared=!1,r=rd(r)?r():r;const u=this.createResolver(t,r,a);c=Wm(i,r,u)}for(const u of n)o[u]=c[u];return o}createResolver(t,n,r=[""],s){const{resolver:o}=Gz(this._resolverCache,t,r);return pn(n)?Wm(o,n,void 0,s):o}}function Gz(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));const s=n.join();let o=r.get(s);return o||(o={resolver:aO(t,n),subPrefixes:n.filter(a=>!a.toLowerCase().includes("hover"))},r.set(s,o)),o}const zDe=e=>pn(e)&&Object.getOwnPropertyNames(e).some(t=>rd(e[t]));function BDe(e,t){const{isScriptable:n,isIndexable:r}=aQ(e);for(const s of t){const o=n(s),i=r(s),a=(i||o)&&e[s];if(o&&(rd(a)||zDe(a))||i&&ur(a))return!0}return!1}var VDe="4.5.1";const HDe=["top","bottom","left","right","chartArea"];function Kz(e,t){return e==="top"||e==="bottom"||HDe.indexOf(e)===-1&&t==="x"}function Zz(e,t){return function(n,r){return n[e]===r[e]?n[t]-r[t]:n[e]-r[e]}}function Xz(e){const t=e.chart,n=t.options.animation;t.notifyPlugins("afterRender"),lr(n&&n.onComplete,[e],t)}function UDe(e){const t=e.chart,n=t.options.animation;lr(n&&n.onProgress,[e],t)}function IQ(e){return uO()&&typeof e=="string"?e=document.getElementById(e):e&&e.length&&(e=e[0]),e&&e.canvas&&(e=e.canvas),e}const FS={},Qz=e=>{const t=IQ(e);return Object.values(FS).filter(n=>n.canvas===t).pop()};function WDe(e,t,n){const r=Object.keys(e);for(const s of r){const o=+s;if(o>=t){const i=e[s];delete e[s],(n>0||o>t)&&(e[o+n]=i)}}}function qDe(e,t,n,r){return!n||e.type==="mouseout"?null:r?t:e}class Rn{static register(...t){Wr.add(...t),Jz()}static unregister(...t){Wr.remove(...t),Jz()}constructor(t,n){const r=this.config=new $De(n),s=IQ(t),o=Qz(s);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const i=r.createResolver(r.chartOptionScopes(),this.getContext());this.platform=new(r.platform||uDe(s)),this.platform.updateConfig(r);const a=this.platform.acquireContext(s,i.aspectRatio),c=a&&a.canvas,u=c&&c.height,d=c&&c.width;if(this.id=Y_e(),this.ctx=a,this.canvas=c,this.width=d,this.height=u,this._options=i,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new EDe,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=uje(f=>this.update(f),i.resizeDelay||0),this._dataChanges=[],FS[this.id]=this,!a||!c){console.error("Failed to create chart: can't acquire context from the given item");return}Ql.listen(this,"complete",Xz),Ql.listen(this,"progress",UDe),this._initialize(),this.attached&&this.update()}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:n},width:r,height:s,_aspectRatio:o}=this;return cn(t)?n&&o?o:s?r/s:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return Wr}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():wz(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return xz(this.canvas,this.ctx),this}stop(){return Ql.stop(this),this}resize(t,n){Ql.running(this)?this._resizeBeforeDraw={width:t,height:n}:this._resize(t,n)}_resize(t,n){const r=this.options,s=this.canvas,o=r.maintainAspectRatio&&this.aspectRatio,i=this.platform.getMaximumSize(s,t,n,o),a=r.devicePixelRatio||this.platform.getDevicePixelRatio(),c=this.width?"resize":"attach";this.width=i.width,this.height=i.height,this._aspectRatio=this.aspectRatio,wz(this,a,!0)&&(this.notifyPlugins("resize",{size:i}),lr(r.onResize,[this,i],this),this.attached&&this._doResize(c)&&this.render())}ensureScalesHaveIDs(){const n=this.options.scales||{};Zn(n,(r,s)=>{r.id=s})}buildOrUpdateScales(){const t=this.options,n=t.scales,r=this.scales,s=Object.keys(r).reduce((i,a)=>(i[a]=!1,i),{});let o=[];n&&(o=o.concat(Object.keys(n).map(i=>{const a=n[i],c=vM(i,a),u=c==="r",d=c==="x";return{options:a,dposition:u?"chartArea":d?"bottom":"left",dtype:u?"radialLinear":d?"category":"linear"}}))),Zn(o,i=>{const a=i.options,c=a.id,u=vM(c,a),d=Yt(a.type,i.dtype);(a.position===void 0||Kz(a.position,u)!==Kz(i.dposition))&&(a.position=i.dposition),s[c]=!0;let f=null;if(c in r&&r[c].type===d)f=r[c];else{const h=Wr.getScale(d);f=new h({id:c,type:d,ctx:this.ctx,chart:this}),r[f.id]=f}f.init(a,t)}),Zn(s,(i,a)=>{i||delete r[a]}),Zn(r,i=>{oo.configure(this,i,i.options),oo.addBox(this,i)})}_updateMetasets(){const t=this._metasets,n=this.data.datasets.length,r=t.length;if(t.sort((s,o)=>s.index-o.index),r>n){for(let s=n;s<r;++s)this._destroyDatasetMeta(s);t.splice(n,r-n)}this._sortedMetasets=t.slice(0).sort(Zz("order","index"))}_removeUnreferencedMetasets(){const{_metasets:t,data:{datasets:n}}=this;t.length>n.length&&delete this._stacks,t.forEach((r,s)=>{n.filter(o=>o===r._dataset).length===0&&this._destroyDatasetMeta(s)})}buildOrUpdateControllers(){const t=[],n=this.data.datasets;let r,s;for(this._removeUnreferencedMetasets(),r=0,s=n.length;r<s;r++){const o=n[r];let i=this.getDatasetMeta(r);const a=o.type||this.config.type;if(i.type&&i.type!==a&&(this._destroyDatasetMeta(r),i=this.getDatasetMeta(r)),i.type=a,i.indexAxis=o.indexAxis||yM(a,this.options),i.order=o.order||0,i.index=r,i.label=""+o.label,i.visible=this.isDatasetVisible(r),i.controller)i.controller.updateIndex(r),i.controller.linkScales();else{const c=Wr.getController(a),{datasetElementType:u,dataElementType:d}=Ir.datasets[a];Object.assign(c,{dataElementType:Wr.getElement(d),datasetElementType:u&&Wr.getElement(u)}),i.controller=new c(this,r),t.push(i.controller)}}return this._updateMetasets(),t}_resetElements(){Zn(this.data.datasets,(t,n)=>{this.getDatasetMeta(n).controller.reset()},this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const n=this.config;n.update();const r=this._options=n.createResolver(n.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!r.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0})===!1)return;const o=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let i=0;for(let u=0,d=this.data.datasets.length;u<d;u++){const{controller:f}=this.getDatasetMeta(u),h=!s&&o.indexOf(f)===-1;f.buildOrUpdateElements(h),i=Math.max(+f.getMaxOverflow(),i)}i=this._minPadding=r.layout.autoPadding?i:0,this._updateLayout(i),s||Zn(o,u=>{u.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(Zz("z","_idx"));const{_active:a,_lastEvent:c}=this;c?this._eventHandler(c,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){Zn(this.scales,t=>{oo.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,n=new Set(Object.keys(this._listeners)),r=new Set(t.events);(!cz(n,r)||!!this._responsiveListeners!==t.responsive)&&(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,n=this._getUniformDataChanges()||[];for(const{method:r,start:s,count:o}of n){const i=r==="_removeElements"?-o:o;WDe(t,s,i)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const n=this.data.datasets.length,r=o=>new Set(t.filter(i=>i[0]===o).map((i,a)=>a+","+i.splice(1).join(","))),s=r(0);for(let o=1;o<n;o++)if(!cz(s,r(o)))return;return Array.from(s).map(o=>o.split(",")).map(o=>({method:o[1],start:+o[2],count:+o[3]}))}_updateLayout(t){if(this.notifyPlugins("beforeLayout",{cancelable:!0})===!1)return;oo.update(this,this.width,this.height,t);const n=this.chartArea,r=n.width<=0||n.height<=0;this._layers=[],Zn(this.boxes,s=>{r&&s.position==="chartArea"||(s.configure&&s.configure(),this._layers.push(...s._layers()))},this),this._layers.forEach((s,o)=>{s._idx=o}),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})!==!1){for(let n=0,r=this.data.datasets.length;n<r;++n)this.getDatasetMeta(n).controller.configure();for(let n=0,r=this.data.datasets.length;n<r;++n)this._updateDataset(n,rd(t)?t({datasetIndex:n}):t);this.notifyPlugins("afterDatasetsUpdate",{mode:t})}}_updateDataset(t,n){const r=this.getDatasetMeta(t),s={meta:r,index:t,mode:n,cancelable:!0};this.notifyPlugins("beforeDatasetUpdate",s)!==!1&&(r.controller._update(n),s.cancelable=!1,this.notifyPlugins("afterDatasetUpdate",s))}render(){this.notifyPlugins("beforeRender",{cancelable:!0})!==!1&&(Ql.has(this)?this.attached&&!Ql.running(this)&&Ql.start(this):(this.draw(),Xz({chart:this})))}draw(){let t;if(this._resizeBeforeDraw){const{width:r,height:s}=this._resizeBeforeDraw;this._resizeBeforeDraw=null,this._resize(r,s)}if(this.clear(),this.width<=0||this.height<=0||this.notifyPlugins("beforeDraw",{cancelable:!0})===!1)return;const n=this._layers;for(t=0;t<n.length&&n[t].z<=0;++t)n[t].draw(this.chartArea);for(this._drawDatasets();t<n.length;++t)n[t].draw(this.chartArea);this.notifyPlugins("afterDraw")}_getSortedDatasetMetas(t){const n=this._sortedMetasets,r=[];let s,o;for(s=0,o=n.length;s<o;++s){const i=n[s];(!t||i.visible)&&r.push(i)}return r}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(this.notifyPlugins("beforeDatasetsDraw",{cancelable:!0})===!1)return;const t=this.getSortedVisibleDatasetMetas();for(let n=t.length-1;n>=0;--n)this._drawDataset(t[n]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const n=this.ctx,r={meta:t,index:t.index,cancelable:!0},s=xQ(this,t);this.notifyPlugins("beforeDatasetDraw",r)!==!1&&(s&&Ku(n,s),t.controller.draw(),s&&Zu(n),r.cancelable=!1,this.notifyPlugins("afterDatasetDraw",r))}isPointInArea(t){return xc(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,n,r,s){const o=HEe.modes[n];return typeof o=="function"?o(this,t,r,s):[]}getDatasetMeta(t){const n=this.data.datasets[t],r=this._metasets;let s=r.filter(o=>o&&o._dataset===n).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:n&&n.order||0,index:t,_dataset:n,_parsed:[],_sorted:!1},r.push(s)),s}getContext(){return this.$context||(this.$context=jd(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const n=this.data.datasets[t];if(!n)return!1;const r=this.getDatasetMeta(t);return typeof r.hidden=="boolean"?!r.hidden:!n.hidden}setDatasetVisibility(t,n){const r=this.getDatasetMeta(t);r.hidden=!n}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,n,r){const s=r?"show":"hide",o=this.getDatasetMeta(t),i=o.controller._resolveAnimations(void 0,s);Um(n)?(o.data[n].hidden=!r,this.update()):(this.setDatasetVisibility(t,r),i.update(o,{visible:r}),this.update(a=>a.datasetIndex===t?s:void 0))}hide(t,n){this._updateVisibility(t,n,!1)}show(t,n){this._updateVisibility(t,n,!0)}_destroyDatasetMeta(t){const n=this._metasets[t];n&&n.controller&&n.controller._destroy(),delete this._metasets[t]}_stop(){let t,n;for(this.stop(),Ql.remove(this),t=0,n=this.data.datasets.length;t<n;++t)this._destroyDatasetMeta(t)}destroy(){this.notifyPlugins("beforeDestroy");const{canvas:t,ctx:n}=this;this._stop(),this.config.clearCache(),t&&(this.unbindEvents(),xz(t,n),this.platform.releaseContext(n),this.canvas=null,this.ctx=null),delete FS[this.id],this.notifyPlugins("afterDestroy")}toBase64Image(...t){return this.canvas.toDataURL(...t)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const t=this._listeners,n=this.platform,r=(o,i)=>{n.addEventListener(this,o,i),t[o]=i},s=(o,i,a)=>{o.offsetX=i,o.offsetY=a,this._eventHandler(o)};Zn(this.options.events,o=>r(o,s))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,n=this.platform,r=(c,u)=>{n.addEventListener(this,c,u),t[c]=u},s=(c,u)=>{t[c]&&(n.removeEventListener(this,c,u),delete t[c])},o=(c,u)=>{this.canvas&&this.resize(c,u)};let i;const a=()=>{s("attach",a),this.attached=!0,this.resize(),r("resize",o),r("detach",i)};i=()=>{this.attached=!1,s("resize",o),this._stop(),this._resize(0,0),r("attach",a)},n.isAttached(this.canvas)?a():i()}unbindEvents(){Zn(this._listeners,(t,n)=>{this.platform.removeEventListener(this,n,t)}),this._listeners={},Zn(this._responsiveListeners,(t,n)=>{this.platform.removeEventListener(this,n,t)}),this._responsiveListeners=void 0}updateHoverStyle(t,n,r){const s=r?"set":"remove";let o,i,a,c;for(n==="dataset"&&(o=this.getDatasetMeta(t[0].datasetIndex),o.controller["_"+s+"DatasetHoverStyle"]()),a=0,c=t.length;a<c;++a){i=t[a];const u=i&&this.getDatasetMeta(i.datasetIndex).controller;u&&u[s+"HoverStyle"](i.element,i.datasetIndex,i.index)}}getActiveElements(){return this._active||[]}setActiveElements(t){const n=this._active||[],r=t.map(({datasetIndex:o,index:i})=>{const a=this.getDatasetMeta(o);if(!a)throw new Error("No dataset found at index "+o);return{datasetIndex:o,element:a.data[i],index:i}});!PC(r,n)&&(this._active=r,this._lastEvent=null,this._updateHoverStyles(r,n))}notifyPlugins(t,n,r){return this._plugins.notify(this,t,n,r)}isPluginEnabled(t){return this._plugins._cache.filter(n=>n.plugin.id===t).length===1}_updateHoverStyles(t,n,r){const s=this.options.hover,o=(c,u)=>c.filter(d=>!u.some(f=>d.datasetIndex===f.datasetIndex&&d.index===f.index)),i=o(n,t),a=r?t:o(t,n);i.length&&this.updateHoverStyle(i,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,n){const r={event:t,replay:n,cancelable:!0,inChartArea:this.isPointInArea(t)},s=i=>(i.options.events||this.options.events).includes(t.native.type);if(this.notifyPlugins("beforeEvent",r,s)===!1)return;const o=this._handleEvent(t,n,r.inChartArea);return r.cancelable=!1,this.notifyPlugins("afterEvent",r,s),(o||r.changed)&&this.render(),this}_handleEvent(t,n,r){const{_active:s=[],options:o}=this,i=n,a=this._getActiveElements(t,s,r,i),c=J_e(t),u=qDe(t,this._lastEvent,r,c);r&&(this._lastEvent=null,lr(o.onHover,[t,a,this],this),c&&lr(o.onClick,[t,a,this],this));const d=!PC(a,s);return(d||n)&&(this._active=a,this._updateHoverStyles(a,s,n)),this._lastEvent=u,d}_getActiveElements(t,n,r,s){if(t.type==="mouseout")return[];if(!r)return n;const o=this.options.hover;return this.getElementsAtEventForMode(t,o.mode,o,s)}}Ne(Rn,"defaults",Ir),Ne(Rn,"instances",FS),Ne(Rn,"overrides",hh),Ne(Rn,"registry",Wr),Ne(Rn,"version",VDe),Ne(Rn,"getChart",Qz);function Jz(){return Zn(Rn.instances,e=>e._plugins.invalidate())}function YDe(e,t,n){const{startAngle:r,x:s,y:o,outerRadius:i,innerRadius:a,options:c}=t,{borderWidth:u,borderJoinStyle:d}=c,f=Math.min(u/i,to(r-n));if(e.beginPath(),e.arc(s,o,i-u/2,r+f/2,n-f/2),a>0){const h=Math.min(u/a,to(r-n));e.arc(s,o,a+u/2,n-h/2,r+h/2,!0)}else{const h=Math.min(u/2,i*to(r-n));if(d==="round")e.arc(s,o,h,n-Vn/2,r+Vn/2,!0);else if(d==="bevel"){const p=2*h*h,g=-p*Math.cos(n+Vn/2)+s,b=-p*Math.sin(n+Vn/2)+o,x=p*Math.cos(r+Vn/2)+s,y=p*Math.sin(r+Vn/2)+o;e.lineTo(g,b),e.lineTo(x,y)}}e.closePath(),e.moveTo(0,0),e.rect(0,0,e.canvas.width,e.canvas.height),e.clip("evenodd")}function GDe(e,t,n){const{startAngle:r,pixelMargin:s,x:o,y:i,outerRadius:a,innerRadius:c}=t;let u=s/a;e.beginPath(),e.arc(o,i,a,r-u,n+u),c>s?(u=s/c,e.arc(o,i,c,n+u,r-u,!0)):e.arc(o,i,s,n+ts,r-ts),e.closePath(),e.clip()}function KDe(e){return oO(e,["outerStart","outerEnd","innerStart","innerEnd"])}function ZDe(e,t,n,r){const s=KDe(e.options.borderRadius),o=(n-t)/2,i=Math.min(o,r*t/2),a=c=>{const u=(n-Math.min(o,c))*r/2;return Es(c,0,Math.min(o,u))};return{outerStart:a(s.outerStart),outerEnd:a(s.outerEnd),innerStart:Es(s.innerStart,0,i),innerEnd:Es(s.innerEnd,0,i)}}function gp(e,t,n,r){return{x:n+e*Math.cos(t),y:r+e*Math.sin(t)}}function HC(e,t,n,r,s,o){const{x:i,y:a,startAngle:c,pixelMargin:u,innerRadius:d}=t,f=Math.max(t.outerRadius+r+n-u,0),h=d>0?d+r+n+u:0;let p=0;const g=s-c;if(r){const R=d>0?d-r:0,B=f>0?f-r:0,z=(R+B)/2,U=z!==0?g*z/(z+r):g;p=(g-U)/2}const b=Math.max(.001,g*f-n/Vn)/f,x=(g-b)/2,y=c+x+p,S=s-x-p,{outerStart:w,outerEnd:C,innerStart:N,innerEnd:k}=ZDe(t,h,f,S-y),_=f-w,E=f-C,D=y+w/_,j=S-C/E,I=h+N,T=h+k,F=y+N/I,P=S-k/T;if(e.beginPath(),o){const R=(D+j)/2;if(e.arc(i,a,f,D,R),e.arc(i,a,f,R,j),C>0){const Y=gp(E,j,i,a);e.arc(Y.x,Y.y,C,j,S+ts)}const B=gp(T,S,i,a);if(e.lineTo(B.x,B.y),k>0){const Y=gp(T,P,i,a);e.arc(Y.x,Y.y,k,S+ts,P+Math.PI)}const z=(S-k/h+(y+N/h))/2;if(e.arc(i,a,h,S-k/h,z,!0),e.arc(i,a,h,z,y+N/h,!0),N>0){const Y=gp(I,F,i,a);e.arc(Y.x,Y.y,N,F+Math.PI,y-ts)}const U=gp(_,y,i,a);if(e.lineTo(U.x,U.y),w>0){const Y=gp(_,D,i,a);e.arc(Y.x,Y.y,w,y-ts,D)}}else{e.moveTo(i,a);const R=Math.cos(D)*f+i,B=Math.sin(D)*f+a;e.lineTo(R,B);const z=Math.cos(j)*f+i,U=Math.sin(j)*f+a;e.lineTo(z,U)}e.closePath()}function XDe(e,t,n,r,s){const{fullCircles:o,startAngle:i,circumference:a}=t;let c=t.endAngle;if(o){HC(e,t,n,r,c,s);for(let u=0;u<o;++u)e.fill();isNaN(a)||(c=i+(a%Dr||Dr))}return HC(e,t,n,r,c,s),e.fill(),c}function QDe(e,t,n,r,s){const{fullCircles:o,startAngle:i,circumference:a,options:c}=t,{borderWidth:u,borderJoinStyle:d,borderDash:f,borderDashOffset:h,borderRadius:p}=c,g=c.borderAlign==="inner";if(!u)return;e.setLineDash(f||[]),e.lineDashOffset=h,g?(e.lineWidth=u*2,e.lineJoin=d||"round"):(e.lineWidth=u,e.lineJoin=d||"bevel");let b=t.endAngle;if(o){HC(e,t,n,r,b,s);for(let x=0;x<o;++x)e.stroke();isNaN(a)||(b=i+(a%Dr||Dr))}g&&GDe(e,t,b),c.selfJoin&&b-i>=Vn&&p===0&&d!=="miter"&&YDe(e,t,b),o||(HC(e,t,n,r,b,s),e.stroke())}class Zp extends ra{constructor(n){super();Ne(this,"circumference");Ne(this,"endAngle");Ne(this,"fullCircles");Ne(this,"innerRadius");Ne(this,"outerRadius");Ne(this,"pixelMargin");Ne(this,"startAngle");this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,n&&Object.assign(this,n)}inRange(n,r,s){const o=this.getProps(["x","y"],s),{angle:i,distance:a}=QX(o,{x:n,y:r}),{startAngle:c,endAngle:u,innerRadius:d,outerRadius:f,circumference:h}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],s),p=(this.options.spacing+this.options.borderWidth)/2,g=Yt(h,u-c),b=Hy(i,c,u)&&c!==u,x=g>=Dr||b,y=gc(a,d+p,f+p);return x&&y}getCenterPoint(n){const{x:r,y:s,startAngle:o,endAngle:i,innerRadius:a,outerRadius:c}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],n),{offset:u,spacing:d}=this.options,f=(o+i)/2,h=(a+c+d+u)/2;return{x:r+Math.cos(f)*h,y:s+Math.sin(f)*h}}tooltipPosition(n){return this.getCenterPoint(n)}draw(n){const{options:r,circumference:s}=this,o=(r.offset||0)/4,i=(r.spacing||0)/2,a=r.circular;if(this.pixelMargin=r.borderAlign==="inner"?.33:0,this.fullCircles=s>Dr?Math.floor(s/Dr):0,s===0||this.innerRadius<0||this.outerRadius<0)return;n.save();const c=(this.startAngle+this.endAngle)/2;n.translate(Math.cos(c)*o,Math.sin(c)*o);const u=1-Math.sin(Math.min(Vn,s||0)),d=o*u;n.fillStyle=r.backgroundColor,n.strokeStyle=r.borderColor,XDe(n,this,d,i,a),QDe(n,this,d,i,a),n.restore()}}Ne(Zp,"id","arc"),Ne(Zp,"defaults",{borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0,selfJoin:!1}),Ne(Zp,"defaultRoutes",{backgroundColor:"backgroundColor"}),Ne(Zp,"descriptors",{_scriptable:!0,_indexable:n=>n!=="borderDash"});function TQ(e,t,n=t){e.lineCap=Yt(n.borderCapStyle,t.borderCapStyle),e.setLineDash(Yt(n.borderDash,t.borderDash)),e.lineDashOffset=Yt(n.borderDashOffset,t.borderDashOffset),e.lineJoin=Yt(n.borderJoinStyle,t.borderJoinStyle),e.lineWidth=Yt(n.borderWidth,t.borderWidth),e.strokeStyle=Yt(n.borderColor,t.borderColor)}function JDe(e,t,n){e.lineTo(n.x,n.y)}function eIe(e){return e.stepped?Sje:e.tension||e.cubicInterpolationMode==="monotone"?Cje:JDe}function MQ(e,t,n={}){const r=e.length,{start:s=0,end:o=r-1}=n,{start:i,end:a}=t,c=Math.max(s,i),u=Math.min(o,a),d=s<i&&o<i||s>a&&o>a;return{count:r,start:c,loop:t.loop,ilen:u<c&&!d?r+u-c:u-c}}function tIe(e,t,n,r){const{points:s,options:o}=t,{count:i,start:a,loop:c,ilen:u}=MQ(s,n,r),d=eIe(o);let{move:f=!0,reverse:h}=r||{},p,g,b;for(p=0;p<=u;++p)g=s[(a+(h?u-p:p))%i],!g.skip&&(f?(e.moveTo(g.x,g.y),f=!1):d(e,b,g,h,o.stepped),b=g);return c&&(g=s[(a+(h?u:0))%i],d(e,b,g,h,o.stepped)),!!c}function nIe(e,t,n,r){const s=t.points,{count:o,start:i,ilen:a}=MQ(s,n,r),{move:c=!0,reverse:u}=r||{};let d=0,f=0,h,p,g,b,x,y;const S=C=>(i+(u?a-C:C))%o,w=()=>{b!==x&&(e.lineTo(d,x),e.lineTo(d,b),e.lineTo(d,y))};for(c&&(p=s[S(0)],e.moveTo(p.x,p.y)),h=0;h<=a;++h){if(p=s[S(h)],p.skip)continue;const C=p.x,N=p.y,k=C|0;k===g?(N<b?b=N:N>x&&(x=N),d=(f*d+C)/++f):(w(),e.lineTo(C,N),g=k,f=0,b=x=N),y=N}w()}function wM(e){const t=e.options,n=t.borderDash&&t.borderDash.length;return!e._decimated&&!e._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!n?nIe:tIe}function rIe(e){return e.stepped?tEe:e.tension||e.cubicInterpolationMode==="monotone"?nEe:tf}function sIe(e,t,n,r){let s=t._path;s||(s=t._path=new Path2D,t.path(s,n,r)&&s.closePath()),TQ(e,t.options),e.stroke(s)}function oIe(e,t,n,r){const{segments:s,options:o}=t,i=wM(t);for(const a of s)TQ(e,o,a.style),e.beginPath(),i(e,t,a,{start:n,end:n+r-1})&&e.closePath(),e.stroke()}const iIe=typeof Path2D=="function";function aIe(e,t,n,r){iIe&&!t.options.segment?sIe(e,t,n,r):oIe(e,t,n,r)}class Ru extends ra{constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,n){const r=this.options;if((r.tension||r.cubicInterpolationMode==="monotone")&&!r.stepped&&!this._pointsUpdated){const s=r.spanGaps?this._loop:this._fullLoop;Yje(this._points,r,t,s,n),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=lEe(this,this.options.segment))}first(){const t=this.segments,n=this.points;return t.length&&n[t[0].start]}last(){const t=this.segments,n=this.points,r=t.length;return r&&n[t[r-1].end]}interpolate(t,n){const r=this.options,s=t[n],o=this.points,i=bQ(this,{property:n,start:s,end:s});if(!i.length)return;const a=[],c=rIe(r);let u,d;for(u=0,d=i.length;u<d;++u){const{start:f,end:h}=i[u],p=o[f],g=o[h];if(p===g){a.push(p);continue}const b=Math.abs((s-p[n])/(g[n]-p[n])),x=c(p,g,b,r.stepped);x[n]=t[n],a.push(x)}return a.length===1?a[0]:a}pathSegment(t,n,r){return wM(this)(t,this,n,r)}path(t,n,r){const s=this.segments,o=wM(this);let i=this._loop;n=n||0,r=r||this.points.length-n;for(const a of s)i&=o(t,this,a,{start:n,end:n+r-1});return!!i}draw(t,n,r,s){const o=this.options||{};(this.points||[]).length&&o.borderWidth&&(t.save(),aIe(t,this,r,s),t.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}Ne(Ru,"id","line"),Ne(Ru,"defaults",{borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0}),Ne(Ru,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"}),Ne(Ru,"descriptors",{_scriptable:!0,_indexable:t=>t!=="borderDash"&&t!=="fill"});function e6(e,t,n,r){const s=e.options,{[n]:o}=e.getProps([n],r);return Math.abs(t-o)<s.radius+s.hitRadius}class Yf extends ra{constructor(n){super();Ne(this,"parsed");Ne(this,"skip");Ne(this,"stop");this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,n&&Object.assign(this,n)}inRange(n,r,s){const o=this.options,{x:i,y:a}=this.getProps(["x","y"],s);return Math.pow(n-i,2)+Math.pow(r-a,2)<Math.pow(o.hitRadius+o.radius,2)}inXRange(n,r){return e6(this,n,"x",r)}inYRange(n,r){return e6(this,n,"y",r)}getCenterPoint(n){const{x:r,y:s}=this.getProps(["x","y"],n);return{x:r,y:s}}size(n){n=n||this.options||{};let r=n.radius||0;r=Math.max(r,r&&n.hoverRadius||0);const s=r&&n.borderWidth||0;return(r+s)*2}draw(n,r){const s=this.options;this.skip||s.radius<.1||!xc(this,r,this.size(s)/2)||(n.strokeStyle=s.borderColor,n.lineWidth=s.borderWidth,n.fillStyle=s.backgroundColor,zC(n,s,this.x,this.y))}getRange(){const n=this.options||{};return n.radius+n.hitRadius}}Ne(Yf,"id","point"),Ne(Yf,"defaults",{borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0}),Ne(Yf,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});function AQ(e,t){const{x:n,y:r,base:s,width:o,height:i}=e.getProps(["x","y","base","width","height"],t);let a,c,u,d,f;return e.horizontal?(f=i/2,a=Math.min(n,s),c=Math.max(n,s),u=r-f,d=r+f):(f=o/2,a=n-f,c=n+f,u=Math.min(r,s),d=Math.max(r,s)),{left:a,top:u,right:c,bottom:d}}function Fu(e,t,n,r){return e?0:Es(t,n,r)}function lIe(e,t,n){const r=e.options.borderWidth,s=e.borderSkipped,o=iO(r);return{t:Fu(s.top,o.top,0,n),r:Fu(s.right,o.right,0,t),b:Fu(s.bottom,o.bottom,0,n),l:Fu(s.left,o.left,0,t)}}function cIe(e,t,n){const{enableBorderRadius:r}=e.getProps(["enableBorderRadius"]),s=e.options.borderRadius,o=Ic(s),i=Math.min(t,n),a=e.borderSkipped,c=r||pn(s);return{topLeft:Fu(!c||a.top||a.left,o.topLeft,0,i),topRight:Fu(!c||a.top||a.right,o.topRight,0,i),bottomLeft:Fu(!c||a.bottom||a.left,o.bottomLeft,0,i),bottomRight:Fu(!c||a.bottom||a.right,o.bottomRight,0,i)}}function uIe(e){const t=AQ(e),n=t.right-t.left,r=t.bottom-t.top,s=lIe(e,n/2,r/2),o=cIe(e,n/2,r/2);return{outer:{x:t.left,y:t.top,w:n,h:r,radius:o},inner:{x:t.left+s.l,y:t.top+s.t,w:n-s.l-s.r,h:r-s.t-s.b,radius:{topLeft:Math.max(0,o.topLeft-Math.max(s.t,s.l)),topRight:Math.max(0,o.topRight-Math.max(s.t,s.r)),bottomLeft:Math.max(0,o.bottomLeft-Math.max(s.b,s.l)),bottomRight:Math.max(0,o.bottomRight-Math.max(s.b,s.r))}}}}function CD(e,t,n,r){const s=t===null,o=n===null,a=e&&!(s&&o)&&AQ(e,r);return a&&(s||gc(t,a.left,a.right))&&(o||gc(n,a.top,a.bottom))}function dIe(e){return e.topLeft||e.topRight||e.bottomLeft||e.bottomRight}function fIe(e,t){e.rect(t.x,t.y,t.w,t.h)}function ND(e,t,n={}){const r=e.x!==n.x?-t:0,s=e.y!==n.y?-t:0,o=(e.x+e.w!==n.x+n.w?t:0)-r,i=(e.y+e.h!==n.y+n.h?t:0)-s;return{x:e.x+r,y:e.y+s,w:e.w+o,h:e.h+i,radius:e.radius}}class ul extends ra{constructor(t){super(),this.options=void 0,this.horizontal=void 0,this.base=void 0,this.width=void 0,this.height=void 0,this.inflateAmount=void 0,t&&Object.assign(this,t)}draw(t){const{inflateAmount:n,options:{borderColor:r,backgroundColor:s}}=this,{inner:o,outer:i}=uIe(this),a=dIe(i.radius)?Dc:fIe;t.save(),(i.w!==o.w||i.h!==o.h)&&(t.beginPath(),a(t,ND(i,n,o)),t.clip(),a(t,ND(o,-n,i)),t.fillStyle=r,t.fill("evenodd")),t.beginPath(),a(t,ND(o,n)),t.fillStyle=s,t.fill(),t.restore()}inRange(t,n,r){return CD(this,t,n,r)}inXRange(t,n){return CD(this,t,null,n)}inYRange(t,n){return CD(this,null,t,n)}getCenterPoint(t){const{x:n,y:r,base:s,horizontal:o}=this.getProps(["x","y","base","horizontal"],t);return{x:o?(n+s)/2:n,y:o?r:(r+s)/2}}getRange(t){return t==="x"?this.width/2:this.height/2}}Ne(ul,"id","bar"),Ne(ul,"defaults",{borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0}),Ne(ul,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});var hIe=Object.freeze({__proto__:null,ArcElement:Zp,BarElement:ul,LineElement:Ru,PointElement:Yf});const SM=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],t6=SM.map(e=>e.replace("rgb(","rgba(").replace(")",", 0.5)"));function RQ(e){return SM[e%SM.length]}function FQ(e){return t6[e%t6.length]}function pIe(e,t){return e.borderColor=RQ(t),e.backgroundColor=FQ(t),++t}function mIe(e,t){return e.backgroundColor=e.data.map(()=>RQ(t++)),t}function gIe(e,t){return e.backgroundColor=e.data.map(()=>FQ(t++)),t}function bIe(e){let t=0;return(n,r)=>{const s=e.getDatasetMeta(r).controller;s instanceof wf?t=mIe(n,t):s instanceof Qx?t=gIe(n,t):s&&(t=pIe(n,t))}}function n6(e){let t;for(t in e)if(e[t].borderColor||e[t].backgroundColor)return!0;return!1}function xIe(e){return e&&(e.borderColor||e.backgroundColor)}function yIe(){return Ir.borderColor!=="rgba(0,0,0,0.1)"||Ir.backgroundColor!=="rgba(0,0,0,0.1)"}var vIe={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(e,t,n){if(!n.enabled)return;const{data:{datasets:r},options:s}=e.config,{elements:o}=s,i=n6(r)||xIe(s)||o&&n6(o)||yIe();if(!n.forceOverride&&i)return;const a=bIe(e);r.forEach(a)}};function wIe(e,t,n,r,s){const o=s.samples||r;if(o>=n)return e.slice(t,t+n);const i=[],a=(n-2)/(o-2);let c=0;const u=t+n-1;let d=t,f,h,p,g,b;for(i[c++]=e[d],f=0;f<o-2;f++){let x=0,y=0,S;const w=Math.floor((f+1)*a)+1+t,C=Math.min(Math.floor((f+2)*a)+1,n)+t,N=C-w;for(S=w;S<C;S++)x+=e[S].x,y+=e[S].y;x/=N,y/=N;const k=Math.floor(f*a)+1+t,_=Math.min(Math.floor((f+1)*a)+1,n)+t,{x:E,y:D}=e[d];for(p=g=-1,S=k;S<_;S++)g=.5*Math.abs((E-x)*(e[S].y-D)-(E-e[S].x)*(y-D)),g>p&&(p=g,h=e[S],b=S);i[c++]=h,d=b}return i[c++]=e[u],i}function SIe(e,t,n,r){let s=0,o=0,i,a,c,u,d,f,h,p,g,b;const x=[],y=t+n-1,S=e[t].x,C=e[y].x-S;for(i=t;i<t+n;++i){a=e[i],c=(a.x-S)/C*r,u=a.y;const N=c|0;if(N===d)u<g?(g=u,f=i):u>b&&(b=u,h=i),s=(o*s+a.x)/++o;else{const k=i-1;if(!cn(f)&&!cn(h)){const _=Math.min(f,h),E=Math.max(f,h);_!==p&&_!==k&&x.push({...e[_],x:s}),E!==p&&E!==k&&x.push({...e[E],x:s})}i>0&&k!==p&&x.push(e[k]),x.push(a),d=N,o=0,g=b=u,f=h=p=i}}return x}function PQ(e){if(e._decimated){const t=e._data;delete e._decimated,delete e._data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,writable:!0,value:t})}}function r6(e){e.data.datasets.forEach(t=>{PQ(t)})}function CIe(e,t){const n=t.length;let r=0,s;const{iScale:o}=e,{min:i,max:a,minDefined:c,maxDefined:u}=o.getUserBounds();return c&&(r=Es(bc(t,o.axis,i).lo,0,n-1)),u?s=Es(bc(t,o.axis,a).hi+1,r,n)-r:s=n-r,{start:r,count:s}}var NIe={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(e,t,n)=>{if(!n.enabled){r6(e);return}const r=e.width;e.data.datasets.forEach((s,o)=>{const{_data:i,indexAxis:a}=s,c=e.getDatasetMeta(o),u=i||s.data;if(Er([a,e.options.indexAxis])==="y"||!c.controller.supportsDecimation)return;const d=e.scales[c.xAxisID];if(d.type!=="linear"&&d.type!=="time"||e.options.parsing)return;let{start:f,count:h}=CIe(c,u);const p=n.threshold||4*r;if(h<=p){PQ(s);return}cn(i)&&(s._data=u,delete s.data,Object.defineProperty(s,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(b){this._data=b}}));let g;switch(n.algorithm){case"lttb":g=wIe(u,f,h,r,n);break;case"min-max":g=SIe(u,f,h,r);break;default:throw new Error(`Unsupported decimation algorithm '${n.algorithm}'`)}s._decimated=g})},destroy(e){r6(e)}};function kIe(e,t,n){const r=e.segments,s=e.points,o=t.points,i=[];for(const a of r){let{start:c,end:u}=a;u=N_(c,u,s);const d=CM(n,s[c],s[u],a.loop);if(!t.segments){i.push({source:a,target:d,start:s[c],end:s[u]});continue}const f=bQ(t,d);for(const h of f){const p=CM(n,o[h.start],o[h.end],h.loop),g=gQ(a,s,p);for(const b of g)i.push({source:b,target:h,start:{[n]:s6(d,p,"start",Math.max)},end:{[n]:s6(d,p,"end",Math.min)}})}}return i}function CM(e,t,n,r){if(r)return;let s=t[e],o=n[e];return e==="angle"&&(s=to(s),o=to(o)),{property:e,start:s,end:o}}function _Ie(e,t){const{x:n=null,y:r=null}=e||{},s=t.points,o=[];return t.segments.forEach(({start:i,end:a})=>{a=N_(i,a,s);const c=s[i],u=s[a];r!==null?(o.push({x:c.x,y:r}),o.push({x:u.x,y:r})):n!==null&&(o.push({x:n,y:c.y}),o.push({x:n,y:u.y}))}),o}function N_(e,t,n){for(;t>e;t--){const r=n[t];if(!isNaN(r.x)&&!isNaN(r.y))break}return t}function s6(e,t,n,r){return e&&t?r(e[n],t[n]):e?e[n]:t?t[n]:0}function OQ(e,t){let n=[],r=!1;return ur(e)?(r=!0,n=e):n=_Ie(e,t),n.length?new Ru({points:n,options:{tension:0},_loop:r,_fullLoop:r}):null}function o6(e){return e&&e.fill!==!1}function jIe(e,t,n){let s=e[t].fill;const o=[t];let i;if(!n)return s;for(;s!==!1&&o.indexOf(s)===-1;){if(!Zr(s))return s;if(i=e[s],!i)return!1;if(i.visible)return s;o.push(s),s=i.fill}return!1}function EIe(e,t,n){const r=MIe(e);if(pn(r))return isNaN(r.value)?!1:r;let s=parseFloat(r);return Zr(s)&&Math.floor(s)===s?DIe(r[0],t,s,n):["origin","start","end","stack","shape"].indexOf(r)>=0&&r}function DIe(e,t,n,r){return(e==="-"||e==="+")&&(n=t+n),n===t||n<0||n>=r?!1:n}function IIe(e,t){let n=null;return e==="start"?n=t.bottom:e==="end"?n=t.top:pn(e)?n=t.getPixelForValue(e.value):t.getBasePixel&&(n=t.getBasePixel()),n}function TIe(e,t,n){let r;return e==="start"?r=n:e==="end"?r=t.options.reverse?t.min:t.max:pn(e)?r=e.value:r=t.getBaseValue(),r}function MIe(e){const t=e.options,n=t.fill;let r=Yt(n&&n.target,n);return r===void 0&&(r=!!t.backgroundColor),r===!1||r===null?!1:r===!0?"origin":r}function AIe(e){const{scale:t,index:n,line:r}=e,s=[],o=r.segments,i=r.points,a=RIe(t,n);a.push(OQ({x:null,y:t.bottom},r));for(let c=0;c<o.length;c++){const u=o[c];for(let d=u.start;d<=u.end;d++)FIe(s,i[d],a)}return new Ru({points:s,options:{}})}function RIe(e,t){const n=[],r=e.getMatchingVisibleMetas("line");for(let s=0;s<r.length;s++){const o=r[s];if(o.index===t)break;o.hidden||n.unshift(o.dataset)}return n}function FIe(e,t,n){const r=[];for(let s=0;s<n.length;s++){const o=n[s],{first:i,last:a,point:c}=PIe(o,t,"x");if(!(!c||i&&a)){if(i)r.unshift(c);else if(e.push(c),!a)break}}e.push(...r)}function PIe(e,t,n){const r=e.interpolate(t,n);if(!r)return{};const s=r[n],o=e.segments,i=e.points;let a=!1,c=!1;for(let u=0;u<o.length;u++){const d=o[u],f=i[d.start][n],h=i[d.end][n];if(gc(s,f,h)){a=s===f,c=s===h;break}}return{first:a,last:c,point:r}}class LQ{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,n,r){const{x:s,y:o,radius:i}=this;return n=n||{start:0,end:Dr},t.arc(s,o,i,n.end,n.start,!0),!r.bounds}interpolate(t){const{x:n,y:r,radius:s}=this,o=t.angle;return{x:n+Math.cos(o)*s,y:r+Math.sin(o)*s,angle:o}}}function OIe(e){const{chart:t,fill:n,line:r}=e;if(Zr(n))return LIe(t,n);if(n==="stack")return AIe(e);if(n==="shape")return!0;const s=$Ie(e);return s instanceof LQ?s:OQ(s,r)}function LIe(e,t){const n=e.getDatasetMeta(t);return n&&e.isDatasetVisible(t)?n.dataset:null}function $Ie(e){return(e.scale||{}).getPointPositionForValue?BIe(e):zIe(e)}function zIe(e){const{scale:t={},fill:n}=e,r=IIe(n,t);if(Zr(r)){const s=t.isHorizontal();return{x:s?r:null,y:s?null:r}}return null}function BIe(e){const{scale:t,fill:n}=e,r=t.options,s=t.getLabels().length,o=r.reverse?t.max:t.min,i=TIe(n,t,o),a=[];if(r.grid.circular){const c=t.getPointPositionForValue(0,o);return new LQ({x:c.x,y:c.y,radius:t.getDistanceFromCenterForValue(i)})}for(let c=0;c<s;++c)a.push(t.getPointPositionForValue(c,i));return a}function kD(e,t,n){const r=OIe(t),{chart:s,index:o,line:i,scale:a,axis:c}=t,u=i.options,d=u.fill,f=u.backgroundColor,{above:h=f,below:p=f}=d||{},g=s.getDatasetMeta(o),b=xQ(s,g);r&&i.points.length&&(Ku(e,n),VIe(e,{line:i,target:r,above:h,below:p,area:n,scale:a,axis:c,clip:b}),Zu(e))}function VIe(e,t){const{line:n,target:r,above:s,below:o,area:i,scale:a,clip:c}=t,u=n._loop?"angle":t.axis;e.save();let d=o;o!==s&&(u==="x"?(i6(e,r,i.top),_D(e,{line:n,target:r,color:s,scale:a,property:u,clip:c}),e.restore(),e.save(),i6(e,r,i.bottom)):u==="y"&&(a6(e,r,i.left),_D(e,{line:n,target:r,color:o,scale:a,property:u,clip:c}),e.restore(),e.save(),a6(e,r,i.right),d=s)),_D(e,{line:n,target:r,color:d,scale:a,property:u,clip:c}),e.restore()}function i6(e,t,n){const{segments:r,points:s}=t;let o=!0,i=!1;e.beginPath();for(const a of r){const{start:c,end:u}=a,d=s[c],f=s[N_(c,u,s)];o?(e.moveTo(d.x,d.y),o=!1):(e.lineTo(d.x,n),e.lineTo(d.x,d.y)),i=!!t.pathSegment(e,a,{move:i}),i?e.closePath():e.lineTo(f.x,n)}e.lineTo(t.first().x,n),e.closePath(),e.clip()}function a6(e,t,n){const{segments:r,points:s}=t;let o=!0,i=!1;e.beginPath();for(const a of r){const{start:c,end:u}=a,d=s[c],f=s[N_(c,u,s)];o?(e.moveTo(d.x,d.y),o=!1):(e.lineTo(n,d.y),e.lineTo(d.x,d.y)),i=!!t.pathSegment(e,a,{move:i}),i?e.closePath():e.lineTo(n,f.y)}e.lineTo(n,t.first().y),e.closePath(),e.clip()}function _D(e,t){const{line:n,target:r,property:s,color:o,scale:i,clip:a}=t,c=kIe(n,r,s);for(const{source:u,target:d,start:f,end:h}of c){const{style:{backgroundColor:p=o}={}}=u,g=r!==!0;e.save(),e.fillStyle=p,HIe(e,i,a,g&&CM(s,f,h)),e.beginPath();const b=!!n.pathSegment(e,u);let x;if(g){b?e.closePath():l6(e,r,h,s);const y=!!r.pathSegment(e,d,{move:b,reverse:!0});x=b&&y,x||l6(e,r,f,s)}e.closePath(),e.fill(x?"evenodd":"nonzero"),e.restore()}}function HIe(e,t,n,r){const s=t.chart.chartArea,{property:o,start:i,end:a}=r||{};if(o==="x"||o==="y"){let c,u,d,f;o==="x"?(c=i,u=s.top,d=a,f=s.bottom):(c=s.left,u=i,d=s.right,f=a),e.beginPath(),n&&(c=Math.max(c,n.left),d=Math.min(d,n.right),u=Math.max(u,n.top),f=Math.min(f,n.bottom)),e.rect(c,u,d-c,f-u),e.clip()}}function l6(e,t,n,r){const s=t.interpolate(n,r);s&&e.lineTo(s.x,s.y)}var UIe={id:"filler",afterDatasetsUpdate(e,t,n){const r=(e.data.datasets||[]).length,s=[];let o,i,a,c;for(i=0;i<r;++i)o=e.getDatasetMeta(i),a=o.dataset,c=null,a&&a.options&&a instanceof Ru&&(c={visible:e.isDatasetVisible(i),index:i,fill:EIe(a,i,r),chart:e,axis:o.controller.options.indexAxis,scale:o.vScale,line:a}),o.$filler=c,s.push(c);for(i=0;i<r;++i)c=s[i],!(!c||c.fill===!1)&&(c.fill=jIe(s,i,n.propagate))},beforeDraw(e,t,n){const r=n.drawTime==="beforeDraw",s=e.getSortedVisibleDatasetMetas(),o=e.chartArea;for(let i=s.length-1;i>=0;--i){const a=s[i].$filler;a&&(a.line.updateControlPoints(o,a.axis),r&&a.fill&&kD(e.ctx,a,o))}},beforeDatasetsDraw(e,t,n){if(n.drawTime!=="beforeDatasetsDraw")return;const r=e.getSortedVisibleDatasetMetas();for(let s=r.length-1;s>=0;--s){const o=r[s].$filler;o6(o)&&kD(e.ctx,o,e.chartArea)}},beforeDatasetDraw(e,t,n){const r=t.meta.$filler;!o6(r)||n.drawTime!=="beforeDatasetDraw"||kD(e.ctx,r,e.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const c6=(e,t)=>{let{boxHeight:n=t,boxWidth:r=t}=e;return e.usePointStyle&&(n=Math.min(n,t),r=e.pointStyleWidth||Math.min(r,t)),{boxWidth:r,boxHeight:n,itemHeight:Math.max(t,n)}},WIe=(e,t)=>e!==null&&t!==null&&e.datasetIndex===t.datasetIndex&&e.index===t.index;class u6 extends ra{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,n,r){this.maxWidth=t,this.maxHeight=n,this._margins=r,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let n=lr(t.generateLabels,[this.chart],this)||[];t.filter&&(n=n.filter(r=>t.filter(r,this.chart.data))),t.sort&&(n=n.sort((r,s)=>t.sort(r,s,this.chart.data))),this.options.reverse&&n.reverse(),this.legendItems=n}fit(){const{options:t,ctx:n}=this;if(!t.display){this.width=this.height=0;return}const r=t.labels,s=Nr(r.font),o=s.size,i=this._computeTitleHeight(),{boxWidth:a,itemHeight:c}=c6(r,o);let u,d;n.font=s.string,this.isHorizontal()?(u=this.maxWidth,d=this._fitRows(i,o,a,c)+10):(d=this.maxHeight,u=this._fitCols(i,s,a,c)+10),this.width=Math.min(u,t.maxWidth||this.maxWidth),this.height=Math.min(d,t.maxHeight||this.maxHeight)}_fitRows(t,n,r,s){const{ctx:o,maxWidth:i,options:{labels:{padding:a}}}=this,c=this.legendHitBoxes=[],u=this.lineWidths=[0],d=s+a;let f=t;o.textAlign="left",o.textBaseline="middle";let h=-1,p=-d;return this.legendItems.forEach((g,b)=>{const x=r+n/2+o.measureText(g.text).width;(b===0||u[u.length-1]+x+2*a>i)&&(f+=d,u[u.length-(b>0?0:1)]=0,p+=d,h++),c[b]={left:0,top:p,row:h,width:x,height:s},u[u.length-1]+=x+a}),f}_fitCols(t,n,r,s){const{ctx:o,maxHeight:i,options:{labels:{padding:a}}}=this,c=this.legendHitBoxes=[],u=this.columnSizes=[],d=i-t;let f=a,h=0,p=0,g=0,b=0;return this.legendItems.forEach((x,y)=>{const{itemWidth:S,itemHeight:w}=qIe(r,n,o,x,s);y>0&&p+w+2*a>d&&(f+=h+a,u.push({width:h,height:p}),g+=h+a,b++,h=p=0),c[y]={left:g,top:p,col:b,width:S,height:w},h=Math.max(h,S),p+=w+a}),f+=h,u.push({width:h,height:p}),f}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:n,options:{align:r,labels:{padding:s},rtl:o}}=this,i=im(o,this.left,this.width);if(this.isHorizontal()){let a=0,c=Zs(r,this.left+s,this.right-this.lineWidths[a]);for(const u of n)a!==u.row&&(a=u.row,c=Zs(r,this.left+s,this.right-this.lineWidths[a])),u.top+=this.top+t+s,u.left=i.leftForLtr(i.x(c),u.width),c+=u.width+s}else{let a=0,c=Zs(r,this.top+t+s,this.bottom-this.columnSizes[a].height);for(const u of n)u.col!==a&&(a=u.col,c=Zs(r,this.top+t+s,this.bottom-this.columnSizes[a].height)),u.top=c,u.left+=this.left+s,u.left=i.leftForLtr(i.x(u.left),u.width),c+=u.height+s}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){const t=this.ctx;Ku(t,this),this._draw(),Zu(t)}}_draw(){const{options:t,columnSizes:n,lineWidths:r,ctx:s}=this,{align:o,labels:i}=t,a=Ir.color,c=im(t.rtl,this.left,this.width),u=Nr(i.font),{padding:d}=i,f=u.size,h=f/2;let p;this.drawTitle(),s.textAlign=c.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=u.string;const{boxWidth:g,boxHeight:b,itemHeight:x}=c6(i,f),y=function(k,_,E){if(isNaN(g)||g<=0||isNaN(b)||b<0)return;s.save();const D=Yt(E.lineWidth,1);if(s.fillStyle=Yt(E.fillStyle,a),s.lineCap=Yt(E.lineCap,"butt"),s.lineDashOffset=Yt(E.lineDashOffset,0),s.lineJoin=Yt(E.lineJoin,"miter"),s.lineWidth=D,s.strokeStyle=Yt(E.strokeStyle,a),s.setLineDash(Yt(E.lineDash,[])),i.usePointStyle){const j={radius:b*Math.SQRT2/2,pointStyle:E.pointStyle,rotation:E.rotation,borderWidth:D},I=c.xPlus(k,g/2),T=_+h;iQ(s,j,I,T,i.pointStyleWidth&&g)}else{const j=_+Math.max((f-b)/2,0),I=c.leftForLtr(k,g),T=Ic(E.borderRadius);s.beginPath(),Object.values(T).some(F=>F!==0)?Dc(s,{x:I,y:j,w:g,h:b,radius:T}):s.rect(I,j,g,b),s.fill(),D!==0&&s.stroke()}s.restore()},S=function(k,_,E){ph(s,E.text,k,_+x/2,u,{strikethrough:E.hidden,textAlign:c.textAlign(E.textAlign)})},w=this.isHorizontal(),C=this._computeTitleHeight();w?p={x:Zs(o,this.left+d,this.right-r[0]),y:this.top+d+C,line:0}:p={x:this.left+d,y:Zs(o,this.top+C+d,this.bottom-n[0].height),line:0},hQ(this.ctx,t.textDirection);const N=x+d;this.legendItems.forEach((k,_)=>{s.strokeStyle=k.fontColor,s.fillStyle=k.fontColor;const E=s.measureText(k.text).width,D=c.textAlign(k.textAlign||(k.textAlign=i.textAlign)),j=g+h+E;let I=p.x,T=p.y;c.setWidth(this.width),w?_>0&&I+j+d>this.right&&(T=p.y+=N,p.line++,I=p.x=Zs(o,this.left+d,this.right-r[p.line])):_>0&&T+N>this.bottom&&(I=p.x=I+n[p.line].width+d,p.line++,T=p.y=Zs(o,this.top+C+d,this.bottom-n[p.line].height));const F=c.x(I);if(y(F,T,k),I=dje(D,I+g+h,w?I+j:this.right,t.rtl),S(c.x(I),T,k),w)p.x+=j+d;else if(typeof k.text!="string"){const P=u.lineHeight;p.y+=$Q(k,P)+d}else p.y+=N}),pQ(this.ctx,t.textDirection)}drawTitle(){const t=this.options,n=t.title,r=Nr(n.font),s=Hs(n.padding);if(!n.display)return;const o=im(t.rtl,this.left,this.width),i=this.ctx,a=n.position,c=r.size/2,u=s.top+c;let d,f=this.left,h=this.width;if(this.isHorizontal())h=Math.max(...this.lineWidths),d=this.top+u,f=Zs(t.align,f,this.right-h);else{const g=this.columnSizes.reduce((b,x)=>Math.max(b,x.height),0);d=u+Zs(t.align,this.top,this.bottom-g-t.labels.padding-this._computeTitleHeight())}const p=Zs(a,f,f+h);i.textAlign=o.textAlign(rO(a)),i.textBaseline="middle",i.strokeStyle=n.color,i.fillStyle=n.color,i.font=r.string,ph(i,n.text,p,d,r)}_computeTitleHeight(){const t=this.options.title,n=Nr(t.font),r=Hs(t.padding);return t.display?n.lineHeight+r.height:0}_getLegendItemAt(t,n){let r,s,o;if(gc(t,this.left,this.right)&&gc(n,this.top,this.bottom)){for(o=this.legendHitBoxes,r=0;r<o.length;++r)if(s=o[r],gc(t,s.left,s.left+s.width)&&gc(n,s.top,s.top+s.height))return this.legendItems[r]}return null}handleEvent(t){const n=this.options;if(!KIe(t.type,n))return;const r=this._getLegendItemAt(t.x,t.y);if(t.type==="mousemove"||t.type==="mouseout"){const s=this._hoveredItem,o=WIe(s,r);s&&!o&&lr(n.onLeave,[t,s,this],this),this._hoveredItem=r,r&&!o&&lr(n.onHover,[t,r,this],this)}else r&&lr(n.onClick,[t,r,this],this)}}function qIe(e,t,n,r,s){const o=YIe(r,e,t,n),i=GIe(s,r,t.lineHeight);return{itemWidth:o,itemHeight:i}}function YIe(e,t,n,r){let s=e.text;return s&&typeof s!="string"&&(s=s.reduce((o,i)=>o.length>i.length?o:i)),t+n.size/2+r.measureText(s).width}function GIe(e,t,n){let r=e;return typeof t.text!="string"&&(r=$Q(t,n)),r}function $Q(e,t){const n=e.text?e.text.length:0;return t*n}function KIe(e,t){return!!((e==="mousemove"||e==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(e==="click"||e==="mouseup"))}var ZIe={id:"legend",_element:u6,start(e,t,n){const r=e.legend=new u6({ctx:e.ctx,options:n,chart:e});oo.configure(e,r,n),oo.addBox(e,r)},stop(e){oo.removeBox(e,e.legend),delete e.legend},beforeUpdate(e,t,n){const r=e.legend;oo.configure(e,r,n),r.options=n},afterUpdate(e){const t=e.legend;t.buildLabels(),t.adjustHitBoxes()},afterEvent(e,t){t.replay||e.legend.handleEvent(t.event)},defaults:{display:!0,position:"top",align:"center",fullSize:!0,reverse:!1,weight:1e3,onClick(e,t,n){const r=t.datasetIndex,s=n.chart;s.isDatasetVisible(r)?(s.hide(r),t.hidden=!0):(s.show(r),t.hidden=!1)},onHover:null,onLeave:null,labels:{color:e=>e.chart.options.color,boxWidth:40,padding:10,generateLabels(e){const t=e.data.datasets,{labels:{usePointStyle:n,pointStyle:r,textAlign:s,color:o,useBorderRadius:i,borderRadius:a}}=e.legend.options;return e._getSortedDatasetMetas().map(c=>{const u=c.controller.getStyle(n?0:void 0),d=Hs(u.borderWidth);return{text:t[c.index].label,fillStyle:u.backgroundColor,fontColor:o,hidden:!c.visible,lineCap:u.borderCapStyle,lineDash:u.borderDash,lineDashOffset:u.borderDashOffset,lineJoin:u.borderJoinStyle,lineWidth:(d.width+d.height)/4,strokeStyle:u.borderColor,pointStyle:r||u.pointStyle,rotation:u.rotation,textAlign:s||u.textAlign,borderRadius:i&&(a||u.borderRadius),datasetIndex:c.index}},this)}},title:{color:e=>e.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:e=>!e.startsWith("on"),labels:{_scriptable:e=>!["generateLabels","filter","sort"].includes(e)}}};class hO extends ra{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,n){const r=this.options;if(this.left=0,this.top=0,!r.display){this.width=this.height=this.right=this.bottom=0;return}this.width=this.right=t,this.height=this.bottom=n;const s=ur(r.text)?r.text.length:1;this._padding=Hs(r.padding);const o=s*Nr(r.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return t==="top"||t==="bottom"}_drawArgs(t){const{top:n,left:r,bottom:s,right:o,options:i}=this,a=i.align;let c=0,u,d,f;return this.isHorizontal()?(d=Zs(a,r,o),f=n+t,u=o-r):(i.position==="left"?(d=r+t,f=Zs(a,s,n),c=Vn*-.5):(d=o-t,f=Zs(a,n,s),c=Vn*.5),u=s-n),{titleX:d,titleY:f,maxWidth:u,rotation:c}}draw(){const t=this.ctx,n=this.options;if(!n.display)return;const r=Nr(n.font),o=r.lineHeight/2+this._padding.top,{titleX:i,titleY:a,maxWidth:c,rotation:u}=this._drawArgs(o);ph(t,n.text,0,0,r,{color:n.color,maxWidth:c,rotation:u,textAlign:rO(n.align),textBaseline:"middle",translation:[i,a]})}}function XIe(e,t){const n=new hO({ctx:e.ctx,options:t,chart:e});oo.configure(e,n,t),oo.addBox(e,n),e.titleBlock=n}var QIe={id:"title",_element:hO,start(e,t,n){XIe(e,n)},stop(e){const t=e.titleBlock;oo.removeBox(e,t),delete e.titleBlock},beforeUpdate(e,t,n){const r=e.titleBlock;oo.configure(e,r,n),r.options=n},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const n1=new WeakMap;var JIe={id:"subtitle",start(e,t,n){const r=new hO({ctx:e.ctx,options:n,chart:e});oo.configure(e,r,n),oo.addBox(e,r),n1.set(e,r)},stop(e){oo.removeBox(e,n1.get(e)),n1.delete(e)},beforeUpdate(e,t,n){const r=n1.get(e);oo.configure(e,r,n),r.options=n},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const kx={average(e){if(!e.length)return!1;let t,n,r=new Set,s=0,o=0;for(t=0,n=e.length;t<n;++t){const a=e[t].element;if(a&&a.hasValue()){const c=a.tooltipPosition();r.add(c.x),s+=c.y,++o}}return o===0||r.size===0?!1:{x:[...r].reduce((a,c)=>a+c)/r.size,y:s/o}},nearest(e,t){if(!e.length)return!1;let n=t.x,r=t.y,s=Number.POSITIVE_INFINITY,o,i,a;for(o=0,i=e.length;o<i;++o){const c=e[o].element;if(c&&c.hasValue()){const u=c.getCenterPoint(),d=gM(t,u);d<s&&(s=d,a=c)}}if(a){const c=a.tooltipPosition();n=c.x,r=c.y}return{x:n,y:r}}};function Ua(e,t){return t&&(ur(t)?Array.prototype.push.apply(e,t):e.push(t)),e}function Jl(e){return(typeof e=="string"||e instanceof String)&&e.indexOf(`
812
812
  `)>-1?e.split(`
813
813
  `):e}function eTe(e,t){const{element:n,datasetIndex:r,index:s}=t,o=e.getDatasetMeta(r).controller,{label:i,value:a}=o.getLabelAndValue(s);return{chart:e,label:i,parsed:o.getParsed(s),raw:e.data.datasets[r].data[s],formattedValue:a,dataset:o.getDataset(),dataIndex:s,datasetIndex:r,element:n}}function d6(e,t){const n=e.chart.ctx,{body:r,footer:s,title:o}=e,{boxWidth:i,boxHeight:a}=t,c=Nr(t.bodyFont),u=Nr(t.titleFont),d=Nr(t.footerFont),f=o.length,h=s.length,p=r.length,g=Hs(t.padding);let b=g.height,x=0,y=r.reduce((C,N)=>C+N.before.length+N.lines.length+N.after.length,0);if(y+=e.beforeBody.length+e.afterBody.length,f&&(b+=f*u.lineHeight+(f-1)*t.titleSpacing+t.titleMarginBottom),y){const C=t.displayColors?Math.max(a,c.lineHeight):c.lineHeight;b+=p*C+(y-p)*c.lineHeight+(y-1)*t.bodySpacing}h&&(b+=t.footerMarginTop+h*d.lineHeight+(h-1)*t.footerSpacing);let S=0;const w=function(C){x=Math.max(x,n.measureText(C).width+S)};return n.save(),n.font=u.string,Zn(e.title,w),n.font=c.string,Zn(e.beforeBody.concat(e.afterBody),w),S=t.displayColors?i+2+t.boxPadding:0,Zn(r,C=>{Zn(C.before,w),Zn(C.lines,w),Zn(C.after,w)}),S=0,n.font=d.string,Zn(e.footer,w),n.restore(),x+=g.width,{width:x,height:b}}function tTe(e,t){const{y:n,height:r}=t;return n<r/2?"top":n>e.height-r/2?"bottom":"center"}function nTe(e,t,n,r){const{x:s,width:o}=r,i=n.caretSize+n.caretPadding;if(e==="left"&&s+o+i>t.width||e==="right"&&s-o-i<0)return!0}function rTe(e,t,n,r){const{x:s,width:o}=n,{width:i,chartArea:{left:a,right:c}}=e;let u="center";return r==="center"?u=s<=(a+c)/2?"left":"right":s<=o/2?u="left":s>=i-o/2&&(u="right"),nTe(u,e,t,n)&&(u="center"),u}function f6(e,t,n){const r=n.yAlign||t.yAlign||tTe(e,n);return{xAlign:n.xAlign||t.xAlign||rTe(e,t,n,r),yAlign:r}}function sTe(e,t){let{x:n,width:r}=e;return t==="right"?n-=r:t==="center"&&(n-=r/2),n}function oTe(e,t,n){let{y:r,height:s}=e;return t==="top"?r+=n:t==="bottom"?r-=s+n:r-=s/2,r}function h6(e,t,n,r){const{caretSize:s,caretPadding:o,cornerRadius:i}=e,{xAlign:a,yAlign:c}=n,u=s+o,{topLeft:d,topRight:f,bottomLeft:h,bottomRight:p}=Ic(i);let g=sTe(t,a);const b=oTe(t,c,u);return c==="center"?a==="left"?g+=u:a==="right"&&(g-=u):a==="left"?g-=Math.max(d,h)+s:a==="right"&&(g+=Math.max(f,p)+s),{x:Es(g,0,r.width-t.width),y:Es(b,0,r.height-t.height)}}function r1(e,t,n){const r=Hs(n.padding);return t==="center"?e.x+e.width/2:t==="right"?e.x+e.width-r.right:e.x+r.left}function p6(e){return Ua([],Jl(e))}function iTe(e,t,n){return jd(e,{tooltip:t,tooltipItems:n,type:"tooltip"})}function m6(e,t){const n=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return n?e.override(n):e}const zQ={beforeTitle:Yl,title(e){if(e.length>0){const t=e[0],n=t.chart.data.labels,r=n?n.length:0;if(this&&this.options&&this.options.mode==="dataset")return t.dataset.label||"";if(t.label)return t.label;if(r>0&&t.dataIndex<r)return n[t.dataIndex]}return""},afterTitle:Yl,beforeBody:Yl,beforeLabel:Yl,label(e){if(this&&this.options&&this.options.mode==="dataset")return e.label+": "+e.formattedValue||e.formattedValue;let t=e.dataset.label||"";t&&(t+=": ");const n=e.formattedValue;return cn(n)||(t+=n),t},labelColor(e){const n=e.chart.getDatasetMeta(e.datasetIndex).controller.getStyle(e.dataIndex);return{borderColor:n.borderColor,backgroundColor:n.backgroundColor,borderWidth:n.borderWidth,borderDash:n.borderDash,borderDashOffset:n.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(e){const n=e.chart.getDatasetMeta(e.datasetIndex).controller.getStyle(e.dataIndex);return{pointStyle:n.pointStyle,rotation:n.rotation}},afterLabel:Yl,afterBody:Yl,beforeFooter:Yl,footer:Yl,afterFooter:Yl};function Bo(e,t,n,r){const s=e[t].call(n,r);return typeof s>"u"?zQ[t].call(n,r):s}class NM extends ra{constructor(t){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=t.chart,this.options=t.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(t){this.options=t,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const t=this._cachedAnimations;if(t)return t;const n=this.chart,r=this.options.setContext(this.getContext()),s=r.enabled&&n.options.animation&&r.animations,o=new yQ(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(o)),o}getContext(){return this.$context||(this.$context=iTe(this.chart.getContext(),this,this._tooltipItems))}getTitle(t,n){const{callbacks:r}=n,s=Bo(r,"beforeTitle",this,t),o=Bo(r,"title",this,t),i=Bo(r,"afterTitle",this,t);let a=[];return a=Ua(a,Jl(s)),a=Ua(a,Jl(o)),a=Ua(a,Jl(i)),a}getBeforeBody(t,n){return p6(Bo(n.callbacks,"beforeBody",this,t))}getBody(t,n){const{callbacks:r}=n,s=[];return Zn(t,o=>{const i={before:[],lines:[],after:[]},a=m6(r,o);Ua(i.before,Jl(Bo(a,"beforeLabel",this,o))),Ua(i.lines,Bo(a,"label",this,o)),Ua(i.after,Jl(Bo(a,"afterLabel",this,o))),s.push(i)}),s}getAfterBody(t,n){return p6(Bo(n.callbacks,"afterBody",this,t))}getFooter(t,n){const{callbacks:r}=n,s=Bo(r,"beforeFooter",this,t),o=Bo(r,"footer",this,t),i=Bo(r,"afterFooter",this,t);let a=[];return a=Ua(a,Jl(s)),a=Ua(a,Jl(o)),a=Ua(a,Jl(i)),a}_createItems(t){const n=this._active,r=this.chart.data,s=[],o=[],i=[];let a=[],c,u;for(c=0,u=n.length;c<u;++c)a.push(eTe(this.chart,n[c]));return t.filter&&(a=a.filter((d,f,h)=>t.filter(d,f,h,r))),t.itemSort&&(a=a.sort((d,f)=>t.itemSort(d,f,r))),Zn(a,d=>{const f=m6(t.callbacks,d);s.push(Bo(f,"labelColor",this,d)),o.push(Bo(f,"labelPointStyle",this,d)),i.push(Bo(f,"labelTextColor",this,d))}),this.labelColors=s,this.labelPointStyles=o,this.labelTextColors=i,this.dataPoints=a,a}update(t,n){const r=this.options.setContext(this.getContext()),s=this._active;let o,i=[];if(!s.length)this.opacity!==0&&(o={opacity:0});else{const a=kx[r.position].call(this,s,this._eventPosition);i=this._createItems(r),this.title=this.getTitle(i,r),this.beforeBody=this.getBeforeBody(i,r),this.body=this.getBody(i,r),this.afterBody=this.getAfterBody(i,r),this.footer=this.getFooter(i,r);const c=this._size=d6(this,r),u=Object.assign({},a,c),d=f6(this.chart,r,u),f=h6(r,u,d,this.chart);this.xAlign=d.xAlign,this.yAlign=d.yAlign,o={opacity:1,x:f.x,y:f.y,width:c.width,height:c.height,caretX:a.x,caretY:a.y}}this._tooltipItems=i,this.$context=void 0,o&&this._resolveAnimations().update(this,o),t&&r.external&&r.external.call(this,{chart:this.chart,tooltip:this,replay:n})}drawCaret(t,n,r,s){const o=this.getCaretPosition(t,r,s);n.lineTo(o.x1,o.y1),n.lineTo(o.x2,o.y2),n.lineTo(o.x3,o.y3)}getCaretPosition(t,n,r){const{xAlign:s,yAlign:o}=this,{caretSize:i,cornerRadius:a}=r,{topLeft:c,topRight:u,bottomLeft:d,bottomRight:f}=Ic(a),{x:h,y:p}=t,{width:g,height:b}=n;let x,y,S,w,C,N;return o==="center"?(C=p+b/2,s==="left"?(x=h,y=x-i,w=C+i,N=C-i):(x=h+g,y=x+i,w=C-i,N=C+i),S=x):(s==="left"?y=h+Math.max(c,d)+i:s==="right"?y=h+g-Math.max(u,f)-i:y=this.caretX,o==="top"?(w=p,C=w-i,x=y-i,S=y+i):(w=p+b,C=w+i,x=y+i,S=y-i),N=w),{x1:x,x2:y,x3:S,y1:w,y2:C,y3:N}}drawTitle(t,n,r){const s=this.title,o=s.length;let i,a,c;if(o){const u=im(r.rtl,this.x,this.width);for(t.x=r1(this,r.titleAlign,r),n.textAlign=u.textAlign(r.titleAlign),n.textBaseline="middle",i=Nr(r.titleFont),a=r.titleSpacing,n.fillStyle=r.titleColor,n.font=i.string,c=0;c<o;++c)n.fillText(s[c],u.x(t.x),t.y+i.lineHeight/2),t.y+=i.lineHeight+a,c+1===o&&(t.y+=r.titleMarginBottom-a)}}_drawColorBox(t,n,r,s,o){const i=this.labelColors[r],a=this.labelPointStyles[r],{boxHeight:c,boxWidth:u}=o,d=Nr(o.bodyFont),f=r1(this,"left",o),h=s.x(f),p=c<d.lineHeight?(d.lineHeight-c)/2:0,g=n.y+p;if(o.usePointStyle){const b={radius:Math.min(u,c)/2,pointStyle:a.pointStyle,rotation:a.rotation,borderWidth:1},x=s.leftForLtr(h,u)+u/2,y=g+c/2;t.strokeStyle=o.multiKeyBackground,t.fillStyle=o.multiKeyBackground,zC(t,b,x,y),t.strokeStyle=i.borderColor,t.fillStyle=i.backgroundColor,zC(t,b,x,y)}else{t.lineWidth=pn(i.borderWidth)?Math.max(...Object.values(i.borderWidth)):i.borderWidth||1,t.strokeStyle=i.borderColor,t.setLineDash(i.borderDash||[]),t.lineDashOffset=i.borderDashOffset||0;const b=s.leftForLtr(h,u),x=s.leftForLtr(s.xPlus(h,1),u-2),y=Ic(i.borderRadius);Object.values(y).some(S=>S!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,Dc(t,{x:b,y:g,w:u,h:c,radius:y}),t.fill(),t.stroke(),t.fillStyle=i.backgroundColor,t.beginPath(),Dc(t,{x,y:g+1,w:u-2,h:c-2,radius:y}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(b,g,u,c),t.strokeRect(b,g,u,c),t.fillStyle=i.backgroundColor,t.fillRect(x,g+1,u-2,c-2))}t.fillStyle=this.labelTextColors[r]}drawBody(t,n,r){const{body:s}=this,{bodySpacing:o,bodyAlign:i,displayColors:a,boxHeight:c,boxWidth:u,boxPadding:d}=r,f=Nr(r.bodyFont);let h=f.lineHeight,p=0;const g=im(r.rtl,this.x,this.width),b=function(E){n.fillText(E,g.x(t.x+p),t.y+h/2),t.y+=h+o},x=g.textAlign(i);let y,S,w,C,N,k,_;for(n.textAlign=i,n.textBaseline="middle",n.font=f.string,t.x=r1(this,x,r),n.fillStyle=r.bodyColor,Zn(this.beforeBody,b),p=a&&x!=="right"?i==="center"?u/2+d:u+2+d:0,C=0,k=s.length;C<k;++C){for(y=s[C],S=this.labelTextColors[C],n.fillStyle=S,Zn(y.before,b),w=y.lines,a&&w.length&&(this._drawColorBox(n,t,C,g,r),h=Math.max(f.lineHeight,c)),N=0,_=w.length;N<_;++N)b(w[N]),h=f.lineHeight;Zn(y.after,b)}p=0,h=f.lineHeight,Zn(this.afterBody,b),t.y-=o}drawFooter(t,n,r){const s=this.footer,o=s.length;let i,a;if(o){const c=im(r.rtl,this.x,this.width);for(t.x=r1(this,r.footerAlign,r),t.y+=r.footerMarginTop,n.textAlign=c.textAlign(r.footerAlign),n.textBaseline="middle",i=Nr(r.footerFont),n.fillStyle=r.footerColor,n.font=i.string,a=0;a<o;++a)n.fillText(s[a],c.x(t.x),t.y+i.lineHeight/2),t.y+=i.lineHeight+r.footerSpacing}}drawBackground(t,n,r,s){const{xAlign:o,yAlign:i}=this,{x:a,y:c}=t,{width:u,height:d}=r,{topLeft:f,topRight:h,bottomLeft:p,bottomRight:g}=Ic(s.cornerRadius);n.fillStyle=s.backgroundColor,n.strokeStyle=s.borderColor,n.lineWidth=s.borderWidth,n.beginPath(),n.moveTo(a+f,c),i==="top"&&this.drawCaret(t,n,r,s),n.lineTo(a+u-h,c),n.quadraticCurveTo(a+u,c,a+u,c+h),i==="center"&&o==="right"&&this.drawCaret(t,n,r,s),n.lineTo(a+u,c+d-g),n.quadraticCurveTo(a+u,c+d,a+u-g,c+d),i==="bottom"&&this.drawCaret(t,n,r,s),n.lineTo(a+p,c+d),n.quadraticCurveTo(a,c+d,a,c+d-p),i==="center"&&o==="left"&&this.drawCaret(t,n,r,s),n.lineTo(a,c+f),n.quadraticCurveTo(a,c,a+f,c),n.closePath(),n.fill(),s.borderWidth>0&&n.stroke()}_updateAnimationTarget(t){const n=this.chart,r=this.$animations,s=r&&r.x,o=r&&r.y;if(s||o){const i=kx[t.position].call(this,this._active,this._eventPosition);if(!i)return;const a=this._size=d6(this,t),c=Object.assign({},i,this._size),u=f6(n,t,c),d=h6(t,c,u,n);(s._to!==d.x||o._to!==d.y)&&(this.xAlign=u.xAlign,this.yAlign=u.yAlign,this.width=a.width,this.height=a.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,d))}}_willRender(){return!!this.opacity}draw(t){const n=this.options.setContext(this.getContext());let r=this.opacity;if(!r)return;this._updateAnimationTarget(n);const s={width:this.width,height:this.height},o={x:this.x,y:this.y};r=Math.abs(r)<.001?0:r;const i=Hs(n.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;n.enabled&&a&&(t.save(),t.globalAlpha=r,this.drawBackground(o,t,s,n),hQ(t,n.textDirection),o.y+=i.top,this.drawTitle(o,t,n),this.drawBody(o,t,n),this.drawFooter(o,t,n),pQ(t,n.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,n){const r=this._active,s=t.map(({datasetIndex:a,index:c})=>{const u=this.chart.getDatasetMeta(a);if(!u)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:u.data[c],index:c}}),o=!PC(r,s),i=this._positionChanged(s,n);(o||i)&&(this._active=s,this._eventPosition=n,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,n,r=!0){if(n&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,o=this._active||[],i=this._getActiveElements(t,o,n,r),a=this._positionChanged(i,t),c=n||!PC(i,o)||a;return c&&(this._active=i,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,n))),c}_getActiveElements(t,n,r,s){const o=this.options;if(t.type==="mouseout")return[];if(!s)return n.filter(a=>this.chart.data.datasets[a.datasetIndex]&&this.chart.getDatasetMeta(a.datasetIndex).controller.getParsed(a.index)!==void 0);const i=this.chart.getElementsAtEventForMode(t,o.mode,o,r);return o.reverse&&i.reverse(),i}_positionChanged(t,n){const{caretX:r,caretY:s,options:o}=this,i=kx[o.position].call(this,t,n);return i!==!1&&(r!==i.x||s!==i.y)}}Ne(NM,"positioners",kx);var BQ={id:"tooltip",_element:NM,positioners:kx,afterInit(e,t,n){n&&(e.tooltip=new NM({chart:e,options:n}))},beforeUpdate(e,t,n){e.tooltip&&e.tooltip.initialize(n)},reset(e,t,n){e.tooltip&&e.tooltip.initialize(n)},afterDraw(e){const t=e.tooltip;if(t&&t._willRender()){const n={tooltip:t};if(e.notifyPlugins("beforeTooltipDraw",{...n,cancelable:!0})===!1)return;t.draw(e.ctx),e.notifyPlugins("afterTooltipDraw",n)}},afterEvent(e,t){if(e.tooltip){const n=t.replay;e.tooltip.handleEvent(t.event,n,t.inChartArea)&&(t.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(e,t)=>t.bodyFont.size,boxWidth:(e,t)=>t.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:zQ},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:e=>e!=="filter"&&e!=="itemSort"&&e!=="external",_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]},aTe=Object.freeze({__proto__:null,Colors:vIe,Decimation:NIe,Filler:UIe,Legend:ZIe,SubTitle:JIe,Title:QIe,Tooltip:BQ});const lTe=(e,t,n,r)=>(typeof t=="string"?(n=e.push(t)-1,r.unshift({index:n,label:t})):isNaN(t)&&(n=null),n);function cTe(e,t,n,r){const s=e.indexOf(t);if(s===-1)return lTe(e,t,n,r);const o=e.lastIndexOf(t);return s!==o?n:s}const uTe=(e,t)=>e===null?null:Es(Math.round(e),0,t);function g6(e){const t=this.getLabels();return e>=0&&e<t.length?t[e]:e}class Wy extends Ed{constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const n=this._addedLabels;if(n.length){const r=this.getLabels();for(const{index:s,label:o}of n)r[s]===o&&r.splice(s,1);this._addedLabels=[]}super.init(t)}parse(t,n){if(cn(t))return null;const r=this.getLabels();return n=isFinite(n)&&r[n]===t?n:cTe(r,t,Yt(n,t),this._addedLabels),uTe(n,r.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:n}=this.getUserBounds();let{min:r,max:s}=this.getMinMax(!0);this.options.bounds==="ticks"&&(t||(r=0),n||(s=this.getLabels().length-1)),this.min=r,this.max=s}buildTicks(){const t=this.min,n=this.max,r=this.options.offset,s=[];let o=this.getLabels();o=t===0&&n===o.length-1?o:o.slice(t,n+1),this._valueRange=Math.max(o.length-(r?0:1),1),this._startValue=this.min-(r?.5:0);for(let i=t;i<=n;i++)s.push({value:i});return s}getLabelForValue(t){return g6.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return typeof t!="number"&&(t=this.parse(t)),t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const n=this.ticks;return t<0||t>n.length-1?null:this.getPixelForValue(n[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}}Ne(Wy,"id","category"),Ne(Wy,"defaults",{ticks:{callback:g6}});function dTe(e,t){const n=[],{bounds:s,step:o,min:i,max:a,precision:c,count:u,maxTicks:d,maxDigits:f,includeBounds:h}=e,p=o||1,g=d-1,{min:b,max:x}=t,y=!cn(i),S=!cn(a),w=!cn(u),C=(x-b)/(f+1);let N=dz((x-b)/g/p)*p,k,_,E,D;if(N<1e-14&&!y&&!S)return[{value:b},{value:x}];D=Math.ceil(x/N)-Math.floor(b/N),D>g&&(N=dz(D*N/g/p)*p),cn(c)||(k=Math.pow(10,c),N=Math.ceil(N*k)/k),s==="ticks"?(_=Math.floor(b/N)*N,E=Math.ceil(x/N)*N):(_=b,E=x),y&&S&&o&&sje((a-i)/o,N/1e3)?(D=Math.round(Math.min((a-i)/N,d)),N=(a-i)/D,_=i,E=a):w?(_=y?i:_,E=S?a:E,D=u-1,N=(E-_)/D):(D=(E-_)/N,Kx(D,Math.round(D),N/1e3)?D=Math.round(D):D=Math.ceil(D));const j=Math.max(fz(N),fz(_));k=Math.pow(10,cn(c)?j:c),_=Math.round(_*k)/k,E=Math.round(E*k)/k;let I=0;for(y&&(h&&_!==i?(n.push({value:i}),_<i&&I++,Kx(Math.round((_+I*N)*k)/k,i,b6(i,C,e))&&I++):_<i&&I++);I<D;++I){const T=Math.round((_+I*N)*k)/k;if(S&&T>a)break;n.push({value:T})}return S&&h&&E!==a?n.length&&Kx(n[n.length-1].value,a,b6(a,C,e))?n[n.length-1].value=a:n.push({value:a}):(!S||E===a)&&n.push({value:E}),n}function b6(e,t,{horizontal:n,minRotation:r}){const s=ma(r),o=(n?Math.sin(s):Math.cos(s))||.001,i=.75*t*(""+e).length;return Math.min(t/o,i)}class UC extends Ed{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,n){return cn(t)||(typeof t=="number"||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){const{beginAtZero:t}=this.options,{minDefined:n,maxDefined:r}=this.getUserBounds();let{min:s,max:o}=this;const i=c=>s=n?s:c,a=c=>o=r?o:c;if(t){const c=cl(s),u=cl(o);c<0&&u<0?a(0):c>0&&u>0&&i(0)}if(s===o){let c=o===0?1:Math.abs(o*.05);a(o+c),t||i(s-c)}this.min=s,this.max=o}getTickLimit(){const t=this.options.ticks;let{maxTicksLimit:n,stepSize:r}=t,s;return r?(s=Math.ceil(this.max/r)-Math.floor(this.min/r)+1,s>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${r} would result generating up to ${s} ticks. Limiting to 1000.`),s=1e3)):(s=this.computeTickLimit(),n=n||11),n&&(s=Math.min(n,s)),s}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,n=t.ticks;let r=this.getTickLimit();r=Math.max(2,r);const s={maxTicks:r,bounds:t.bounds,min:t.min,max:t.max,precision:n.precision,step:n.stepSize,count:n.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:n.minRotation||0,includeBounds:n.includeBounds!==!1},o=this._range||this,i=dTe(s,o);return t.bounds==="ticks"&&XX(i,this,"value"),t.reverse?(i.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),i}configure(){const t=this.ticks;let n=this.min,r=this.max;if(super.configure(),this.options.offset&&t.length){const s=(r-n)/Math.max(t.length-1,1)/2;n-=s,r+=s}this._startValue=n,this._endValue=r,this._valueRange=r-n}getLabelForValue(t){return Sv(t,this.chart.options.locale,this.options.ticks.format)}}class mh extends UC{determineDataLimits(){const{min:t,max:n}=this.getMinMax(!0);this.min=Zr(t)?t:0,this.max=Zr(n)?n:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),n=t?this.width:this.height,r=ma(this.options.ticks.minRotation),s=(t?Math.sin(r):Math.cos(r))||.001,o=this._resolveTickFontOptions(0);return Math.ceil(n/Math.min(40,o.lineHeight/s))}getPixelForValue(t){return t===null?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}Ne(mh,"id","linear"),Ne(mh,"defaults",{ticks:{callback:w_.formatters.numeric}});const qy=e=>Math.floor(Mu(e)),Ud=(e,t)=>Math.pow(10,qy(e)+t);function x6(e){return e/Math.pow(10,qy(e))===1}function y6(e,t,n){const r=Math.pow(10,n),s=Math.floor(e/r);return Math.ceil(t/r)-s}function fTe(e,t){const n=t-e;let r=qy(n);for(;y6(e,t,r)>10;)r++;for(;y6(e,t,r)<10;)r--;return Math.min(r,qy(e))}function hTe(e,{min:t,max:n}){t=di(e.min,t);const r=[],s=qy(t);let o=fTe(t,n),i=o<0?Math.pow(10,Math.abs(o)):1;const a=Math.pow(10,o),c=s>o?Math.pow(10,s):0,u=Math.round((t-c)*i)/i,d=Math.floor((t-c)/a/10)*a*10;let f=Math.floor((u-d)/Math.pow(10,o)),h=di(e.min,Math.round((c+d+f*Math.pow(10,o))*i)/i);for(;h<n;)r.push({value:h,major:x6(h),significand:f}),f>=10?f=f<15?15:20:f++,f>=20&&(o++,f=2,i=o>=0?1:i),h=Math.round((c+d+f*Math.pow(10,o))*i)/i;const p=di(e.max,h);return r.push({value:p,major:x6(p),significand:f}),r}class Ym extends Ed{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,n){const r=UC.prototype.parse.apply(this,[t,n]);if(r===0){this._zero=!0;return}return Zr(r)&&r>0?r:null}determineDataLimits(){const{min:t,max:n}=this.getMinMax(!0);this.min=Zr(t)?Math.max(0,t):null,this.max=Zr(n)?Math.max(0,n):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!Zr(this._userMin)&&(this.min=t===Ud(this.min,0)?Ud(this.min,-1):Ud(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:n}=this.getUserBounds();let r=this.min,s=this.max;const o=a=>r=t?r:a,i=a=>s=n?s:a;r===s&&(r<=0?(o(1),i(10)):(o(Ud(r,-1)),i(Ud(s,1)))),r<=0&&o(Ud(s,-1)),s<=0&&i(Ud(r,1)),this.min=r,this.max=s}buildTicks(){const t=this.options,n={min:this._userMin,max:this._userMax},r=hTe(n,this);return t.bounds==="ticks"&&XX(r,this,"value"),t.reverse?(r.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),r}getLabelForValue(t){return t===void 0?"0":Sv(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=Mu(t),this._valueRange=Mu(this.max)-Mu(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(Mu(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const n=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+n*this._valueRange)}}Ne(Ym,"id","logarithmic"),Ne(Ym,"defaults",{ticks:{callback:w_.formatters.logarithmic,major:{enabled:!0}}});function kM(e){const t=e.ticks;if(t.display&&e.display){const n=Hs(t.backdropPadding);return Yt(t.font&&t.font.size,Ir.font.size)+n.height}return 0}function pTe(e,t,n){return n=ur(n)?n:[n],{w:wje(e,t.string,n),h:n.length*t.lineHeight}}function v6(e,t,n,r,s){return e===r||e===s?{start:t-n/2,end:t+n/2}:e<r||e>s?{start:t-n,end:t}:{start:t,end:t+n}}function mTe(e){const t={l:e.left+e._padding.left,r:e.right-e._padding.right,t:e.top+e._padding.top,b:e.bottom-e._padding.bottom},n=Object.assign({},t),r=[],s=[],o=e._pointLabels.length,i=e.options.pointLabels,a=i.centerPointLabels?Vn/o:0;for(let c=0;c<o;c++){const u=i.setContext(e.getPointLabelContext(c));s[c]=u.padding;const d=e.getPointPosition(c,e.drawingArea+s[c],a),f=Nr(u.font),h=pTe(e.ctx,f,e._pointLabels[c]);r[c]=h;const p=to(e.getIndexAngle(c)+a),g=Math.round(tO(p)),b=v6(g,d.x,h.w,0,180),x=v6(g,d.y,h.h,90,270);gTe(n,t,p,b,x)}e.setCenterPoint(t.l-n.l,n.r-t.r,t.t-n.t,n.b-t.b),e._pointLabelItems=yTe(e,r,s)}function gTe(e,t,n,r,s){const o=Math.abs(Math.sin(n)),i=Math.abs(Math.cos(n));let a=0,c=0;r.start<t.l?(a=(t.l-r.start)/o,e.l=Math.min(e.l,t.l-a)):r.end>t.r&&(a=(r.end-t.r)/o,e.r=Math.max(e.r,t.r+a)),s.start<t.t?(c=(t.t-s.start)/i,e.t=Math.min(e.t,t.t-c)):s.end>t.b&&(c=(s.end-t.b)/i,e.b=Math.max(e.b,t.b+c))}function bTe(e,t,n){const r=e.drawingArea,{extra:s,additionalAngle:o,padding:i,size:a}=n,c=e.getPointPosition(t,r+s+i,o),u=Math.round(tO(to(c.angle+ts))),d=STe(c.y,a.h,u),f=vTe(u),h=wTe(c.x,a.w,f);return{visible:!0,x:c.x,y:d,textAlign:f,left:h,top:d,right:h+a.w,bottom:d+a.h}}function xTe(e,t){if(!t)return!0;const{left:n,top:r,right:s,bottom:o}=e;return!(xc({x:n,y:r},t)||xc({x:n,y:o},t)||xc({x:s,y:r},t)||xc({x:s,y:o},t))}function yTe(e,t,n){const r=[],s=e._pointLabels.length,o=e.options,{centerPointLabels:i,display:a}=o.pointLabels,c={extra:kM(o)/2,additionalAngle:i?Vn/s:0};let u;for(let d=0;d<s;d++){c.padding=n[d],c.size=t[d];const f=bTe(e,d,c);r.push(f),a==="auto"&&(f.visible=xTe(f,u),f.visible&&(u=f))}return r}function vTe(e){return e===0||e===180?"center":e<180?"left":"right"}function wTe(e,t,n){return n==="right"?e-=t:n==="center"&&(e-=t/2),e}function STe(e,t,n){return n===90||n===270?e-=t/2:(n>270||n<90)&&(e-=t),e}function CTe(e,t,n){const{left:r,top:s,right:o,bottom:i}=n,{backdropColor:a}=t;if(!cn(a)){const c=Ic(t.borderRadius),u=Hs(t.backdropPadding);e.fillStyle=a;const d=r-u.left,f=s-u.top,h=o-r+u.width,p=i-s+u.height;Object.values(c).some(g=>g!==0)?(e.beginPath(),Dc(e,{x:d,y:f,w:h,h:p,radius:c}),e.fill()):e.fillRect(d,f,h,p)}}function NTe(e,t){const{ctx:n,options:{pointLabels:r}}=e;for(let s=t-1;s>=0;s--){const o=e._pointLabelItems[s];if(!o.visible)continue;const i=r.setContext(e.getPointLabelContext(s));CTe(n,i,o);const a=Nr(i.font),{x:c,y:u,textAlign:d}=o;ph(n,e._pointLabels[s],c,u+a.lineHeight/2,a,{color:i.color,textAlign:d,textBaseline:"middle"})}}function VQ(e,t,n,r){const{ctx:s}=e;if(n)s.arc(e.xCenter,e.yCenter,t,0,Dr);else{let o=e.getPointPosition(0,t);s.moveTo(o.x,o.y);for(let i=1;i<r;i++)o=e.getPointPosition(i,t),s.lineTo(o.x,o.y)}}function kTe(e,t,n,r,s){const o=e.ctx,i=t.circular,{color:a,lineWidth:c}=t;!i&&!r||!a||!c||n<0||(o.save(),o.strokeStyle=a,o.lineWidth=c,o.setLineDash(s.dash||[]),o.lineDashOffset=s.dashOffset,o.beginPath(),VQ(e,n,i,r),o.closePath(),o.stroke(),o.restore())}function _Te(e,t,n){return jd(e,{label:n,index:t,type:"pointLabel"})}class _x extends UC{constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=Hs(kM(this.options)/2),n=this.width=this.maxWidth-t.width,r=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+n/2+t.left),this.yCenter=Math.floor(this.top+r/2+t.top),this.drawingArea=Math.floor(Math.min(n,r)/2)}determineDataLimits(){const{min:t,max:n}=this.getMinMax(!1);this.min=Zr(t)&&!isNaN(t)?t:0,this.max=Zr(n)&&!isNaN(n)?n:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/kM(this.options))}generateTickLabels(t){UC.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((n,r)=>{const s=lr(this.options.pointLabels.callback,[n,r],this);return s||s===0?s:""}).filter((n,r)=>this.chart.getDataVisibility(r))}fit(){const t=this.options;t.display&&t.pointLabels.display?mTe(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,n,r,s){this.xCenter+=Math.floor((t-n)/2),this.yCenter+=Math.floor((r-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,n,r,s))}getIndexAngle(t){const n=Dr/(this._pointLabels.length||1),r=this.options.startAngle||0;return to(t*n+ma(r))}getDistanceFromCenterForValue(t){if(cn(t))return NaN;const n=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*n:(t-this.min)*n}getValueForDistanceFromCenter(t){if(cn(t))return NaN;const n=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-n:this.min+n}getPointLabelContext(t){const n=this._pointLabels||[];if(t>=0&&t<n.length){const r=n[t];return _Te(this.getContext(),t,r)}}getPointPosition(t,n,r=0){const s=this.getIndexAngle(t)-ts+r;return{x:Math.cos(s)*n+this.xCenter,y:Math.sin(s)*n+this.yCenter,angle:s}}getPointPositionForValue(t,n){return this.getPointPosition(t,this.getDistanceFromCenterForValue(n))}getBasePosition(t){return this.getPointPositionForValue(t||0,this.getBaseValue())}getPointLabelPosition(t){const{left:n,top:r,right:s,bottom:o}=this._pointLabelItems[t];return{left:n,top:r,right:s,bottom:o}}drawBackground(){const{backgroundColor:t,grid:{circular:n}}=this.options;if(t){const r=this.ctx;r.save(),r.beginPath(),VQ(this,this.getDistanceFromCenterForValue(this._endValue),n,this._pointLabels.length),r.closePath(),r.fillStyle=t,r.fill(),r.restore()}}drawGrid(){const t=this.ctx,n=this.options,{angleLines:r,grid:s,border:o}=n,i=this._pointLabels.length;let a,c,u;if(n.pointLabels.display&&NTe(this,i),s.display&&this.ticks.forEach((d,f)=>{if(f!==0||f===0&&this.min<0){c=this.getDistanceFromCenterForValue(d.value);const h=this.getContext(f),p=s.setContext(h),g=o.setContext(h);kTe(this,p,c,i,g)}}),r.display){for(t.save(),a=i-1;a>=0;a--){const d=r.setContext(this.getPointLabelContext(a)),{color:f,lineWidth:h}=d;!h||!f||(t.lineWidth=h,t.strokeStyle=f,t.setLineDash(d.borderDash),t.lineDashOffset=d.borderDashOffset,c=this.getDistanceFromCenterForValue(n.reverse?this.min:this.max),u=this.getPointPosition(a,c),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(u.x,u.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,n=this.options,r=n.ticks;if(!r.display)return;const s=this.getIndexAngle(0);let o,i;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach((a,c)=>{if(c===0&&this.min>=0&&!n.reverse)return;const u=r.setContext(this.getContext(c)),d=Nr(u.font);if(o=this.getDistanceFromCenterForValue(this.ticks[c].value),u.showLabelBackdrop){t.font=d.string,i=t.measureText(a.label).width,t.fillStyle=u.backdropColor;const f=Hs(u.backdropPadding);t.fillRect(-i/2-f.left,-o-d.size/2-f.top,i+f.width,d.size+f.height)}ph(t,a.label,0,-o,d,{color:u.color,strokeColor:u.textStrokeColor,strokeWidth:u.textStrokeWidth})}),t.restore()}drawTitle(){}}Ne(_x,"id","radialLinear"),Ne(_x,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:w_.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),Ne(_x,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),Ne(_x,"descriptors",{angleLines:{_fallback:"grid"}});const k_={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},Xo=Object.keys(k_);function w6(e,t){return e-t}function S6(e,t){if(cn(t))return null;const n=e._adapter,{parser:r,round:s,isoWeekday:o}=e._parseOpts;let i=t;return typeof r=="function"&&(i=r(i)),Zr(i)||(i=typeof r=="string"?n.parse(i,r):n.parse(i)),i===null?null:(s&&(i=s==="week"&&(fh(o)||o===!0)?n.startOf(i,"isoWeek",o):n.startOf(i,s)),+i)}function C6(e,t,n,r){const s=Xo.length;for(let o=Xo.indexOf(e);o<s-1;++o){const i=k_[Xo[o]],a=i.steps?i.steps:Number.MAX_SAFE_INTEGER;if(i.common&&Math.ceil((n-t)/(a*i.size))<=r)return Xo[o]}return Xo[s-1]}function jTe(e,t,n,r,s){for(let o=Xo.length-1;o>=Xo.indexOf(n);o--){const i=Xo[o];if(k_[i].common&&e._adapter.diff(s,r,i)>=t-1)return i}return Xo[n?Xo.indexOf(n):0]}function ETe(e){for(let t=Xo.indexOf(e)+1,n=Xo.length;t<n;++t)if(k_[Xo[t]].common)return Xo[t]}function N6(e,t,n){if(!n)e[t]=!0;else if(n.length){const{lo:r,hi:s}=nO(n,t),o=n[r]>=t?n[r]:n[s];e[o]=!0}}function DTe(e,t,n,r){const s=e._adapter,o=+s.startOf(t[0].value,r),i=t[t.length-1].value;let a,c;for(a=o;a<=i;a=+s.add(a,1,r))c=n[a],c>=0&&(t[c].major=!0);return t}function k6(e,t,n){const r=[],s={},o=t.length;let i,a;for(i=0;i<o;++i)a=t[i],s[a]=i,r.push({value:a,major:!1});return o===0||!n?r:DTe(e,r,s,n)}class Yy extends Ed{constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,n={}){const r=t.time||(t.time={}),s=this._adapter=new LEe._date(t.adapters.date);s.init(n),Gx(r.displayFormats,s.formats()),this._parseOpts={parser:r.parser,round:r.round,isoWeekday:r.isoWeekday},super.init(t),this._normalized=n.normalized}parse(t,n){return t===void 0?null:S6(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,n=this._adapter,r=t.time.unit||"day";let{min:s,max:o,minDefined:i,maxDefined:a}=this.getUserBounds();function c(u){!i&&!isNaN(u.min)&&(s=Math.min(s,u.min)),!a&&!isNaN(u.max)&&(o=Math.max(o,u.max))}(!i||!a)&&(c(this._getLabelBounds()),(t.bounds!=="ticks"||t.ticks.source!=="labels")&&c(this.getMinMax(!1))),s=Zr(s)&&!isNaN(s)?s:+n.startOf(Date.now(),r),o=Zr(o)&&!isNaN(o)?o:+n.endOf(Date.now(),r)+1,this.min=Math.min(s,o-1),this.max=Math.max(s+1,o)}_getLabelBounds(){const t=this.getLabelTimestamps();let n=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;return t.length&&(n=t[0],r=t[t.length-1]),{min:n,max:r}}buildTicks(){const t=this.options,n=t.time,r=t.ticks,s=r.source==="labels"?this.getLabelTimestamps():this._generate();t.bounds==="ticks"&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const o=this.min,i=this.max,a=lje(s,o,i);return this._unit=n.unit||(r.autoSkip?C6(n.minUnit,this.min,this.max,this._getLabelCapacity(o)):jTe(this,a.length,n.minUnit,this.min,this.max)),this._majorUnit=!r.major.enabled||this._unit==="year"?void 0:ETe(this._unit),this.initOffsets(s),t.reverse&&a.reverse(),k6(this,a,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map(t=>+t.value))}initOffsets(t=[]){let n=0,r=0,s,o;this.options.offset&&t.length&&(s=this.getDecimalForValue(t[0]),t.length===1?n=1-s:n=(this.getDecimalForValue(t[1])-s)/2,o=this.getDecimalForValue(t[t.length-1]),t.length===1?r=o:r=(o-this.getDecimalForValue(t[t.length-2]))/2);const i=t.length<3?.5:.25;n=Es(n,0,i),r=Es(r,0,i),this._offsets={start:n,end:r,factor:1/(n+1+r)}}_generate(){const t=this._adapter,n=this.min,r=this.max,s=this.options,o=s.time,i=o.unit||C6(o.minUnit,n,r,this._getLabelCapacity(n)),a=Yt(s.ticks.stepSize,1),c=i==="week"?o.isoWeekday:!1,u=fh(c)||c===!0,d={};let f=n,h,p;if(u&&(f=+t.startOf(f,"isoWeek",c)),f=+t.startOf(f,u?"day":i),t.diff(r,n,i)>1e5*a)throw new Error(n+" and "+r+" are too far apart with stepSize of "+a+" "+i);const g=s.ticks.source==="data"&&this.getDataTimestamps();for(h=f,p=0;h<r;h=+t.add(h,a,i),p++)N6(d,h,g);return(h===r||s.bounds==="ticks"||p===1)&&N6(d,h,g),Object.keys(d).sort(w6).map(b=>+b)}getLabelForValue(t){const n=this._adapter,r=this.options.time;return r.tooltipFormat?n.format(t,r.tooltipFormat):n.format(t,r.displayFormats.datetime)}format(t,n){const s=this.options.time.displayFormats,o=this._unit,i=n||s[o];return this._adapter.format(t,i)}_tickFormatFunction(t,n,r,s){const o=this.options,i=o.ticks.callback;if(i)return lr(i,[t,n,r],this);const a=o.time.displayFormats,c=this._unit,u=this._majorUnit,d=c&&a[c],f=u&&a[u],h=r[n],p=u&&f&&h&&h.major;return this._adapter.format(t,s||(p?f:d))}generateTickLabels(t){let n,r,s;for(n=0,r=t.length;n<r;++n)s=t[n],s.label=this._tickFormatFunction(s.value,n,t)}getDecimalForValue(t){return t===null?NaN:(t-this.min)/(this.max-this.min)}getPixelForValue(t){const n=this._offsets,r=this.getDecimalForValue(t);return this.getPixelForDecimal((n.start+r)*n.factor)}getValueForPixel(t){const n=this._offsets,r=this.getDecimalForPixel(t)/n.factor-n.end;return this.min+r*(this.max-this.min)}_getLabelSize(t){const n=this.options.ticks,r=this.ctx.measureText(t).width,s=ma(this.isHorizontal()?n.maxRotation:n.minRotation),o=Math.cos(s),i=Math.sin(s),a=this._resolveTickFontOptions(0).size;return{w:r*o+a*i,h:r*i+a*o}}_getLabelCapacity(t){const n=this.options.time,r=n.displayFormats,s=r[n.unit]||r.millisecond,o=this._tickFormatFunction(t,0,k6(this,[t],this._majorUnit),s),i=this._getLabelSize(o),a=Math.floor(this.isHorizontal()?this.width/i.w:this.height/i.h)-1;return a>0?a:1}getDataTimestamps(){let t=this._cache.data||[],n,r;if(t.length)return t;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(n=0,r=s.length;n<r;++n)t=t.concat(s[n].controller.getAllParsedValues(this));return this._cache.data=this.normalize(t)}getLabelTimestamps(){const t=this._cache.labels||[];let n,r;if(t.length)return t;const s=this.getLabels();for(n=0,r=s.length;n<r;++n)t.push(S6(this,s[n]));return this._cache.labels=this._normalized?t:this.normalize(t)}normalize(t){return eQ(t.sort(w6))}}Ne(Yy,"id","time"),Ne(Yy,"defaults",{bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}});function s1(e,t,n){let r=0,s=e.length-1,o,i,a,c;n?(t>=e[r].pos&&t<=e[s].pos&&({lo:r,hi:s}=bc(e,"pos",t)),{pos:o,time:a}=e[r],{pos:i,time:c}=e[s]):(t>=e[r].time&&t<=e[s].time&&({lo:r,hi:s}=bc(e,"time",t)),{time:o,pos:a}=e[r],{time:i,pos:c}=e[s]);const u=i-o;return u?a+(c-a)*(t-o)/u:a}class _M extends Yy{constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),n=this._table=this.buildLookupTable(t);this._minPos=s1(n,this.min),this._tableRange=s1(n,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:n,max:r}=this,s=[],o=[];let i,a,c,u,d;for(i=0,a=t.length;i<a;++i)u=t[i],u>=n&&u<=r&&s.push(u);if(s.length<2)return[{time:n,pos:0},{time:r,pos:1}];for(i=0,a=s.length;i<a;++i)d=s[i+1],c=s[i-1],u=s[i],Math.round((d+c)/2)!==u&&o.push({time:u,pos:i/(a-1)});return o}_generate(){const t=this.min,n=this.max;let r=super.getDataTimestamps();return(!r.includes(t)||!r.length)&&r.splice(0,0,t),(!r.includes(n)||r.length===1)&&r.push(n),r.sort((s,o)=>s-o)}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const n=this.getDataTimestamps(),r=this.getLabelTimestamps();return n.length&&r.length?t=this.normalize(n.concat(r)):t=n.length?n:r,t=this._cache.all=t,t}getDecimalForValue(t){return(s1(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const n=this._offsets,r=this.getDecimalForPixel(t)/n.factor-n.end;return s1(this._table,r*this._tableRange+this._minPos,!0)}}Ne(_M,"id","timeseries"),Ne(_M,"defaults",Yy.defaults);var ITe=Object.freeze({__proto__:null,CategoryScale:Wy,LinearScale:mh,LogarithmicScale:Ym,RadialLinearScale:_x,TimeScale:Yy,TimeSeriesScale:_M});const TTe=[OEe,hIe,aTe,ITe];function MTe(){return function(e){const t=Rn.defaults.plugins.legend.labels.generateLabels;return t(e).map(r=>(r.pointStyle="rect",r))}}function ATe(){return function(e){const t=e.data.datasets||[],n=Rn.defaults.plugins.legend.labels.generateLabels;return n(e).map(s=>{const o=s.datasetIndex;if(o!==void 0&&t[o]){const i=t[o];s.pointStyle="line",s.lineWidth=i.borderWidth??2,s.lineDash=i.borderDash??[],s.strokeStyle=i.borderColor}return s})}}function RTe(){return function(e){const t=Rn.defaults.plugins.legend.labels.generateLabels;return t(e).map(r=>(r.pointStyle="rect",r))}}function FTe(){return function(e){const t=e.data.datasets||[],n=Rn.defaults.plugins.legend.labels.generateLabels;return n(e).map(s=>{const o=s.datasetIndex;if(o!==void 0&&t[o]){const i=t[o],a=e.config.type;i.type==="bar"||!i.type&&a==="bar"?s.pointStyle="rect":i.type==="line"&&(s.pointStyle="line",s.lineWidth=i.borderWidth??2,s.lineDash=i.borderDash??[],s.strokeStyle=i.borderColor)}return s})}}function pO(e,t,n){var h,p,g;const r={};(t==null?void 0:t.display)!==void 0&&(r.display=t.display),t!=null&&t.position&&(r.position=t.position),t!=null&&t.align&&(r.align=t.align);const s=["line","stackedLine"],o=["area","stackedArea"],i=["bar","horizontalBar","stackedBar"],a=s.includes(n||""),c=o.includes(n||""),u=i.includes(n||""),d=n==="combo",f={...(p=(h=e.plugins)==null?void 0:h.legend)==null?void 0:p.labels};return d?(f.usePointStyle=!0,f.generateLabels=FTe()):c?(f.usePointStyle=!0,f.generateLabels=MTe()):a?(f.usePointStyle=!0,f.generateLabels=ATe()):u&&(f.usePointStyle=!0,f.generateLabels=RTe()),{...e,plugins:{...e.plugins,legend:{...(g=e.plugins)==null?void 0:g.legend,...r,labels:f}}}}function HQ(e){return!["kpi","metric","text","table","pivotTable","treemap"].includes(e)}function mO(e){if(HQ(e))switch(e){case"heatmap":return{display:!1,position:"top",align:"center"};case"pie":case"doughnut":return{display:!0,position:"right",align:"center"};case"bubble":case"scatter":return{display:!1,position:"right",align:"center"};case"line":case"bar":case"combo":case"stackedBar":case"stackedLine":return{display:!0,position:"top",align:"center"};default:return{display:!0,position:"top",align:"center"}}}function UQ(e,t){return{...e,...t}}function PTe(e,t=!1,n=!1){switch(e){case"bar":case"range":return t?{anchor:"end",align:"right"}:{anchor:"end",align:"top"};case"horizontalBar":return{anchor:"end",align:"right"};case"line":case"radar":case"area":return t?{anchor:"end",align:"right"}:{anchor:"end",align:"top"};case"pie":case"doughnut":case"polarArea":case"funnel":return{anchor:"center",align:"center"};case"stackedBar":case"stackedLine":case"stackedArea":return n?t?{anchor:"end",align:"right"}:{anchor:"end",align:"top"}:{anchor:"center",align:"center"};case"heatmap":return{anchor:"center",align:"center"};default:return{anchor:"center",align:"center"}}}function OTe(e,t){return(t==null?void 0:t.enabled)!==void 0?t.enabled:(t==null?void 0:t.display)==="auto"?e<=30:!1}function _6(e,t,n,r){return function(s){if(s==null)return"";if(r==="range"&&Array.isArray(s)){const o=e||{},i=e==null?void 0:e.type;return s.slice(0,2).map(c=>i&&i!=="auto"?Fn(Number(c),i,o):c).join(" - ")}return t?s:e!=null&&e.type&&e.type!=="auto"?Fn(Number(s),e.type,e):n?n(s):s}}function o1(e,t,n,r,s){if(e!=null&&e.color&&e.color!=="auto")return e.color;const o=n==="end"&&r==="top"||n==="end"&&r==="right",i=n==="start"&&r==="bottom",a=n==="start"&&r==="left";return o?c=>{var u;return m.getContrastColor(m.getCanvasBackgroundColor((u=c==null?void 0:c.chart)==null?void 0:u.canvas))}:i||a?c=>{var u;return m.getContrastColor(m.getCanvasBackgroundColor((u=c==null?void 0:c.chart)==null?void 0:u.canvas))}:c=>{var d,f,h,p,g;const u=((f=(d=c.dataset)==null?void 0:d.backgroundColor)==null?void 0:f[c.dataIndex])||((h=c.dataset)==null?void 0:h.backgroundColor)||t||m.getCanvasBackgroundColor((p=c==null?void 0:c.chart)==null?void 0:p.canvas);return m.getContrastColor(u,{baseColor:m.getCanvasBackgroundColor((g=c==null?void 0:c.chart)==null?void 0:g.canvas)})}}function Eg(e,t,n,r,s){var T,F,P,R,B,z,U,Y,O,K,q,M,G,L,$,V,H,A;const o=(F=(T=n==null?void 0:n.chartOptions)==null?void 0:T.plugins)==null?void 0:F.datalabels,i=(o==null?void 0:o.display)!==!1&&((o==null?void 0:o.anchor)||(o==null?void 0:o.align));if(r==="heatmap")return{...e,plugins:{...e.plugins,datalabels:{display:!1}}};if((t==null?void 0:t.enabled)===!1)return{...e,plugins:{...e.plugins,datalabels:{display:!1}}};if(!t&&i)return e;if(!t)return{...e,plugins:{...e.plugins,datalabels:{display:!1}}};const c=r||e.type||"bar",u=c==="bubble"||c==="scatter",d=((P=n==null?void 0:n.chartOptions)==null?void 0:P.indexAxis)||(e==null?void 0:e.indexAxis)||"x",f=d==="y"?"x":"y",h=d==="y"?"y":"x",p=((B=(R=e.scales)==null?void 0:R[f])==null?void 0:B.stacked)===!0||c==="stackedBar"||c==="stackedLine"||c==="stackedArea"||c==="bar"&&((U=(z=e.scales)==null?void 0:z[h])==null?void 0:U.stacked)===!0&&((O=(Y=e.scales)==null?void 0:Y[f])==null?void 0:O.stacked)===!0,g=c==="stackedBar"||c==="bar"&&((q=(K=e.scales)==null?void 0:K[h])==null?void 0:q.stacked)===!0&&((G=(M=e.scales)==null?void 0:M[f])==null?void 0:G.stacked)===!0,b=d==="y";b?n==null||n.xAxisConfig:n==null||n.yAxisConfig;const x=bv({card:s,chartType:c,preferences:n,dataLabelsConfig:t}),y=_g(x),S=x.formatOptions,w=PTe(c,b,t.showTotal),C=g&&!t.showTotal?"center":t.anchor||w.anchor,N=g&&!t.showTotal?"center":t.align||w.align;let k=C,_=N;const E=c==="pie"||c==="doughnut"||c==="polarArea"||c==="funnel";g&&!t.showTotal&&(k="center",_="center");const D=u?"start":k,j=u?"center":_,I={display:t.display!==!1,anchor:u?"start":k,align:u?"center":_,clamp:t.clamp??!0,clip:t.clip??!1,offset:t.offset??0,formatter:u?(W,X)=>{var fe,de,Se,ue,ve;const Z=(X==null?void 0:X.raw)||W,J=(Z==null?void 0:Z.label)??((fe=Z==null?void 0:Z.meta)==null?void 0:fe.label)??((ue=Z==null?void 0:Z.meta)==null?void 0:ue[(Se=(de=X==null?void 0:X.chart)==null?void 0:de.data)==null?void 0:Se.labelKey])??((ve=Z==null?void 0:Z.meta)==null?void 0:ve.labelKey);if(J!=null&&J!=="")return J;const re=(typeof(Z==null?void 0:Z.y)=="number"?Z==null?void 0:Z.y:Number(Z==null?void 0:Z.y))??(typeof(Z==null?void 0:Z.x)=="number"?Z==null?void 0:Z.x:Number(Z==null?void 0:Z.x))??Number(W);return Number.isFinite(re)?y?re:S!=null&&S.type&&S.type!=="auto"?Fn(re,S.type,S):re:""}:_6(S,y,($=(L=e.plugins)==null?void 0:L.datalabels)==null?void 0:$.formatter,c),color:o1(t,void 0,D,j),font:{size:((V=t.font)==null?void 0:V.size)||12,weight:((H=t.font)==null?void 0:H.weight)||"normal"},rotation:t.rotation||0};if(E&&c!=="funnel"&&(delete I.anchor,delete I.align,Object.assign(I,{anchor:"center",align:"center",offset:0,clamp:!0,clip:!1,display:function(W){if(t.display===!1)return!1;const X=W.dataset.data[W.dataIndex],Z=W.dataset.data.reduce((re,fe)=>re+fe,0);return X/Z*100>5}})),c==="funnel"&&t.enabled&&(Object.assign(I,{display:function(W){var Z;if(t.display===!1)return!1;const X=(((Z=n==null?void 0:n.funnelConfig)==null?void 0:Z.labelThreshold)??0)/100;if(X>0){const J=W.dataset.data,re=J[W.dataIndex],fe=J.reduce((Se,ue)=>Se+ue,0);return(fe>0?re/fe:0)>=X}return!0},anchor:function(W){return W.dataset.data[W.dataIndex]<.02?"end":"start"},align:function(W){return W.dataset.data[W.dataIndex]<.02?"end":"center"},textAlign:"center",offset:0,clamp:!0,clip:!1}),I.font||(I.font={}),I.font.size=I.font.size||14),p&&t.showTotal&&(I.display=function(W){const X=W.chart.data.datasets.length;return W.datasetIndex===X-1},I.formatter=function(W,X){var fe,de;let Z=0;const J=X.dataIndex;return X.chart.data.datasets.forEach(Se=>{const ue=Se.data[J];ue&&!isNaN(ue)&&(Z+=Number(ue))}),_6(S,y,(de=(fe=e.plugins)==null?void 0:fe.datalabels)==null?void 0:de.formatter,c)(Z)},I.anchor="end",I.align=b?"right":"top",I.color=o1(t,void 0,"end",b?"right":"top")),!g&&!E&&t.position&&t.position!=="auto"&&t.position!=="custom"){if(b)switch(t.position){case"left":I.anchor="start",I.align="left";break;case"right":I.anchor="end",I.align="right";break;case"center":I.anchor="center",I.align="center";break;case"top":case"bottom":I.anchor="center",I.align="center";break}else switch(t.position){case"top":I.anchor="end",I.align="top";break;case"bottom":I.anchor="start",I.align="bottom";break;case"center":I.anchor="center",I.align="center";break;case"left":case"right":I.anchor="center",I.align="center";break}I.color=o1(t,void 0,I.anchor,I.align)}else t.position==="custom"&&(I.color=o1(t,void 0,I.anchor,I.align));return E||c==="funnel"?{...e,plugins:{...e.plugins,datalabels:I}}:{...e,plugins:{...e.plugins,datalabels:{...(A=e.plugins)==null?void 0:A.datalabels,...I}}}}function WQ(e){return!["kpi","metric","text","table","pivotTable","custom"].includes(e)}function Cv(e,t){var n,r,s,o;if(WQ(e))switch(e){case"treemap":return{enabled:!0,display:!0,format:"number"};case"bullet":{const i=(n=t==null?void 0:t.bulletConfig)==null?void 0:n.showValueLabels,c=(((r=t==null?void 0:t.bulletConfig)==null?void 0:r.orientation)??(((s=t==null?void 0:t.chartOptions)==null?void 0:s.indexAxis)==="x"?"vertical":"horizontal"))==="vertical"?"top":"right";return i===!1?{enabled:!1,display:!1}:{enabled:!0,display:!0,format:"number",position:c}}case"heatmap":return(o=t==null?void 0:t.heatmapConfig)!=null&&o.showDataLabels?{enabled:!0,display:!0}:void 0;case"bubble":case"scatter":return{enabled:!1,display:!1};default:return}}function LTe(e){return e.length===1?[e[0]]:e.slice(1).filter(n=>!m.METADATA_KEYS.includes(n))}function jD({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var C;const i=s==="radar"?.2:1,{keys:a}=pr(e),c=LTe(a);let u="none";s=="bar"?u="bar":s=="line"&&(u="line");const d=a==null?void 0:a[0],f=Qc(e,d),p=Ng(c,e,r,i,u,d,s==="stackedBar"||s==="stackedLine",Cg(e)),g=Da(p,n),{options:b,plugins:x}=sd({cardType:s,cfg:t,preferences:r,customCfg:n,card:o}),y=((C=o.interactionConfig)==null?void 0:C.interactions)&&o.interactionConfig.interactions.length>0,S=function(N,k){var E;const _=((E=N.native)==null?void 0:E.target)||N.target;k.length?_.style.cursor="pointer":_.style.cursor="default"};return{type:(n==null?void 0:n.type)||(t==null?void 0:t.type)||"bar",data:{labels:f,datasets:g},options:{...b,onHover:y?S:void 0},plugins:x}}function $Te(e,t){var s,o,i;const n=((s=t==null?void 0:t.options)==null?void 0:s.indexAxis)==="y"?"x":"y";return(o=e==null?void 0:e.chartOptions)!=null&&o.indexAxis?((i=e==null?void 0:e.chartOptions)==null?void 0:i.indexAxis)==="x"?"y":"x":n}function zTe(e){var n,r;return(n=e==null?void 0:e.chartOptions)!=null&&n.indexAxis?((r=e==null?void 0:e.chartOptions)==null?void 0:r.indexAxis)==="x"?"x":"y":"x"}function qQ(e,t){var u,d,f,h,p,g,b,x,y,S,w,C,N,k;const n=$Te(t,e),r=zTe(t);if((t==null?void 0:t.xAxisConfig)||(t==null?void 0:t.yAxisConfig))return(e==null?void 0:e.options)||{};const o=vv(t),{callback:i,...a}=((f=(d=(u=e==null?void 0:e.options)==null?void 0:u.scales)==null?void 0:d[r])==null?void 0:f.ticks)??{};return{...e==null?void 0:e.options,scales:{...(h=e==null?void 0:e.options)==null?void 0:h.scales,[n]:{...(g=(p=e==null?void 0:e.options)==null?void 0:p.scales)==null?void 0:g[n],ticks:{...(y=(x=(b=e==null?void 0:e.options)==null?void 0:b.scales)==null?void 0:x[n])==null?void 0:y.ticks,callback:_=>{var E,D,j,I;return o!=null&&o.type&&o.type!=="auto"?Fn(Number(_),o.type,o):$y({number:Number(_),decimalPlaces:((E=t==null?void 0:t.numberAxisFormat)==null?void 0:E.decimalPlaces)||0,useSuffix:!!((D=t==null?void 0:t.numberAxisFormat)!=null&&D.suffix),customSuffix:"",locale:((j=t==null?void 0:t.numberAxisFormat)==null?void 0:j.locale)||"",currency:((I=t==null?void 0:t.numberAxisFormat)==null?void 0:I.currency)||""})}}},[r]:{...(w=(S=e==null?void 0:e.options)==null?void 0:S.scales)==null?void 0:w[r],ticks:a}},plugins:{...(C=e==null?void 0:e.options)==null?void 0:C.plugins,datalabels:{...(k=(N=e==null?void 0:e.options)==null?void 0:N.plugins)==null?void 0:k.datalabels,formatter:function(_){var E,D,j,I;return o!=null&&o.type&&o.type!=="auto"?Fn(Number(_),o.type,o):$y({number:Number(_),decimalPlaces:((E=t==null?void 0:t.numberAxisFormat)==null?void 0:E.decimalPlaces)||0,useSuffix:!!((D=t==null?void 0:t.numberAxisFormat)!=null&&D.suffix),customSuffix:"",locale:((j=t==null?void 0:t.numberAxisFormat)==null?void 0:j.locale)||"",currency:((I=t==null?void 0:t.numberAxisFormat)==null?void 0:I.currency)||""})}}}}}function sd({cardType:e,cfg:t,preferences:n,customCfg:r,card:s}){var x,y,S,w,C,N,k,_,E,D,j,I,T,F,P,R,B,z,U,Y,O,K,q;const o=m.useDashboardStore.getState().themeStyle,i=qQ(t,n),a=es((t==null?void 0:t.options)||{},n==null?void 0:n.chartOptions),c=es(i,a),u=es(c,(r==null?void 0:r.options)||{}),d=UTe(e,n,u,s),f=Y4(u,(y=(x=o==null?void 0:o.chart)==null?void 0:x.options)==null?void 0:y.scales),h={...f,plugins:{...f==null?void 0:f.plugins,tooltip:{filter:function(M){return M.raw!==void 0&&M.raw!==null&&M.raw!==0},footerColor:((N=(C=(w=(S=o==null?void 0:o.chart)==null?void 0:S.options)==null?void 0:w.plugins)==null?void 0:C.tooltip)==null?void 0:N.footerColor)||"#999",footerFont:{size:11,weight:"normal"},footerMarginTop:6,callbacks:d,...(k=f==null?void 0:f.plugins)==null?void 0:k.tooltip,backgroundColor:(j=(D=(E=(_=o==null?void 0:o.chart)==null?void 0:_.options)==null?void 0:E.plugins)==null?void 0:D.tooltip)==null?void 0:j.backgroundColor,bodyColor:(P=(F=(T=(I=o==null?void 0:o.chart)==null?void 0:I.options)==null?void 0:T.plugins)==null?void 0:F.tooltip)==null?void 0:P.bodyColor,titleColor:(U=(z=(B=(R=o==null?void 0:o.chart)==null?void 0:R.options)==null?void 0:B.plugins)==null?void 0:z.tooltip)==null?void 0:U.titleColor}}},{plugins:p,options:g}=kd((n==null?void 0:n.customVisualCode)||"");let b=jg.applyAxisConfig(h,e||"bar",n,s);return b=Y4(b,(O=(Y=o==null?void 0:o.chart)==null?void 0:Y.options)==null?void 0:O.scales),b=pO(b,(q=(K=n==null?void 0:n.chartOptions)==null?void 0:K.plugins)==null?void 0:q.legend,e),b=Eg(b,n==null?void 0:n.dataLabelsConfig,n,e,s),b=BTe(b,u),b=es(b,g),{options:b,plugins:p}}function BTe(e,t){var r,s;const n=e.scales?Object.entries(e.scales).reduce((o,[i,a])=>{var u;if(!a)return o;const c=(u=t.scales)==null?void 0:u[i];return o[i]=VTe(a,c),o},{}):void 0;return{...e,...n?{scales:n}:{},plugins:{...e.plugins,legend:HTe((r=e.plugins)==null?void 0:r.legend,(s=t.plugins)==null?void 0:s.legend)}}}function VTe(e,t){return t?{...e,grid:Ap(e==null?void 0:e.grid,t.grid),angleLines:Ap(e==null?void 0:e.angleLines,t.angleLines),ticks:Ap(e==null?void 0:e.ticks,t.ticks),title:Ap(e==null?void 0:e.title,t.title),pointLabels:Ap(e==null?void 0:e.pointLabels,t.pointLabels)}:e}function HTe(e,t){const n=Ap(e==null?void 0:e.labels,t==null?void 0:t.labels);return n===(e==null?void 0:e.labels)?e:{...e,labels:n}}function Ap(e,t){return!(t!=null&&t.color)||e!=null&&e.color?e:{...e,color:t.color}}function UTe(e,t,n,r){var c,u,d,f,h,p;if(e==="map")return{};const s=g=>{var y,S,w,C;const b=typeof(g==null?void 0:g.datasetIndex)=="number"?g.datasetIndex:typeof((y=g==null?void 0:g[0])==null?void 0:y.datasetIndex)=="number"?g[0].datasetIndex:void 0,x=((S=g==null?void 0:g.dataset)==null?void 0:S.label)||((C=(w=g==null?void 0:g[0])==null?void 0:w.dataset)==null?void 0:C.label)||void 0;return zy({card:r,datasetIndex:b,datasetLabel:x,metricKey:x})},o=g=>{var b,x;return e==="combo"?((b=g==null?void 0:g.dataset)==null?void 0:b.yAxisID)==="y2"?"y2":"y":((x=t==null?void 0:t.chartOptions)==null?void 0:x.indexAxis)==="y"?"x":"y"},i=(g,b)=>{var S,w,C,N;const x=WP({card:r,chartType:e,preferences:t,metric:s(b),axis:o(b)}).formatOptions;if(x!=null&&x.type&&x.type!=="auto")return Fn(g,x.type,x);const y=vv(t);return y!=null&&y.type&&y.type!=="auto"?Fn(g,y.type,y):$y({number:g,decimalPlaces:((S=t==null?void 0:t.numberAxisFormat)==null?void 0:S.decimalPlaces)||0,useSuffix:!!((w=t==null?void 0:t.numberAxisFormat)!=null&&w.suffix),customSuffix:"",locale:((C=t==null?void 0:t.numberAxisFormat)==null?void 0:C.locale)||"",currency:((N=t==null?void 0:t.numberAxisFormat)==null?void 0:N.currency)||""})},a=(((u=(c=r==null?void 0:r.interactionConfig)==null?void 0:c.drillHierarchies)==null?void 0:u.length)??0)>0||(((f=(d=r==null?void 0:r.interactionConfig)==null?void 0:d.interactions)==null?void 0:f.some(g=>g.mode==="drillDown"||g.mode==="drillToDetail"||g.mode==="drillThrough"||g.mode==="drillToURL"))??!1);return{title:function(g){var x;const b=((x=g==null?void 0:g[0])==null?void 0:x.label)||"";if(g.length>1&&["stackedBar","stackedLine"].includes(e||"")){const y=g.reduce((w,C)=>{const N=C.raw;return N!==void 0&&N!==0?w+N:w},0),S=i(y,g==null?void 0:g[0]);return`${b} (${S})`}return b},label:function(g){var S;const b=((S=g==null?void 0:g.dataset)==null?void 0:S.label)||"",x=g==null?void 0:g.raw;if(x===void 0||x===0)return;const y=i(Number(x),g);return`${b}: ${y}`},footer:function(g){return a?["─────────────────","Click to drill"]:[]},...((p=(h=n==null?void 0:n.plugins)==null?void 0:h.tooltip)==null?void 0:p.callbacks)||{}}}class od{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const n=this._partials;let r=0;for(let s=0;s<this._n&&s<32;s++){const o=n[s],i=t+o,a=Math.abs(t)<Math.abs(o)?t-(i-o):o-(i-t);a&&(n[r++]=a),t=i}return n[r]=t,this._n=r+1,this}valueOf(){const t=this._partials;let n=this._n,r,s,o,i=0;if(n>0){for(i=t[--n];n>0&&(r=i,s=t[--n],i=r+s,o=s-(i-r),!o););n>0&&(o<0&&t[n-1]<0||o>0&&t[n-1]>0)&&(s=o*2,r=i+s,s==r-i&&(i=r))}return i}}function*WTe(e){for(const t of e)yield*t}function YQ(e){return Array.from(WTe(e))}function Xp(e,t,n){e=+e,t=+t,n=(s=arguments.length)<2?(t=e,e=0,1):s<3?1:+n;for(var r=-1,s=Math.max(0,Math.ceil((t-e)/n))|0,o=new Array(s);++r<s;)o[r]=e+r*n;return o}var Xt=1e-6,gO=1e-12,vn=Math.PI,Gr=vn/2,j6=vn/4,wi=vn*2,Do=180/vn,cr=vn/180,$n=Math.abs,Dg=Math.atan,jl=Math.atan2,ln=Math.cos,i1=Math.ceil,GQ=Math.exp,WC=Math.log,ED=Math.pow,tn=Math.sin,Yi=Math.sign||function(e){return e>0?1:e<0?-1:0},Fo=Math.sqrt,bO=Math.tan;function KQ(e){return e>1?0:e<-1?vn:Math.acos(e)}function Xi(e){return e>1?Gr:e<-1?-Gr:Math.asin(e)}function Cs(){}function qC(e,t){e&&D6.hasOwnProperty(e.type)&&D6[e.type](e,t)}var E6={Feature:function(e,t){qC(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,s=n.length;++r<s;)qC(n[r].geometry,t)}},D6={Sphere:function(e,t){t.sphere()},Point:function(e,t){e=e.coordinates,t.point(e[0],e[1],e[2])},MultiPoint:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)e=n[r],t.point(e[0],e[1],e[2])},LineString:function(e,t){jM(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)jM(n[r],t,0)},Polygon:function(e,t){I6(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)I6(n[r],t)},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,s=n.length;++r<s;)qC(n[r],t)}};function jM(e,t,n){var r=-1,s=e.length-n,o;for(t.lineStart();++r<s;)o=e[r],t.point(o[0],o[1],o[2]);t.lineEnd()}function I6(e,t){var n=-1,r=e.length;for(t.polygonStart();++n<r;)jM(e[n],t,1);t.polygonEnd()}function df(e,t){e&&E6.hasOwnProperty(e.type)?E6[e.type](e,t):qC(e,t)}function EM(e){return[jl(e[1],e[0]),Xi(e[2])]}function Gm(e){var t=e[0],n=e[1],r=ln(n);return[r*ln(t),r*tn(t),tn(n)]}function a1(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function YC(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function DD(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function l1(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function DM(e){var t=Fo(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function IM(e,t){function n(r,s){return r=e(r,s),t(r[0],r[1])}return e.invert&&t.invert&&(n.invert=function(r,s){return r=t.invert(r,s),r&&e.invert(r[0],r[1])}),n}function TM(e,t){return $n(e)>vn&&(e-=Math.round(e/wi)*wi),[e,t]}TM.invert=TM;function ZQ(e,t,n){return(e%=wi)?t||n?IM(M6(e),A6(t,n)):M6(e):t||n?A6(t,n):TM}function T6(e){return function(t,n){return t+=e,$n(t)>vn&&(t-=Math.round(t/wi)*wi),[t,n]}}function M6(e){var t=T6(e);return t.invert=T6(-e),t}function A6(e,t){var n=ln(e),r=tn(e),s=ln(t),o=tn(t);function i(a,c){var u=ln(c),d=ln(a)*u,f=tn(a)*u,h=tn(c),p=h*n+d*r;return[jl(f*s-p*o,d*n-h*r),Xi(p*s+f*o)]}return i.invert=function(a,c){var u=ln(c),d=ln(a)*u,f=tn(a)*u,h=tn(c),p=h*s-f*o;return[jl(f*s+h*o,d*n+p*r),Xi(p*n-d*r)]},i}function qTe(e){e=ZQ(e[0]*cr,e[1]*cr,e.length>2?e[2]*cr:0);function t(n){return n=e(n[0]*cr,n[1]*cr),n[0]*=Do,n[1]*=Do,n}return t.invert=function(n){return n=e.invert(n[0]*cr,n[1]*cr),n[0]*=Do,n[1]*=Do,n},t}function YTe(e,t,n,r,s,o){if(n){var i=ln(t),a=tn(t),c=r*n;s==null?(s=t+r*wi,o=t-c/2):(s=R6(i,s),o=R6(i,o),(r>0?s<o:s>o)&&(s+=r*wi));for(var u,d=s;r>0?d>o:d<o;d-=c)u=EM([i,-a*ln(d),-a*tn(d)]),e.point(u[0],u[1])}}function R6(e,t){t=Gm(t),t[0]-=e,DM(t);var n=KQ(-t[1]);return((-t[2]<0?-n:n)+wi-Xt)%wi}function XQ(){var e=[],t;return{point:function(n,r,s){t.push([n,r,s])},lineStart:function(){e.push(t=[])},lineEnd:Cs,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function PS(e,t){return $n(e[0]-t[0])<Xt&&$n(e[1]-t[1])<Xt}function c1(e,t,n,r){this.x=e,this.z=t,this.o=n,this.e=r,this.v=!1,this.n=this.p=null}function QQ(e,t,n,r,s){var o=[],i=[],a,c;if(e.forEach(function(g){if(!((b=g.length-1)<=0)){var b,x=g[0],y=g[b],S;if(PS(x,y)){if(!x[2]&&!y[2]){for(s.lineStart(),a=0;a<b;++a)s.point((x=g[a])[0],x[1]);s.lineEnd();return}y[0]+=2*Xt}o.push(S=new c1(x,g,null,!0)),i.push(S.o=new c1(x,null,S,!1)),o.push(S=new c1(y,g,null,!1)),i.push(S.o=new c1(y,null,S,!0))}}),!!o.length){for(i.sort(t),F6(o),F6(i),a=0,c=i.length;a<c;++a)i[a].e=n=!n;for(var u=o[0],d,f;;){for(var h=u,p=!0;h.v;)if((h=h.n)===u)return;d=h.z,s.lineStart();do{if(h.v=h.o.v=!0,h.e){if(p)for(a=0,c=d.length;a<c;++a)s.point((f=d[a])[0],f[1]);else r(h.x,h.n.x,1,s);h=h.n}else{if(p)for(d=h.p.z,a=d.length-1;a>=0;--a)s.point((f=d[a])[0],f[1]);else r(h.x,h.p.x,-1,s);h=h.p}h=h.o,d=h.z,p=!p}while(!h.v);s.lineEnd()}}}function F6(e){if(t=e.length){for(var t,n=0,r=e[0],s;++n<t;)r.n=s=e[n],s.p=r,r=s;r.n=s=e[0],s.p=r}}function ID(e){return $n(e[0])<=vn?e[0]:Yi(e[0])*(($n(e[0])+vn)%wi-vn)}function JQ(e,t){var n=ID(t),r=t[1],s=tn(r),o=[tn(n),-ln(n),0],i=0,a=0,c=new od;s===1?r=Gr+Xt:s===-1&&(r=-Gr-Xt);for(var u=0,d=e.length;u<d;++u)if(h=(f=e[u]).length)for(var f,h,p=f[h-1],g=ID(p),b=p[1]/2+j6,x=tn(b),y=ln(b),S=0;S<h;++S,g=C,x=k,y=_,p=w){var w=f[S],C=ID(w),N=w[1]/2+j6,k=tn(N),_=ln(N),E=C-g,D=E>=0?1:-1,j=D*E,I=j>vn,T=x*k;if(c.add(jl(T*D*tn(j),y*_+T*ln(j))),i+=I?E+D*wi:E,I^g>=n^C>=n){var F=YC(Gm(p),Gm(w));DM(F);var P=YC(o,F);DM(P);var R=(I^E>=0?-1:1)*Xi(P[2]);(r>R||r===R&&(F[0]||F[1]))&&(a+=I^E>=0?1:-1)}}return(i<-Xt||i<Xt&&c<-gO)^a&1}function eJ(e,t,n,r){return function(s){var o=t(s),i=XQ(),a=t(i),c=!1,u,d,f,h={point:p,lineStart:b,lineEnd:x,polygonStart:function(){h.point=y,h.lineStart=S,h.lineEnd=w,d=[],u=[]},polygonEnd:function(){h.point=p,h.lineStart=b,h.lineEnd=x,d=YQ(d);var C=JQ(u,r);d.length?(c||(s.polygonStart(),c=!0),QQ(d,KTe,C,n,s)):C&&(c||(s.polygonStart(),c=!0),s.lineStart(),n(null,null,1,s),s.lineEnd()),c&&(s.polygonEnd(),c=!1),d=u=null},sphere:function(){s.polygonStart(),s.lineStart(),n(null,null,1,s),s.lineEnd(),s.polygonEnd()}};function p(C,N){e(C,N)&&s.point(C,N)}function g(C,N){o.point(C,N)}function b(){h.point=g,o.lineStart()}function x(){h.point=p,o.lineEnd()}function y(C,N){f.push([C,N]),a.point(C,N)}function S(){a.lineStart(),f=[]}function w(){y(f[0][0],f[0][1]),a.lineEnd();var C=a.clean(),N=i.result(),k,_=N.length,E,D,j;if(f.pop(),u.push(f),f=null,!!_){if(C&1){if(D=N[0],(E=D.length-1)>0){for(c||(s.polygonStart(),c=!0),s.lineStart(),k=0;k<E;++k)s.point((j=D[k])[0],j[1]);s.lineEnd()}return}_>1&&C&2&&N.push(N.pop().concat(N.shift())),d.push(N.filter(GTe))}}return h}}function GTe(e){return e.length>1}function KTe(e,t){return((e=e.x)[0]<0?e[1]-Gr-Xt:Gr-e[1])-((t=t.x)[0]<0?t[1]-Gr-Xt:Gr-t[1])}const P6=eJ(function(){return!0},ZTe,QTe,[-vn,-Gr]);function ZTe(e){var t=NaN,n=NaN,r=NaN,s;return{lineStart:function(){e.lineStart(),s=1},point:function(o,i){var a=o>0?vn:-vn,c=$n(o-t);$n(c-vn)<Xt?(e.point(t,n=(n+i)/2>0?Gr:-Gr),e.point(r,n),e.lineEnd(),e.lineStart(),e.point(a,n),e.point(o,n),s=0):r!==a&&c>=vn&&($n(t-r)<Xt&&(t-=r*Xt),$n(o-a)<Xt&&(o-=a*Xt),n=XTe(t,n,o,i),e.point(r,n),e.lineEnd(),e.lineStart(),e.point(a,n),s=0),e.point(t=o,n=i),r=a},lineEnd:function(){e.lineEnd(),t=n=NaN},clean:function(){return 2-s}}}function XTe(e,t,n,r){var s,o,i=tn(e-n);return $n(i)>Xt?Dg((tn(t)*(o=ln(r))*tn(n)-tn(r)*(s=ln(t))*tn(e))/(s*o*i)):(t+r)/2}function QTe(e,t,n,r){var s;if(e==null)s=n*Gr,r.point(-vn,s),r.point(0,s),r.point(vn,s),r.point(vn,0),r.point(vn,-s),r.point(0,-s),r.point(-vn,-s),r.point(-vn,0),r.point(-vn,s);else if($n(e[0]-t[0])>Xt){var o=e[0]<t[0]?vn:-vn;s=n*o/2,r.point(-o,s),r.point(0,s),r.point(o,s)}else r.point(t[0],t[1])}function JTe(e){var t=ln(e),n=2*cr,r=t>0,s=$n(t)>Xt;function o(d,f,h,p){YTe(p,e,n,h,d,f)}function i(d,f){return ln(d)*ln(f)>t}function a(d){var f,h,p,g,b;return{lineStart:function(){g=p=!1,b=1},point:function(x,y){var S=[x,y],w,C=i(x,y),N=r?C?0:u(x,y):C?u(x+(x<0?vn:-vn),y):0;if(!f&&(g=p=C)&&d.lineStart(),C!==p&&(w=c(f,S),(!w||PS(f,w)||PS(S,w))&&(S[2]=1)),C!==p)b=0,C?(d.lineStart(),w=c(S,f),d.point(w[0],w[1])):(w=c(f,S),d.point(w[0],w[1],2),d.lineEnd()),f=w;else if(s&&f&&r^C){var k;!(N&h)&&(k=c(S,f,!0))&&(b=0,r?(d.lineStart(),d.point(k[0][0],k[0][1]),d.point(k[1][0],k[1][1]),d.lineEnd()):(d.point(k[1][0],k[1][1]),d.lineEnd(),d.lineStart(),d.point(k[0][0],k[0][1],3)))}C&&(!f||!PS(f,S))&&d.point(S[0],S[1]),f=S,p=C,h=N},lineEnd:function(){p&&d.lineEnd(),f=null},clean:function(){return b|(g&&p)<<1}}}function c(d,f,h){var p=Gm(d),g=Gm(f),b=[1,0,0],x=YC(p,g),y=a1(x,x),S=x[0],w=y-S*S;if(!w)return!h&&d;var C=t*y/w,N=-t*S/w,k=YC(b,x),_=l1(b,C),E=l1(x,N);DD(_,E);var D=k,j=a1(_,D),I=a1(D,D),T=j*j-I*(a1(_,_)-1);if(!(T<0)){var F=Fo(T),P=l1(D,(-j-F)/I);if(DD(P,_),P=EM(P),!h)return P;var R=d[0],B=f[0],z=d[1],U=f[1],Y;B<R&&(Y=R,R=B,B=Y);var O=B-R,K=$n(O-vn)<Xt,q=K||O<Xt;if(!K&&U<z&&(Y=z,z=U,U=Y),q?K?z+U>0^P[1]<($n(P[0]-R)<Xt?z:U):z<=P[1]&&P[1]<=U:O>vn^(R<=P[0]&&P[0]<=B)){var M=l1(D,(-j+F)/I);return DD(M,_),[P,EM(M)]}}}function u(d,f){var h=r?e:vn-e,p=0;return d<-h?p|=1:d>h&&(p|=2),f<-h?p|=4:f>h&&(p|=8),p}return eJ(i,a,o,r?[0,-e]:[-vn,e-vn])}function e2e(e,t,n,r,s,o){var i=e[0],a=e[1],c=t[0],u=t[1],d=0,f=1,h=c-i,p=u-a,g;if(g=n-i,!(!h&&g>0)){if(g/=h,h<0){if(g<d)return;g<f&&(f=g)}else if(h>0){if(g>f)return;g>d&&(d=g)}if(g=s-i,!(!h&&g<0)){if(g/=h,h<0){if(g>f)return;g>d&&(d=g)}else if(h>0){if(g<d)return;g<f&&(f=g)}if(g=r-a,!(!p&&g>0)){if(g/=p,p<0){if(g<d)return;g<f&&(f=g)}else if(p>0){if(g>f)return;g>d&&(d=g)}if(g=o-a,!(!p&&g<0)){if(g/=p,p<0){if(g>f)return;g>d&&(d=g)}else if(p>0){if(g<d)return;g<f&&(f=g)}return d>0&&(e[0]=i+d*h,e[1]=a+d*p),f<1&&(t[0]=i+f*h,t[1]=a+f*p),!0}}}}}var jx=1e9,u1=-jx;function t2e(e,t,n,r){function s(u,d){return e<=u&&u<=n&&t<=d&&d<=r}function o(u,d,f,h){var p=0,g=0;if(u==null||(p=i(u,f))!==(g=i(d,f))||c(u,d)<0^f>0)do h.point(p===0||p===3?e:n,p>1?r:t);while((p=(p+f+4)%4)!==g);else h.point(d[0],d[1])}function i(u,d){return $n(u[0]-e)<Xt?d>0?0:3:$n(u[0]-n)<Xt?d>0?2:1:$n(u[1]-t)<Xt?d>0?1:0:d>0?3:2}function a(u,d){return c(u.x,d.x)}function c(u,d){var f=i(u,1),h=i(d,1);return f!==h?f-h:f===0?d[1]-u[1]:f===1?u[0]-d[0]:f===2?u[1]-d[1]:d[0]-u[0]}return function(u){var d=u,f=XQ(),h,p,g,b,x,y,S,w,C,N,k,_={point:E,lineStart:T,lineEnd:F,polygonStart:j,polygonEnd:I};function E(R,B){s(R,B)&&d.point(R,B)}function D(){for(var R=0,B=0,z=p.length;B<z;++B)for(var U=p[B],Y=1,O=U.length,K=U[0],q,M,G=K[0],L=K[1];Y<O;++Y)q=G,M=L,K=U[Y],G=K[0],L=K[1],M<=r?L>r&&(G-q)*(r-M)>(L-M)*(e-q)&&++R:L<=r&&(G-q)*(r-M)<(L-M)*(e-q)&&--R;return R}function j(){d=f,h=[],p=[],k=!0}function I(){var R=D(),B=k&&R,z=(h=YQ(h)).length;(B||z)&&(u.polygonStart(),B&&(u.lineStart(),o(null,null,1,u),u.lineEnd()),z&&QQ(h,a,R,o,u),u.polygonEnd()),d=u,h=p=g=null}function T(){_.point=P,p&&p.push(g=[]),N=!0,C=!1,S=w=NaN}function F(){h&&(P(b,x),y&&C&&f.rejoin(),h.push(f.result())),_.point=E,C&&d.lineEnd()}function P(R,B){var z=s(R,B);if(p&&g.push([R,B]),N)b=R,x=B,y=z,N=!1,z&&(d.lineStart(),d.point(R,B));else if(z&&C)d.point(R,B);else{var U=[S=Math.max(u1,Math.min(jx,S)),w=Math.max(u1,Math.min(jx,w))],Y=[R=Math.max(u1,Math.min(jx,R)),B=Math.max(u1,Math.min(jx,B))];e2e(U,Y,e,t,n,r)?(C||(d.lineStart(),d.point(U[0],U[1])),d.point(Y[0],Y[1]),z||d.lineEnd(),k=!1):z&&(d.lineStart(),d.point(R,B),k=!1)}S=R,w=B,C=z}return _}}var MM,AM,OS,LS,Km={sphere:Cs,point:Cs,lineStart:n2e,lineEnd:Cs,polygonStart:Cs,polygonEnd:Cs};function n2e(){Km.point=s2e,Km.lineEnd=r2e}function r2e(){Km.point=Km.lineEnd=Cs}function s2e(e,t){e*=cr,t*=cr,AM=e,OS=tn(t),LS=ln(t),Km.point=o2e}function o2e(e,t){e*=cr,t*=cr;var n=tn(t),r=ln(t),s=$n(e-AM),o=ln(s),i=tn(s),a=r*i,c=LS*n-OS*r*o,u=OS*n+LS*r*o;MM.add(jl(Fo(a*a+c*c),u)),AM=e,OS=n,LS=r}function i2e(e){return MM=new od,df(e,Km),+MM}var RM=[null,null],a2e={type:"LineString",coordinates:RM};function FM(e,t){return RM[0]=e,RM[1]=t,i2e(a2e)}var O6={Feature:function(e,t){return GC(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,s=n.length;++r<s;)if(GC(n[r].geometry,t))return!0;return!1}},L6={Sphere:function(){return!0},Point:function(e,t){return $6(e.coordinates,t)},MultiPoint:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if($6(n[r],t))return!0;return!1},LineString:function(e,t){return z6(e.coordinates,t)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(z6(n[r],t))return!0;return!1},Polygon:function(e,t){return B6(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(B6(n[r],t))return!0;return!1},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,s=n.length;++r<s;)if(GC(n[r],t))return!0;return!1}};function GC(e,t){return e&&L6.hasOwnProperty(e.type)?L6[e.type](e,t):!1}function $6(e,t){return FM(e,t)===0}function z6(e,t){for(var n,r,s,o=0,i=e.length;o<i;o++){if(r=FM(e[o],t),r===0||o>0&&(s=FM(e[o],e[o-1]),s>0&&n<=s&&r<=s&&(n+r-s)*(1-Math.pow((n-r)/s,2))<gO*s))return!0;n=r}return!1}function B6(e,t){return!!JQ(e.map(l2e),tJ(t))}function l2e(e){return e=e.map(tJ),e.pop(),e}function tJ(e){return[e[0]*cr,e[1]*cr]}function c2e(e,t){return(e&&O6.hasOwnProperty(e.type)?O6[e.type]:GC)(e,t)}function V6(e,t,n){var r=Xp(e,t-Xt,n).concat(t);return function(s){return r.map(function(o){return[s,o]})}}function H6(e,t,n){var r=Xp(e,t-Xt,n).concat(t);return function(s){return r.map(function(o){return[o,s]})}}function nJ(){var e,t,n,r,s,o,i,a,c=10,u=c,d=90,f=360,h,p,g,b,x=2.5;function y(){return{type:"MultiLineString",coordinates:S()}}function S(){return Xp(i1(r/d)*d,n,d).map(g).concat(Xp(i1(a/f)*f,i,f).map(b)).concat(Xp(i1(t/c)*c,e,c).filter(function(w){return $n(w%d)>Xt}).map(h)).concat(Xp(i1(o/u)*u,s,u).filter(function(w){return $n(w%f)>Xt}).map(p))}return y.lines=function(){return S().map(function(w){return{type:"LineString",coordinates:w}})},y.outline=function(){return{type:"Polygon",coordinates:[g(r).concat(b(i).slice(1),g(n).reverse().slice(1),b(a).reverse().slice(1))]}},y.extent=function(w){return arguments.length?y.extentMajor(w).extentMinor(w):y.extentMinor()},y.extentMajor=function(w){return arguments.length?(r=+w[0][0],n=+w[1][0],a=+w[0][1],i=+w[1][1],r>n&&(w=r,r=n,n=w),a>i&&(w=a,a=i,i=w),y.precision(x)):[[r,a],[n,i]]},y.extentMinor=function(w){return arguments.length?(t=+w[0][0],e=+w[1][0],o=+w[0][1],s=+w[1][1],t>e&&(w=t,t=e,e=w),o>s&&(w=o,o=s,s=w),y.precision(x)):[[t,o],[e,s]]},y.step=function(w){return arguments.length?y.stepMajor(w).stepMinor(w):y.stepMinor()},y.stepMajor=function(w){return arguments.length?(d=+w[0],f=+w[1],y):[d,f]},y.stepMinor=function(w){return arguments.length?(c=+w[0],u=+w[1],y):[c,u]},y.precision=function(w){return arguments.length?(x=+w,h=V6(o,s,90),p=H6(t,e,x),g=V6(a,i,90),b=H6(r,n,x),y):x},y.extentMajor([[-180,-90+Xt],[180,90-Xt]]).extentMinor([[-180,-80-Xt],[180,80+Xt]])}function u2e(){return nJ()()}const PM=e=>e;var TD=new od,OM=new od,rJ,sJ,LM,$M,hc={point:Cs,lineStart:Cs,lineEnd:Cs,polygonStart:function(){hc.lineStart=d2e,hc.lineEnd=h2e},polygonEnd:function(){hc.lineStart=hc.lineEnd=hc.point=Cs,TD.add($n(OM)),OM=new od},result:function(){var e=TD/2;return TD=new od,e}};function d2e(){hc.point=f2e}function f2e(e,t){hc.point=oJ,rJ=LM=e,sJ=$M=t}function oJ(e,t){OM.add($M*e-LM*t),LM=e,$M=t}function h2e(){oJ(rJ,sJ)}var Zm=1/0,KC=Zm,Gy=-Zm,ZC=Gy,XC={point:p2e,lineStart:Cs,lineEnd:Cs,polygonStart:Cs,polygonEnd:Cs,result:function(){var e=[[Zm,KC],[Gy,ZC]];return Gy=ZC=-(KC=Zm=1/0),e}};function p2e(e,t){e<Zm&&(Zm=e),e>Gy&&(Gy=e),t<KC&&(KC=t),t>ZC&&(ZC=t)}var zM=0,BM=0,Ex=0,QC=0,JC=0,Qp=0,VM=0,HM=0,Dx=0,iJ,aJ,rl,sl,Hi={point:gh,lineStart:U6,lineEnd:W6,polygonStart:function(){Hi.lineStart=b2e,Hi.lineEnd=x2e},polygonEnd:function(){Hi.point=gh,Hi.lineStart=U6,Hi.lineEnd=W6},result:function(){var e=Dx?[VM/Dx,HM/Dx]:Qp?[QC/Qp,JC/Qp]:Ex?[zM/Ex,BM/Ex]:[NaN,NaN];return zM=BM=Ex=QC=JC=Qp=VM=HM=Dx=0,e}};function gh(e,t){zM+=e,BM+=t,++Ex}function U6(){Hi.point=m2e}function m2e(e,t){Hi.point=g2e,gh(rl=e,sl=t)}function g2e(e,t){var n=e-rl,r=t-sl,s=Fo(n*n+r*r);QC+=s*(rl+e)/2,JC+=s*(sl+t)/2,Qp+=s,gh(rl=e,sl=t)}function W6(){Hi.point=gh}function b2e(){Hi.point=y2e}function x2e(){lJ(iJ,aJ)}function y2e(e,t){Hi.point=lJ,gh(iJ=rl=e,aJ=sl=t)}function lJ(e,t){var n=e-rl,r=t-sl,s=Fo(n*n+r*r);QC+=s*(rl+e)/2,JC+=s*(sl+t)/2,Qp+=s,s=sl*e-rl*t,VM+=s*(rl+e),HM+=s*(sl+t),Dx+=s*3,gh(rl=e,sl=t)}function cJ(e){this._context=e}cJ.prototype={_radius:4.5,pointRadius:function(e){return this._radius=e,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){this._line===0&&this._context.closePath(),this._point=NaN},point:function(e,t){switch(this._point){case 0:{this._context.moveTo(e,t),this._point=1;break}case 1:{this._context.lineTo(e,t);break}default:{this._context.moveTo(e+this._radius,t),this._context.arc(e,t,this._radius,0,wi);break}}},result:Cs};var UM=new od,MD,uJ,dJ,Ix,Tx,Ky={point:Cs,lineStart:function(){Ky.point=v2e},lineEnd:function(){MD&&fJ(uJ,dJ),Ky.point=Cs},polygonStart:function(){MD=!0},polygonEnd:function(){MD=null},result:function(){var e=+UM;return UM=new od,e}};function v2e(e,t){Ky.point=fJ,uJ=Ix=e,dJ=Tx=t}function fJ(e,t){Ix-=e,Tx-=t,UM.add(Fo(Ix*Ix+Tx*Tx)),Ix=e,Tx=t}let q6,eN,Y6,G6;class K6{constructor(t){this._append=t==null?hJ:w2e(t),this._radius=4.5,this._=""}pointRadius(t){return this._radius=+t,this}polygonStart(){this._line=0}polygonEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){this._line===0&&(this._+="Z"),this._point=NaN}point(t,n){switch(this._point){case 0:{this._append`M${t},${n}`,this._point=1;break}case 1:{this._append`L${t},${n}`;break}default:{if(this._append`M${t},${n}`,this._radius!==Y6||this._append!==eN){const r=this._radius,s=this._;this._="",this._append`m0,${r}a${r},${r} 0 1,1 0,${-2*r}a${r},${r} 0 1,1 0,${2*r}z`,Y6=r,eN=this._append,G6=this._,this._=s}this._+=G6;break}}}result(){const t=this._;return this._="",t.length?t:null}}function hJ(e){let t=1;this._+=e[0];for(const n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function w2e(e){const t=Math.floor(e);if(!(t>=0))throw new RangeError(`invalid digits: ${e}`);if(t>15)return hJ;if(t!==q6){const n=10**t;q6=t,eN=function(s){let o=1;this._+=s[0];for(const i=s.length;o<i;++o)this._+=Math.round(arguments[o]*n)/n+s[o]}}return eN}function Z6(e,t){let n=3,r=4.5,s,o;function i(a){return a&&(typeof r=="function"&&o.pointRadius(+r.apply(this,arguments)),df(a,s(o))),o.result()}return i.area=function(a){return df(a,s(hc)),hc.result()},i.measure=function(a){return df(a,s(Ky)),Ky.result()},i.bounds=function(a){return df(a,s(XC)),XC.result()},i.centroid=function(a){return df(a,s(Hi)),Hi.result()},i.projection=function(a){return arguments.length?(s=a==null?(e=null,PM):(e=a).stream,i):e},i.context=function(a){return arguments.length?(o=a==null?(t=null,new K6(n)):new cJ(t=a),typeof r!="function"&&o.pointRadius(r),i):t},i.pointRadius=function(a){return arguments.length?(r=typeof a=="function"?a:(o.pointRadius(+a),+a),i):r},i.digits=function(a){if(!arguments.length)return n;if(a==null)n=null;else{const c=Math.floor(a);if(!(c>=0))throw new RangeError(`invalid digits: ${a}`);n=c}return t===null&&(o=new K6(n)),i},i.projection(e).digits(n).context(t)}function xO(e){return function(t){var n=new WM;for(var r in e)n[r]=e[r];return n.stream=t,n}}function WM(){}WM.prototype={constructor:WM,point:function(e,t){this.stream.point(e,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};function yO(e,t,n){var r=e.clipExtent&&e.clipExtent();return e.scale(150).translate([0,0]),r!=null&&e.clipExtent(null),df(n,e.stream(XC)),t(XC.result()),r!=null&&e.clipExtent(r),e}function vO(e,t,n){return yO(e,function(r){var s=t[1][0]-t[0][0],o=t[1][1]-t[0][1],i=Math.min(s/(r[1][0]-r[0][0]),o/(r[1][1]-r[0][1])),a=+t[0][0]+(s-i*(r[1][0]+r[0][0]))/2,c=+t[0][1]+(o-i*(r[1][1]+r[0][1]))/2;e.scale(150*i).translate([a,c])},n)}function pJ(e,t,n){return vO(e,[[0,0],t],n)}function mJ(e,t,n){return yO(e,function(r){var s=+t,o=s/(r[1][0]-r[0][0]),i=(s-o*(r[1][0]+r[0][0]))/2,a=-o*r[0][1];e.scale(150*o).translate([i,a])},n)}function gJ(e,t,n){return yO(e,function(r){var s=+t,o=s/(r[1][1]-r[0][1]),i=-o*r[0][0],a=(s-o*(r[1][1]+r[0][1]))/2;e.scale(150*o).translate([i,a])},n)}var X6=16,S2e=ln(30*cr);function Q6(e,t){return+t?N2e(e,t):C2e(e)}function C2e(e){return xO({point:function(t,n){t=e(t,n),this.stream.point(t[0],t[1])}})}function N2e(e,t){function n(r,s,o,i,a,c,u,d,f,h,p,g,b,x){var y=u-r,S=d-s,w=y*y+S*S;if(w>4*t&&b--){var C=i+h,N=a+p,k=c+g,_=Fo(C*C+N*N+k*k),E=Xi(k/=_),D=$n($n(k)-1)<Xt||$n(o-f)<Xt?(o+f)/2:jl(N,C),j=e(D,E),I=j[0],T=j[1],F=I-r,P=T-s,R=S*F-y*P;(R*R/w>t||$n((y*F+S*P)/w-.5)>.3||i*h+a*p+c*g<S2e)&&(n(r,s,o,i,a,c,I,T,D,C/=_,N/=_,k,b,x),x.point(I,T),n(I,T,D,C,N,k,u,d,f,h,p,g,b,x))}}return function(r){var s,o,i,a,c,u,d,f,h,p,g,b,x={point:y,lineStart:S,lineEnd:C,polygonStart:function(){r.polygonStart(),x.lineStart=N},polygonEnd:function(){r.polygonEnd(),x.lineStart=S}};function y(E,D){E=e(E,D),r.point(E[0],E[1])}function S(){f=NaN,x.point=w,r.lineStart()}function w(E,D){var j=Gm([E,D]),I=e(E,D);n(f,h,d,p,g,b,f=I[0],h=I[1],d=E,p=j[0],g=j[1],b=j[2],X6,r),r.point(f,h)}function C(){x.point=y,r.lineEnd()}function N(){S(),x.point=k,x.lineEnd=_}function k(E,D){w(s=E,D),o=f,i=h,a=p,c=g,u=b,x.point=w}function _(){n(f,h,d,p,g,b,o,i,s,a,c,u,X6,r),x.lineEnd=C,C()}return x}}var k2e=xO({point:function(e,t){this.stream.point(e*cr,t*cr)}});function _2e(e){return xO({point:function(t,n){var r=e(t,n);return this.stream.point(r[0],r[1])}})}function j2e(e,t,n,r,s){function o(i,a){return i*=r,a*=s,[t+e*i,n-e*a]}return o.invert=function(i,a){return[(i-t)/e*r,(n-a)/e*s]},o}function J6(e,t,n,r,s,o){if(!o)return j2e(e,t,n,r,s);var i=ln(o),a=tn(o),c=i*e,u=a*e,d=i/e,f=a/e,h=(a*n-i*t)/e,p=(a*t+i*n)/e;function g(b,x){return b*=r,x*=s,[c*b-u*x+t,n-u*b-c*x]}return g.invert=function(b,x){return[r*(d*b-f*x+h),s*(p-f*b-d*x)]},g}function Jc(e){return bJ(function(){return e})()}function bJ(e){var t,n=150,r=480,s=250,o=0,i=0,a=0,c=0,u=0,d,f=0,h=1,p=1,g=null,b=P6,x=null,y,S,w,C=PM,N=.5,k,_,E,D,j;function I(R){return E(R[0]*cr,R[1]*cr)}function T(R){return R=E.invert(R[0],R[1]),R&&[R[0]*Do,R[1]*Do]}I.stream=function(R){return D&&j===R?D:D=k2e(_2e(d)(b(k(C(j=R)))))},I.preclip=function(R){return arguments.length?(b=R,g=void 0,P()):b},I.postclip=function(R){return arguments.length?(C=R,x=y=S=w=null,P()):C},I.clipAngle=function(R){return arguments.length?(b=+R?JTe(g=R*cr):(g=null,P6),P()):g*Do},I.clipExtent=function(R){return arguments.length?(C=R==null?(x=y=S=w=null,PM):t2e(x=+R[0][0],y=+R[0][1],S=+R[1][0],w=+R[1][1]),P()):x==null?null:[[x,y],[S,w]]},I.scale=function(R){return arguments.length?(n=+R,F()):n},I.translate=function(R){return arguments.length?(r=+R[0],s=+R[1],F()):[r,s]},I.center=function(R){return arguments.length?(o=R[0]%360*cr,i=R[1]%360*cr,F()):[o*Do,i*Do]},I.rotate=function(R){return arguments.length?(a=R[0]%360*cr,c=R[1]%360*cr,u=R.length>2?R[2]%360*cr:0,F()):[a*Do,c*Do,u*Do]},I.angle=function(R){return arguments.length?(f=R%360*cr,F()):f*Do},I.reflectX=function(R){return arguments.length?(h=R?-1:1,F()):h<0},I.reflectY=function(R){return arguments.length?(p=R?-1:1,F()):p<0},I.precision=function(R){return arguments.length?(k=Q6(_,N=R*R),P()):Fo(N)},I.fitExtent=function(R,B){return vO(I,R,B)},I.fitSize=function(R,B){return pJ(I,R,B)},I.fitWidth=function(R,B){return mJ(I,R,B)},I.fitHeight=function(R,B){return gJ(I,R,B)};function F(){var R=J6(n,0,0,h,p,f).apply(null,t(o,i)),B=J6(n,r-R[0],s-R[1],h,p,f);return d=ZQ(a,c,u),_=IM(t,B),E=IM(d,_),k=Q6(_,N),P()}function P(){return D=j=null,I}return function(){return t=e.apply(this,arguments),I.invert=t.invert&&T,F()}}function wO(e){var t=0,n=vn/3,r=bJ(e),s=r(t,n);return s.parallels=function(o){return arguments.length?r(t=o[0]*cr,n=o[1]*cr):[t*Do,n*Do]},s}function E2e(e){var t=ln(e);function n(r,s){return[r*t,tn(s)/t]}return n.invert=function(r,s){return[r/t,Xi(s*t)]},n}function D2e(e,t){var n=tn(e),r=(n+tn(t))/2;if($n(r)<Xt)return E2e(e);var s=1+n*(2*r-n),o=Fo(s)/r;function i(a,c){var u=Fo(s-2*r*tn(c))/r;return[u*tn(a*=r),o-u*ln(a)]}return i.invert=function(a,c){var u=o-c,d=jl(a,$n(u))*Yi(u);return u*r<0&&(d-=vn*Yi(a)*Yi(u)),[d/r,Xi((s-(a*a+u*u)*r*r)/(2*r))]},i}function tN(){return wO(D2e).scale(155.424).center([0,33.6442])}function xJ(){return tN().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function I2e(e){var t=e.length;return{point:function(n,r){for(var s=-1;++s<t;)e[s].point(n,r)},sphere:function(){for(var n=-1;++n<t;)e[n].sphere()},lineStart:function(){for(var n=-1;++n<t;)e[n].lineStart()},lineEnd:function(){for(var n=-1;++n<t;)e[n].lineEnd()},polygonStart:function(){for(var n=-1;++n<t;)e[n].polygonStart()},polygonEnd:function(){for(var n=-1;++n<t;)e[n].polygonEnd()}}}function T2e(){var e,t,n=xJ(),r,s=tN().rotate([154,0]).center([-2,58.5]).parallels([55,65]),o,i=tN().rotate([157,0]).center([-3,19.9]).parallels([8,18]),a,c,u={point:function(h,p){c=[h,p]}};function d(h){var p=h[0],g=h[1];return c=null,r.point(p,g),c||(o.point(p,g),c)||(a.point(p,g),c)}d.invert=function(h){var p=n.scale(),g=n.translate(),b=(h[0]-g[0])/p,x=(h[1]-g[1])/p;return(x>=.12&&x<.234&&b>=-.425&&b<-.214?s:x>=.166&&x<.234&&b>=-.214&&b<-.115?i:n).invert(h)},d.stream=function(h){return e&&t===h?e:e=I2e([n.stream(t=h),s.stream(h),i.stream(h)])},d.precision=function(h){return arguments.length?(n.precision(h),s.precision(h),i.precision(h),f()):n.precision()},d.scale=function(h){return arguments.length?(n.scale(h),s.scale(h*.35),i.scale(h),d.translate(n.translate())):n.scale()},d.translate=function(h){if(!arguments.length)return n.translate();var p=n.scale(),g=+h[0],b=+h[1];return r=n.translate(h).clipExtent([[g-.455*p,b-.238*p],[g+.455*p,b+.238*p]]).stream(u),o=s.translate([g-.307*p,b+.201*p]).clipExtent([[g-.425*p+Xt,b+.12*p+Xt],[g-.214*p-Xt,b+.234*p-Xt]]).stream(u),a=i.translate([g-.205*p,b+.212*p]).clipExtent([[g-.214*p+Xt,b+.166*p+Xt],[g-.115*p-Xt,b+.234*p-Xt]]).stream(u),f()},d.fitExtent=function(h,p){return vO(d,h,p)},d.fitSize=function(h,p){return pJ(d,h,p)},d.fitWidth=function(h,p){return mJ(d,h,p)},d.fitHeight=function(h,p){return gJ(d,h,p)};function f(){return e=t=null,d}return d.scale(1070)}function yJ(e){return function(t,n){var r=ln(t),s=ln(n),o=e(r*s);return o===1/0?[2,0]:[o*s*tn(t),o*tn(n)]}}function Nv(e){return function(t,n){var r=Fo(t*t+n*n),s=e(r),o=tn(s),i=ln(s);return[jl(t*o,r*i),Xi(r&&n*o/r)]}}var vJ=yJ(function(e){return Fo(2/(1+e))});vJ.invert=Nv(function(e){return 2*Xi(e/2)});function M2e(){return Jc(vJ).scale(124.75).clipAngle(180-.001)}var wJ=yJ(function(e){return(e=KQ(e))&&e/tn(e)});wJ.invert=Nv(function(e){return e});function A2e(){return Jc(wJ).scale(79.4188).clipAngle(180-.001)}function __(e,t){return[e,WC(bO((Gr+t)/2))]}__.invert=function(e,t){return[e,2*Dg(GQ(t))-Gr]};function R2e(){return SJ(__).scale(961/wi)}function SJ(e){var t=Jc(e),n=t.center,r=t.scale,s=t.translate,o=t.clipExtent,i=null,a,c,u;t.scale=function(f){return arguments.length?(r(f),d()):r()},t.translate=function(f){return arguments.length?(s(f),d()):s()},t.center=function(f){return arguments.length?(n(f),d()):n()},t.clipExtent=function(f){return arguments.length?(f==null?i=a=c=u=null:(i=+f[0][0],a=+f[0][1],c=+f[1][0],u=+f[1][1]),d()):i==null?null:[[i,a],[c,u]]};function d(){var f=vn*r(),h=t(qTe(t.rotate()).invert([0,0]));return o(i==null?[[h[0]-f,h[1]-f],[h[0]+f,h[1]+f]]:e===__?[[Math.max(h[0]-f,i),a],[Math.min(h[0]+f,c),u]]:[[i,Math.max(h[1]-f,a)],[c,Math.min(h[1]+f,u)]])}return d()}function d1(e){return bO((Gr+e)/2)}function F2e(e,t){var n=ln(e),r=e===t?tn(e):WC(n/ln(t))/WC(d1(t)/d1(e)),s=n*ED(d1(e),r)/r;if(!r)return __;function o(i,a){s>0?a<-Gr+Xt&&(a=-Gr+Xt):a>Gr-Xt&&(a=Gr-Xt);var c=s/ED(d1(a),r);return[c*tn(r*i),s-c*ln(r*i)]}return o.invert=function(i,a){var c=s-a,u=Yi(r)*Fo(i*i+c*c),d=jl(i,$n(c))*Yi(c);return c*r<0&&(d-=vn*Yi(i)*Yi(c)),[d/r,2*Dg(ED(s/u,1/r))-Gr]},o}function P2e(){return wO(F2e).scale(109.5).parallels([30,30])}function nN(e,t){return[e,t]}nN.invert=nN;function O2e(){return Jc(nN).scale(152.63)}function L2e(e,t){var n=ln(e),r=e===t?tn(e):(n-ln(t))/(t-e),s=n/r+e;if($n(r)<Xt)return nN;function o(i,a){var c=s-a,u=r*i;return[c*tn(u),s-c*ln(u)]}return o.invert=function(i,a){var c=s-a,u=jl(i,$n(c))*Yi(c);return c*r<0&&(u-=vn*Yi(i)*Yi(c)),[u/r,s-Yi(r)*Fo(i*i+c*c)]},o}function $2e(){return wO(L2e).scale(131.154).center([0,13.9389])}var Jx=1.340264,ey=-.081106,ty=893e-6,ny=.003796,rN=Fo(3)/2,z2e=12;function CJ(e,t){var n=Xi(rN*tn(t)),r=n*n,s=r*r*r;return[e*ln(n)/(rN*(Jx+3*ey*r+s*(7*ty+9*ny*r))),n*(Jx+ey*r+s*(ty+ny*r))]}CJ.invert=function(e,t){for(var n=t,r=n*n,s=r*r*r,o=0,i,a,c;o<z2e&&(a=n*(Jx+ey*r+s*(ty+ny*r))-t,c=Jx+3*ey*r+s*(7*ty+9*ny*r),n-=i=a/c,r=n*n,s=r*r*r,!($n(i)<gO));++o);return[rN*e*(Jx+3*ey*r+s*(7*ty+9*ny*r))/ln(n),Xi(tn(n)/rN)]};function B2e(){return Jc(CJ).scale(177.158)}function NJ(e,t){var n=ln(t),r=ln(e)*n;return[n*tn(e)/r,tn(t)/r]}NJ.invert=Nv(Dg);function V2e(){return Jc(NJ).scale(144.049).clipAngle(60)}function kJ(e,t){var n=t*t,r=n*n;return[e*(.8707-.131979*n+r*(-.013791+r*(.003971*n-.001529*r))),t*(1.007226+n*(.015085+r*(-.044475+.028874*n-.005916*r)))]}kJ.invert=function(e,t){var n=t,r=25,s;do{var o=n*n,i=o*o;n-=s=(n*(1.007226+o*(.015085+i*(-.044475+.028874*o-.005916*i)))-t)/(1.007226+o*(.015085*3+i*(-.044475*7+.028874*9*o-.005916*11*i)))}while($n(s)>Xt&&--r>0);return[e/(.8707+(o=n*n)*(-.131979+o*(-.013791+o*o*o*(.003971-.001529*o)))),n]};function H2e(){return Jc(kJ).scale(175.295)}function _J(e,t){return[ln(t)*tn(e),tn(t)]}_J.invert=Nv(Xi);function U2e(){return Jc(_J).scale(249.5).clipAngle(90+Xt)}function jJ(e,t){var n=ln(t),r=1+ln(e)*n;return[n*tn(e)/r,tn(t)/r]}jJ.invert=Nv(function(e){return 2*Dg(e)});function W2e(){return Jc(jJ).scale(250).clipAngle(142)}function EJ(e,t){return[WC(bO((Gr+t)/2)),-e]}EJ.invert=function(e,t){return[-t,2*Dg(GQ(e))-Gr]};function q2e(){var e=SJ(EJ),t=e.center,n=e.rotate;return e.center=function(r){return arguments.length?t([-r[1],r[0]]):(r=t(),[r[1],-r[0]])},e.rotate=function(r){return arguments.length?n([r[0],r[1],r.length>2?r[2]+90:90]):(r=n(),[r[0],r[1],r[2]-90])},n([0,0,90]).scale(159.155)}function Wn(e){for(var t=e.length/6|0,n=new Array(t),r=0;r<t;)n[r]="#"+e.slice(r*6,++r*6);return n}function j_(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function SO(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Ig(){}var bh=.7,Xm=1/bh,am="\\s*([+-]?\\d+)\\s*",Zy="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",dl="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Y2e=/^#([0-9a-f]{3,8})$/,G2e=new RegExp(`^rgb\\(${am},${am},${am}\\)$`),K2e=new RegExp(`^rgb\\(${dl},${dl},${dl}\\)$`),Z2e=new RegExp(`^rgba\\(${am},${am},${am},${Zy}\\)$`),X2e=new RegExp(`^rgba\\(${dl},${dl},${dl},${Zy}\\)$`),Q2e=new RegExp(`^hsl\\(${Zy},${dl},${dl}\\)$`),J2e=new RegExp(`^hsla\\(${Zy},${dl},${dl},${Zy}\\)$`),eB={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};j_(Ig,CO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:tB,formatHex:tB,formatHex8:eMe,formatHsl:tMe,formatRgb:nB,toString:nB});function tB(){return this.rgb().formatHex()}function eMe(){return this.rgb().formatHex8()}function tMe(){return IJ(this).formatHsl()}function nB(){return this.rgb().formatRgb()}function CO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=Y2e.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?rB(t):n===3?new io(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?f1(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?f1(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=G2e.exec(e))?new io(t[1],t[2],t[3],1):(t=K2e.exec(e))?new io(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Z2e.exec(e))?f1(t[1],t[2],t[3],t[4]):(t=X2e.exec(e))?f1(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Q2e.exec(e))?iB(t[1],t[2]/100,t[3]/100,1):(t=J2e.exec(e))?iB(t[1],t[2]/100,t[3]/100,t[4]):eB.hasOwnProperty(e)?rB(eB[e]):e==="transparent"?new io(NaN,NaN,NaN,0):null}function rB(e){return new io(e>>16&255,e>>8&255,e&255,1)}function f1(e,t,n,r){return r<=0&&(e=t=n=NaN),new io(e,t,n,r)}function DJ(e){return e instanceof Ig||(e=CO(e)),e?(e=e.rgb(),new io(e.r,e.g,e.b,e.opacity)):new io}function Xy(e,t,n,r){return arguments.length===1?DJ(e):new io(e,t,n,r??1)}function io(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}j_(io,Xy,SO(Ig,{brighter(e){return e=e==null?Xm:Math.pow(Xm,e),new io(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?bh:Math.pow(bh,e),new io(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new io(Gf(this.r),Gf(this.g),Gf(this.b),sN(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:sB,formatHex:sB,formatHex8:nMe,formatRgb:oB,toString:oB}));function sB(){return`#${Sf(this.r)}${Sf(this.g)}${Sf(this.b)}`}function nMe(){return`#${Sf(this.r)}${Sf(this.g)}${Sf(this.b)}${Sf((isNaN(this.opacity)?1:this.opacity)*255)}`}function oB(){const e=sN(this.opacity);return`${e===1?"rgb(":"rgba("}${Gf(this.r)}, ${Gf(this.g)}, ${Gf(this.b)}${e===1?")":`, ${e})`}`}function sN(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Gf(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Sf(e){return e=Gf(e),(e<16?"0":"")+e.toString(16)}function iB(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new pa(e,t,n,r)}function IJ(e){if(e instanceof pa)return new pa(e.h,e.s,e.l,e.opacity);if(e instanceof Ig||(e=CO(e)),!e)return new pa;if(e instanceof pa)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),o=Math.max(t,n,r),i=NaN,a=o-s,c=(o+s)/2;return a?(t===o?i=(n-r)/a+(n<r)*6:n===o?i=(r-t)/a+2:i=(t-n)/a+4,a/=c<.5?o+s:2-o-s,i*=60):a=c>0&&c<1?0:i,new pa(i,a,c,e.opacity)}function rMe(e,t,n,r){return arguments.length===1?IJ(e):new pa(e,t,n,r??1)}function pa(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}j_(pa,rMe,SO(Ig,{brighter(e){return e=e==null?Xm:Math.pow(Xm,e),new pa(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?bh:Math.pow(bh,e),new pa(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new io(AD(e>=240?e-240:e+120,s,r),AD(e,s,r),AD(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new pa(aB(this.h),h1(this.s),h1(this.l),sN(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=sN(this.opacity);return`${e===1?"hsl(":"hsla("}${aB(this.h)}, ${h1(this.s)*100}%, ${h1(this.l)*100}%${e===1?")":`, ${e})`}`}}));function aB(e){return e=(e||0)%360,e<0?e+360:e}function h1(e){return Math.max(0,Math.min(1,e||0))}function AD(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const sMe=Math.PI/180,oMe=180/Math.PI;var TJ=-.14861,NO=1.78277,kO=-.29227,E_=-.90649,Qy=1.97294,lB=Qy*E_,cB=Qy*NO,uB=NO*kO-E_*TJ;function iMe(e){if(e instanceof Kf)return new Kf(e.h,e.s,e.l,e.opacity);e instanceof io||(e=DJ(e));var t=e.r/255,n=e.g/255,r=e.b/255,s=(uB*r+lB*t-cB*n)/(uB+lB-cB),o=r-s,i=(Qy*(n-s)-kO*o)/E_,a=Math.sqrt(i*i+o*o)/(Qy*s*(1-s)),c=a?Math.atan2(i,o)*oMe-120:NaN;return new Kf(c<0?c+360:c,a,s,e.opacity)}function El(e,t,n,r){return arguments.length===1?iMe(e):new Kf(e,t,n,r??1)}function Kf(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}j_(Kf,El,SO(Ig,{brighter(e){return e=e==null?Xm:Math.pow(Xm,e),new Kf(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?bh:Math.pow(bh,e),new Kf(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=isNaN(this.h)?0:(this.h+120)*sMe,t=+this.l,n=isNaN(this.s)?0:this.s*t*(1-t),r=Math.cos(e),s=Math.sin(e);return new io(255*(t+n*(TJ*r+NO*s)),255*(t+n*(kO*r+E_*s)),255*(t+n*(Qy*r)),this.opacity)}}));function aMe(e,t,n,r,s){var o=e*e,i=o*e;return((1-3*e+3*o-i)*t+(4-6*o+3*i)*n+(1+3*e+3*o-3*i)*r+i*s)/6}function lMe(e){var t=e.length-1;return function(n){var r=n<=0?n=0:n>=1?(n=1,t-1):Math.floor(n*t),s=e[r],o=e[r+1],i=r>0?e[r-1]:2*s-o,a=r<t-1?e[r+2]:2*o-s;return aMe((n-r/t)*t,i,s,o,a)}}const _O=e=>()=>e;function MJ(e,t){return function(n){return e+n*t}}function cMe(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function uMe(e,t){var n=t-e;return n?MJ(e,n>180||n<-180?n-360*Math.round(n/360):n):_O(isNaN(e)?t:e)}function dMe(e){return(e=+e)==1?lm:function(t,n){return n-t?cMe(t,n,e):_O(isNaN(t)?n:t)}}function lm(e,t){var n=t-e;return n?MJ(e,n):_O(isNaN(e)?t:e)}(function e(t){var n=dMe(t);function r(s,o){var i=n((s=Xy(s)).r,(o=Xy(o)).r),a=n(s.g,o.g),c=n(s.b,o.b),u=lm(s.opacity,o.opacity);return function(d){return s.r=i(d),s.g=a(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function fMe(e){return function(t){var n=t.length,r=new Array(n),s=new Array(n),o=new Array(n),i,a;for(i=0;i<n;++i)a=Xy(t[i]),r[i]=a.r||0,s[i]=a.g||0,o[i]=a.b||0;return r=e(r),s=e(s),o=e(o),a.opacity=1,function(c){return a.r=r(c),a.g=s(c),a.b=o(c),a+""}}}var hMe=fMe(lMe);function AJ(e){return function t(n){n=+n;function r(s,o){var i=e((s=El(s)).h,(o=El(o)).h),a=lm(s.s,o.s),c=lm(s.l,o.l),u=lm(s.opacity,o.opacity);return function(d){return s.h=i(d),s.s=a(d),s.l=c(Math.pow(d,n)),s.opacity=u(d),s+""}}return r.gamma=t,r}(1)}AJ(uMe);var jO=AJ(lm);const xr=e=>hMe(e[e.length-1]);var pMe=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(Wn);const mMe=xr(pMe);var gMe=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(Wn);const bMe=xr(gMe);var xMe=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(Wn);const yMe=xr(xMe);var vMe=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(Wn);const wMe=xr(vMe);var SMe=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(Wn);const CMe=xr(SMe);var NMe=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(Wn);const kMe=xr(NMe);var _Me=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(Wn);const jMe=xr(_Me);var EMe=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(Wn);const DMe=xr(EMe);var IMe=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(Wn);const TMe=xr(IMe);var MMe=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(Wn);const AMe=xr(MMe);var RMe=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(Wn);const FMe=xr(RMe);var PMe=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(Wn);const OMe=xr(PMe);var LMe=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(Wn);const $Me=xr(LMe);var zMe=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(Wn);const BMe=xr(zMe);var VMe=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(Wn);const HMe=xr(VMe);var UMe=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(Wn);const WMe=xr(UMe);var qMe=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(Wn);const YMe=xr(qMe);var GMe=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(Wn);const KMe=xr(GMe);var ZMe=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(Wn);const XMe=xr(ZMe);var QMe=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(Wn);const JMe=xr(QMe);var eAe=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(Wn);const tAe=xr(eAe);var nAe=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(Wn);const rAe=xr(nAe);var sAe=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(Wn);const oAe=xr(sAe);var iAe=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(Wn);const aAe=xr(iAe);var lAe=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(Wn);const cAe=xr(lAe);var uAe=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(Wn);const dAe=xr(uAe);var fAe=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(Wn);const hAe=xr(fAe);function pAe(e){return e=Math.max(0,Math.min(1,e)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-e*(35.34-e*(2381.73-e*(6402.7-e*(7024.72-e*2710.57)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+e*(170.73+e*(52.82-e*(131.46-e*(176.58-e*67.37)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+e*(442.36-e*(2482.43-e*(6167.24-e*(6614.94-e*2475.67)))))))+")"}const mAe=jO(El(300,.5,0),El(-240,.5,1));var gAe=jO(El(-100,.75,.35),El(80,1.5,.8)),bAe=jO(El(260,.75,.35),El(80,1.5,.8)),p1=El();function xAe(e){(e<0||e>1)&&(e-=Math.floor(e));var t=Math.abs(e-.5);return p1.h=360*e-100,p1.s=1.5-1.5*t,p1.l=.8-.9*t,p1+""}var m1=Xy(),yAe=Math.PI/3,vAe=Math.PI*2/3;function wAe(e){var t;return e=(.5-e)*Math.PI,m1.r=255*(t=Math.sin(e))*t,m1.g=255*(t=Math.sin(e+yAe))*t,m1.b=255*(t=Math.sin(e+vAe))*t,m1+""}function SAe(e){return e=Math.max(0,Math.min(1,e)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+e*(1172.33-e*(10793.56-e*(33300.12-e*(38394.49-e*14825.05)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+e*(557.33+e*(1225.33-e*(3574.96-e*(1073.77+e*707.56)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+e*(3211.1-e*(15327.97-e*(27814-e*(22569.18-e*6838.66)))))))+")"}function D_(e){var t=e.length;return function(n){return e[Math.max(0,Math.min(t-1,Math.floor(n*t)))]}}const CAe=D_(Wn("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var NAe=D_(Wn("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),kAe=D_(Wn("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),_Ae=D_(Wn("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function jAe(e){return e}function EAe(e){if(e==null)return jAe;var t,n,r=e.scale[0],s=e.scale[1],o=e.translate[0],i=e.translate[1];return function(a,c){c||(t=n=0);var u=2,d=a.length,f=new Array(d);for(f[0]=(t+=a[0])*r+o,f[1]=(n+=a[1])*s+i;u<d;)f[u]=a[u],++u;return f}}function DAe(e,t){for(var n,r=e.length,s=r-t;s<--r;)n=e[s],e[s++]=e[r],e[r]=n}function IAe(e,t){return typeof t=="string"&&(t=e.objects[t]),t.type==="GeometryCollection"?{type:"FeatureCollection",features:t.geometries.map(function(n){return dB(e,n)})}:dB(e,t)}function dB(e,t){var n=t.id,r=t.bbox,s=t.properties==null?{}:t.properties,o=TAe(e,t);return n==null&&r==null?{type:"Feature",properties:s,geometry:o}:r==null?{type:"Feature",id:n,properties:s,geometry:o}:{type:"Feature",id:n,bbox:r,properties:s,geometry:o}}function TAe(e,t){var n=EAe(e.transform),r=e.arcs;function s(d,f){f.length&&f.pop();for(var h=r[d<0?~d:d],p=0,g=h.length;p<g;++p)f.push(n(h[p],p));d<0&&DAe(f,g)}function o(d){return n(d)}function i(d){for(var f=[],h=0,p=d.length;h<p;++h)s(d[h],f);return f.length<2&&f.push(f[0]),f}function a(d){for(var f=i(d);f.length<4;)f.push(f[0]);return f}function c(d){return d.map(a)}function u(d){var f=d.type,h;switch(f){case"GeometryCollection":return{type:f,geometries:d.geometries.map(u)};case"Point":h=o(d.coordinates);break;case"MultiPoint":h=d.coordinates.map(o);break;case"LineString":h=i(d.arcs);break;case"MultiLineString":h=d.arcs.map(i);break;case"Polygon":h=c(d.arcs);break;case"MultiPolygon":h=d.arcs.map(c);break;default:return null}return{type:f,coordinates:h}}return u(t)}const ry={geoAzimuthalEqualArea:M2e,geoAzimuthalEquidistant:A2e,geoGnomonic:V2e,geoOrthographic:U2e,geoStereographic:W2e,geoEqualEarth:B2e,geoAlbers:xJ,geoAlbersUsa:T2e,geoConicConformal:P2e,geoConicEqualArea:tN,geoConicEquidistant:$2e,geoEquirectangular:O2e,geoMercator:R2e,geoTransverseMercator:q2e,geoNaturalEarth1:H2e};Object.keys(ry).forEach(e=>{ry[`${e.charAt(3).toLowerCase()}${e.slice(4)}`]=ry[e]});class Yh extends Ed{constructor(t){super(t),this.outlineBounds=null,this.oldChartBounds=null,this.geoPath=Z6()}init(t){t.position="chartArea",super.init(t),typeof t.projection=="function"?this.projection=t.projection:this.projection=(ry[t.projection]||ry.albersUsa)(),this.geoPath.projection(this.projection),this.outlineBounds=null,this.oldChartBounds=null}computeBounds(t){const n=Z6(this.projection.fitWidth(1e3,t)).bounds(t),r=Math.ceil(n[1][1]-n[0][1]),s=Math.ceil(n[1][0]-n[0][0]),o=this.projection.translate();this.outlineBounds={width:s,height:r,aspectRatio:s/r,refScale:this.projection.scale(),refX:o[0],refY:o[1]}}updateBounds(){const t=this.chart.chartArea,n=this.outlineBounds;if(!n)return!1;const r=this.options.padding,s=typeof r=="number"?r:r.top,o=typeof r=="number"?r:r.left,i=typeof r=="number"?r:r.bottom,a=typeof r=="number"?r:r.right,c=t.right-t.left-o-a,u=t.bottom-t.top-s-i,d=this.oldChartBounds;this.oldChartBounds={chartWidth:c,chartHeight:u};const f=Math.min(c/n.width,u/n.height),h=n.width*f,p=n.height*f,g=(c-h)*.5+t.left+o,b=(u-p)*.5+t.top+s,x=this.options;return this.projection.scale(n.refScale*f*x.projectionScale).translate([f*n.refX+g+x.projectionOffset[0],f*n.refY+b+x.projectionOffset[1]]),!d||d.chartWidth!==this.oldChartBounds.chartWidth||d.chartHeight!==this.oldChartBounds.chartHeight}}Yh.id="projection";Yh.defaults={projection:"albersUsa",projectionScale:1,projectionOffset:[0,0],padding:0};Yh.descriptors={_scriptable:e=>e!=="projection",_indexable:e=>e!=="projectionOffset"};const I_={position:"chartArea",property:"value",grid:{z:1,drawOnChartArea:!1},ticks:{z:1},legend:{align:"right",position:"bottom-right",length:100,width:50,margin:8,indicatorWidth:10}};function MAe(e){const{indicatorWidth:t,align:n,margin:r}=e,s=(typeof r=="number"?r:r.left)+(n==="right"?t:0),o=(typeof r=="number"?r:r.top)+(n==="bottom"?t:0),i=(typeof r=="number"?r:r.right)+(n==="left"?t:0),a=(typeof r=="number"?r:r.bottom)+(n==="top"?t:0);return{left:s,top:o,right:i,bottom:a}}function AAe(e,t,n,r,s){const{indicatorWidth:o,align:i,position:a}=t,c=i==="top"||i==="bottom",u=(i==="left"?s.w:n)+(c?o:0),d=(i==="top"?s.h:r)+(c?0:o),f=MAe(t);if(typeof a=="string")switch(a){case"top-left":return[f.left,f.top];case"top":return[(e.right-u)/2,f.top];case"left":return[f.left,(e.bottom-d)/2];case"top-right":return[e.right-u-f.right,f.top];case"bottom-right":return[e.right-u-f.right,e.bottom-d-f.bottom];case"bottom":return[(e.right-u)/2,e.bottom-d-f.bottom];case"bottom-left":return[f.left,e.bottom-d-f.bottom];default:return[e.right-u-f.right,(e.bottom-d)/2]}return[a.x,a.y]}class Jp extends mh{constructor(){super(...arguments),this.legendSize={w:0,h:0}}init(t){t.position="chartArea",super.init(t),this.axis="r"}parse(t,n){return t&&typeof t[this.options.property]=="number"?t[this.options.property]:super.parse(t,n)}isHorizontal(){return this.options.legend.align==="top"||this.options.legend.align==="bottom"}_getNormalizedValue(t){return t==null||Number.isNaN(t)?null:(t-this._startValue)/this._valueRange}update(t,n,r){const s=Math.min(n,this.bottom==null?Number.POSITIVE_INFINITY:this.bottom),o=Math.min(t,this.right==null?Number.POSITIVE_INFINITY:this.right),i=this.options.legend,a=this.isHorizontal(),c=(p,g)=>p<1?g*p:p,u=Math.min(o,c(a?i.length:i.width,o))-(a?0:i.indicatorWidth),d=Math.min(s,c(a?i.width:i.length,s))-(a?i.indicatorWidth:0);this.legendSize={w:u,h:d},this.bottom=d,this.height=d,this.right=u,this.width=u;const f=this.options.position;this.options.position=this.options.legend.align;const h=super.update(u,d,r);return this.options.position=f,this.height=Math.min(d,this.height),this.width=Math.min(u,this.width),h}_computeLabelArea(){}draw(t){if(!this._isVisible())return;const n=AAe(t,this.options.legend,this.width,this.height,this.legendSize),{ctx:r}=this;r.save(),r.translate(n[0],n[1]);const s=this.options.position;this.options.position=this.options.legend.align,super.draw({...t,bottom:this.height+10,right:this.width}),this.options.position=s;const{indicatorWidth:o}=this.options.legend;switch(this.options.legend.align){case"left":r.translate(this.legendSize.w,0);break;case"top":r.translate(0,this.legendSize.h);break;case"bottom":r.translate(0,-o);break;default:r.translate(-o,0);break}this._drawIndicator(),r.restore()}_drawIndicator(){}}class RJ extends Ym{constructor(){super(...arguments),this.legendSize={w:0,h:0}}init(t){Jp.prototype.init.call(this,t)}parse(t,n){return Jp.prototype.parse.call(this,t,n)}isHorizontal(){return this.options.legend.align==="top"||this.options.legend.align==="bottom"}_getNormalizedValue(t){return t==null||Number.isNaN(t)?null:(Math.log10(t)-this._startValue)/this._valueRange}update(t,n,r){return Jp.prototype.update.call(this,t,n,r)}_computeLabelArea(){}draw(t){return Jp.prototype.draw.call(this,t)}_drawIndicator(){}}const pc={interpolateBlues:rAe,interpolateBrBG:mMe,interpolateBuGn:AMe,interpolateBuPu:FMe,interpolateCividis:pAe,interpolateCool:bAe,interpolateCubehelixDefault:mAe,interpolateGnBu:OMe,interpolateGreens:oAe,interpolateGreys:aAe,interpolateInferno:kAe,interpolateMagma:NAe,interpolateOrRd:$Me,interpolateOranges:hAe,interpolatePRGn:bMe,interpolatePiYG:yMe,interpolatePlasma:_Ae,interpolatePuBu:HMe,interpolatePuBuGn:BMe,interpolatePuOr:wMe,interpolatePuRd:WMe,interpolatePurples:cAe,interpolateRainbow:xAe,interpolateRdBu:CMe,interpolateRdGy:kMe,interpolateRdPu:YMe,interpolateRdYlBu:jMe,interpolateRdYlGn:DMe,interpolateReds:dAe,interpolateSinebow:wAe,interpolateSpectral:TMe,interpolateTurbo:SAe,interpolateViridis:CAe,interpolateWarm:gAe,interpolateYlGn:XMe,interpolateYlGnBu:KMe,interpolateYlOrBr:JMe,interpolateYlOrRd:tAe};Object.keys(pc).forEach(e=>{pc[`${e.charAt(11).toLowerCase()}${e.slice(12)}`]=pc[e],pc[e.slice(11)]=pc[e]});function FJ(e,t){const n=1/t;if(e<=n)return 0;if(e>=1-n)return 1;for(let r=0;r<1;r+=n)if(e<r)return r-n/2;return e}const PJ={interpolate:"blues",missing:"transparent",quantize:0};class id extends Jp{get interpolate(){const t=this.options;return t?typeof t.interpolate=="function"?t.interpolate:pc[t.interpolate]||pc.blues:n=>`rgb(${n},${n},${n})`}getColorForValue(t){const n=this._getNormalizedValue(t);return n==null||Number.isNaN(n)?this.options.missing:this.getColor(n)}getColor(t){let n=t;return this.options.quantize>0&&(n=FJ(n,this.options.quantize)),this.interpolate(n)}_drawIndicator(){const{indicatorWidth:t}=this.options.legend,n=this._reversePixels;if(this.isHorizontal()){const r=this.width;if(this.options.quantize>0){const s=r/this.options.quantize,o=n?i=>r-s-i:i=>i;for(let i=0;i<r;i+=s){const a=(i+s/2)/r;this.ctx.fillStyle=this.getColor(a),this.ctx.fillRect(o(i),0,s,t)}}else{const s=n?o=>r-1-o:o=>o;for(let o=0;o<r;o+=1)this.ctx.fillStyle=this.getColor((o+.5)/r),this.ctx.fillRect(s(o),0,1,t)}}else{const r=this.height;if(this.options.quantize>0){const s=r/this.options.quantize,o=n?i=>r-s-i:i=>i;for(let i=0;i<r;i+=s){const a=(i+s/2)/r;this.ctx.fillStyle=this.getColor(a),this.ctx.fillRect(0,o(i),t,s)}}else{const s=n?o=>r-1-o:o=>o;for(let o=0;o<r;o+=1)this.ctx.fillStyle=this.getColor((o+.5)/r),this.ctx.fillRect(0,s(o),t,1)}}}}id.id="color";id.defaults=as({},[mh.defaults,I_,PJ]);id.descriptors={_scriptable:e=>e!=="interpolate",_indexable:!1};class EO extends RJ{constructor(){super(...arguments),this.interpolate=t=>`rgb(${t},${t},${t})`}init(t){super.init(t),typeof t.interpolate=="function"?this.interpolate=t.interpolate:this.interpolate=pc[t.interpolate]||pc.blues}getColorForValue(t){return id.prototype.getColorForValue.call(this,t)}getColor(t){let n=t;return this.options.quantize>0&&(n=FJ(n,this.options.quantize)),this.interpolate(n)}_drawIndicator(){return id.prototype._drawIndicator.call(this)}}EO.id="colorLogarithmic";EO.defaults=as({},[Ym.defaults,I_,PJ]);EO.descriptors={_scriptable:e=>e!=="interpolate",_indexable:!1};const OJ={missing:1,mode:"area",range:[2,20],legend:{align:"bottom",length:90,width:70,indicatorWidth:42}};class ad extends Jp{constructor(){super(...arguments),this._model=null}getSizeForValue(t){const n=this._getNormalizedValue(t);return n==null||Number.isNaN(n)?this.options.missing:this.getSizeImpl(n)}getSizeImpl(t){const[n,r]=this.options.range;if(this.options.mode==="area"){const o=r*r*Math.PI,i=n*n*Math.PI,a=o-i,c=t*a+i;return Math.sqrt(c/Math.PI)}const s=r-n;return t*s+n}_drawIndicator(){const{ctx:t}=this,n=this.options.legend.indicatorWidth/2,r=this.isHorizontal(),s=this.ticks,o=this.getLabelItems(),i=o?o.map(a=>({[r?"x":"y"]:a.options.translation[r?0:1]})):s.map((a,c)=>({[r?"x":"y"]:this.getPixelForTick(c)}));if((this._gridLineItems||[]).forEach(a=>{if(t.save(),t.strokeStyle=a.color,t.lineWidth=a.width,t.setLineDash&&(t.setLineDash(a.borderDash),t.lineDashOffset=a.borderDashOffset),t.beginPath(),this.options.grid.drawTicks)switch(this.options.legend.align){case"left":t.moveTo(0,a.ty1),t.lineTo(n,a.ty2);break;case"top":t.moveTo(a.tx1,0),t.lineTo(a.tx2,n);break;case"bottom":t.moveTo(a.tx1,n),t.lineTo(a.tx2,n*2);break;default:t.moveTo(n,a.ty1),t.lineTo(n*2,a.ty2);break}t.stroke(),t.restore()}),this._model){const a=this._model;t.strokeStyle=a.borderColor,t.lineWidth=a.borderWidth||0,t.fillStyle=a.backgroundColor}else t.fillStyle="blue";s.forEach((a,c)=>{const u=i[c],d=this.getSizeForValue(a.value),f=r?u.x:n,h=r?n:u.y,p={pointStyle:"circle",borderWidth:0,...this._model||{},radius:d};zC(t,p,f,h)})}}ad.id="size";ad.defaults=as({},[mh.defaults,I_,OJ]);ad.descriptors={_scriptable:!0,_indexable:e=>e!=="range"};class LJ extends RJ{constructor(){super(...arguments),this._model=null}getSizeForValue(t){const n=this._getNormalizedValue(t);return n==null||Number.isNaN(n)?this.options.missing:this.getSizeImpl(n)}getSizeImpl(t){return ad.prototype.getSizeImpl.call(this,t)}_drawIndicator(){ad.prototype._drawIndicator.call(this)}}LJ.id="sizeLogarithmic";LJ.defaults=as({},[Ym.defaults,I_,OJ]);function RAe(e,t){return[[e[0][0]-t,e[0][1]-t],[e[1][0]+t,e[1][1]+t]]}class zc extends ra{constructor(){super(...arguments),this.cache=void 0}updateExtras({scale:t,feature:n,center:r,pixelRatio:s,mode:o}){var i,a;const c=o==="resize"||o==="reset"||this.projectionScale!==t||this.feature!==n||((i=this.center)===null||i===void 0?void 0:i.longitude)!==(r==null?void 0:r.longitude)||((a=this.center)===null||a===void 0?void 0:a.latitude)!==(r==null?void 0:r.latitude)||this.pixelRatio!==s;return this.projectionScale=t,this.feature=n,this.center=r,this.pixelRatio=s,c&&(this.cache=void 0),this.getCenterPoint()}inRange(t,n){const r=this.getBounds(),s=(Number.isNaN(t)||t>=r.x&&t<=r.x2)&&(Number.isNaN(n)||n>=r.y&&n<=r.y2),o=this.projectionScale.geoPath.projection();if(s&&!Number.isNaN(t)&&!Number.isNaN(n)&&typeof o.invert=="function"){const i=o.invert([t,n]);return i!=null&&c2e(this.feature,i)}return s}inXRange(t){return this.inRange(t,Number.NaN)}inYRange(t){return this.inRange(Number.NaN,t)}getCenterPoint(){if(this.cache&&this.cache.center)return this.cache.center;let t;if(this.center){const n=this.projectionScale.projection([this.center.longitude,this.center.latitude]);t={x:n[0],y:n[1]}}else{const n=this.projectionScale.geoPath.centroid(this.feature);t={x:n[0],y:n[1]}}return this.cache={...this.cache||{},center:t},t}getBounds(){if(this.cache&&this.cache.bounds)return this.cache.bounds;const t=RAe(this.projectionScale.geoPath.bounds(this.feature),this.options.borderWidth/2),n={x:t[0][0],x2:t[1][0],y:t[0][1],y2:t[1][1],width:t[1][0]-t[0][0],height:t[1][1]-t[0][1]};return this.cache={...this.cache||{},bounds:n},n}_drawInCache(t){const n=this.getBounds();if(!Number.isFinite(n.x))return;const r=this.cache&&this.cache.canvas?this.cache.canvas:t.createElement("canvas"),s=Math.floor(n.x),o=Math.floor(n.y),i=Math.ceil(n.x+n.width),a=Math.ceil(n.y+n.height),c=this.pixelRatio||1,u=Math.ceil(Math.max(i-s,1)*c),d=Math.ceil(Math.max(a-o,1)*c);if(u<=0||d<=0)return;r.width=u,r.height=d;const f=r.getContext("2d");f&&(f.clearRect(0,0,r.width,r.height),f.save(),f.scale(c,c),f.translate(-s,-o),this._drawImpl(f),f.restore(),this.cache={...this.cache||{},canvas:r,canvasKey:this._optionsToKey()})}_optionsToKey(){const{options:t}=this;return`${t.backgroundColor};${t.borderColor};${t.borderWidth};${this.pixelRatio}`}_drawImpl(t){const{feature:n}=this,{options:r}=this;t.beginPath(),this.projectionScale.geoPath.context(t)(n),r.backgroundColor&&(t.fillStyle=r.backgroundColor,t.fill()),r.borderColor&&(t.strokeStyle=r.borderColor,t.lineWidth=r.borderWidth,t.stroke())}draw(t){const{feature:n}=this;if(!n)return;(!this.cache||this.cache.canvasKey!==this._optionsToKey())&&t.canvas.ownerDocument!=null&&this._drawInCache(t.canvas.ownerDocument);const r=this.getBounds();if(this.cache&&this.cache.canvas&&this.cache.canvas.width>0&&this.cache.canvas.height>0){const s=Math.floor(r.x),o=Math.floor(r.y),i=Math.ceil(r.x+r.width),a=Math.ceil(r.y+r.height),c=i-s,u=a-o;c>0&&u>0&&t.drawImage(this.cache.canvas,s,o,i-s,a-o)}else Number.isFinite(r.x)&&(t.save(),this._drawImpl(t),t.restore())}}zc.id="geoFeature";zc.defaults={...ul.defaults,outlineBackgroundColor:null,outlineBorderWidth:0,graticuleBorderColor:"#CCCCCC",graticuleBorderWidth:0};zc.defaultRoutes={outlineBorderColor:"borderColor",...ul.defaultRoutes||{}};const $J={showOutline:!1,showGraticule:!1,clipMap:!0},zJ={scales:{projection:{axis:"x",type:Yh.id,position:"chartArea",display:!1}}};function fB(e){const t={...e};return Object.keys(e).forEach(n=>{let r=n;if(n.startsWith("outline")){const s=n.slice(7);r=s[0].toLowerCase()+s.slice(1)}else if(n.startsWith("hoverOutline"))r=`hover${n.slice(12)}`;else return;delete t[n],t[r]=e[n]}),t}class BJ extends ti{getGeoDataset(){return super.getDataset()}getGeoOptions(){return this.chart.options}getProjectionScale(){return this.getScaleForId("projection")}linkScales(){const t=this.getGeoDataset(),n=this.getMeta();n.xAxisID="projection",t.xAxisID="projection",n.yAxisID="projection",t.yAxisID="projection",n.xScale=this.getScaleForId("projection"),n.yScale=this.getScaleForId("projection"),this.getProjectionScale().computeBounds(this.resolveOutline())}showOutline(){return Yt(this.getGeoDataset().showOutline,this.getGeoOptions().showOutline)}clipMap(){return Yt(this.getGeoDataset().clipMap,this.getGeoOptions().clipMap)}getGraticule(){return Yt(this.getGeoDataset().showGraticule,this.getGeoOptions().showGraticule)}update(t){super.update(t);const n=this.getMeta(),r=this.getProjectionScale(),s=r.updateBounds()||t==="resize"||t==="reset";if(this.showOutline()){const o=n.dataset;if(s&&delete o.cache,o.projectionScale=r,o.pixelRatio=this.chart.currentDevicePixelRatio,t!=="resize"){const i=fB(this.resolveDatasetElementOptions(t)),a={feature:this.resolveOutline(),options:i};this.updateElement(o,void 0,a,t),this.getGraticule()&&(n.graticule=i)}}else this.getGraticule()&&t!=="resize"&&(n.graticule=fB(this.resolveDatasetElementOptions(t)));s&&n.data.forEach(o=>delete o.cache),this.updateElements(n.data,0,n.data.length,t)}resolveOutline(){const n=this.getGeoDataset().outline||{type:"Sphere"};return Array.isArray(n)?{type:"FeatureCollection",features:n}:n}showGraticule(){const t=this.getGraticule(),n=this.getMeta().graticule;if(!t||!n)return;const{ctx:r}=this.chart,o=this.getProjectionScale().geoPath.context(r);if(r.save(),r.beginPath(),typeof t=="boolean")t&&o(u2e());else{const i=nJ();t.stepMajor&&i.stepMajor(t.stepMajor),t.stepMinor&&i.stepMinor(t.stepMinor),o(i())}r.strokeStyle=n.graticuleBorderColor,r.lineWidth=n.graticuleBorderWidth,r.stroke(),r.restore()}draw(){const{chart:t}=this,n=this.clipMap();let r=!1;(n===!0||n==="outline"||n==="outline+graticule")&&(r=!0,Ku(t.ctx,t.chartArea)),this.showOutline()&&this.getMeta().dataset&&this.getMeta().dataset.draw.call(this.getMeta().dataset,t.ctx,t.chartArea),n===!0||n==="graticule"||n==="outline+graticule"?r||Ku(t.ctx,t.chartArea):r&&(r=!1,Zu(t.ctx)),this.showGraticule(),n===!0||n==="items"?r||Ku(t.ctx,t.chartArea):r&&(r=!1,Zu(t.ctx)),this.getMeta().data.forEach(s=>s.draw.call(s,t.ctx,t.chartArea)),r&&(r=!1,Zu(t.ctx))}}function VJ(e,t,n,r=[],s=[]){Wr.addControllers(n),Array.isArray(r)?Wr.addElements(...r):Wr.addElements(r),Array.isArray(s)?Wr.addScales(...s):Wr.addScales(s);const o=t;return o.type=e,o}class Tg extends BJ{initialize(){super.initialize(),this.enableOptionSharing=!0}linkScales(){super.linkScales();const t=this.getGeoDataset(),n=this.getMeta();n.vAxisID="color",n.rAxisID="color",t.vAxisID="color",t.rAxisID="color",n.rScale=this.getScaleForId("color"),n.vScale=n.rScale,n.iScale=n.xScale,n.iAxisID=n.xAxisID,t.iAxisID=n.xAxisID}_getOtherScale(t){return t}parse(t,n){const r=this.getMeta().rScale,{data:s}=this.getDataset(),o=this._cachedMeta;for(let i=t;i<t+n;i+=1)o._parsed[i]={[r.axis]:r.parse(s[i],i)}}updateElements(t,n,r,s){const o=this.resolveDataElementOptions(n,s),i=this.getSharedOptions(o),a=this.includeOptions(s,i),c=this.getProjectionScale();this.updateSharedOptions(i,s,o);for(let u=n;u<n+r;u+=1){const d=t[u];d.projectionScale=c;const f=d.updateExtras({scale:c,feature:this._data[u].feature,center:this._data[u].center,pixelRatio:this.chart.currentDevicePixelRatio,mode:s}),h={x:f.x,y:f.y};a&&(h.options=i||this.resolveDataElementOptions(u,s)),this.updateElement(d,u,h,s)}}indexToColor(t){const n=this.getMeta().rScale;return n.getColorForValue(this.getParsed(t)[n.axis])}}Tg.id="choropleth";Tg.defaults=as({},[$J,{datasetElementType:zc.id,dataElementType:zc.id}]);Tg.overrides=as({},[zJ,{plugins:{tooltip:{callbacks:{title(){return""},label(e){var t,n,r,s;return e.formattedValue==null?(n=(t=e.chart.data)===null||t===void 0?void 0:t.labels)===null||n===void 0?void 0:n[e.dataIndex]:`${(s=(r=e.chart.data)===null||r===void 0?void 0:r.labels)===null||s===void 0?void 0:s[e.dataIndex]}: ${e.formattedValue}`}}},colors:{enabled:!1}},scales:{color:{type:id.id,axis:"x"}},elements:{geoFeature:{backgroundColor(e){return e.dataIndex==null?null:e.chart.getDatasetMeta(e.datasetIndex).controller.indexToColor(e.dataIndex)}}}}]);class FAe extends Rn{constructor(t,n){super(t,VJ("choropleth",n,Tg,zc,[id,Yh]))}}FAe.id=Tg.id;class Mg extends BJ{initialize(){super.initialize(),this.enableOptionSharing=!0}linkScales(){super.linkScales();const t=this.getGeoDataset(),n=this.getMeta();n.vAxisID="size",n.rAxisID="size",t.vAxisID="size",t.rAxisID="size",n.rScale=this.getScaleForId("size"),n.vScale=n.rScale,n.iScale=n.xScale,n.iAxisID=n.xAxisID,t.iAxisID=n.xAxisID}_getOtherScale(t){return t}parse(t,n){const r=this.getMeta().rScale,s=this.getDataset().data,o=this._cachedMeta;for(let i=t;i<t+n;i+=1){const a=s[i];o._parsed[i]={x:a.longitude==null?a.x:a.longitude,y:a.latitude==null?a.y:a.latitude,[r.axis]:r.parse(a,i)}}}updateElements(t,n,r,s){const o=s==="reset",i=this.resolveDataElementOptions(n,s),a=this.getSharedOptions(i),c=this.includeOptions(s,a),u=this.getProjectionScale();this.getMeta().rScale._model=i,this.updateSharedOptions(a,s,i);for(let d=n;d<n+r;d+=1){const f=t[d],h=this.getParsed(d),p=u.projection([h.x,h.y]),g={x:p?p[0]:0,y:p?p[1]:0,skip:Number.isNaN(h.x)||Number.isNaN(h.y)};c&&(g.options=a||this.resolveDataElementOptions(d,s),o&&(g.options.radius=0)),this.updateElement(f,d,g,s)}}indexToRadius(t){const n=this.getMeta().rScale;return n.getSizeForValue(this.getParsed(t)[n.axis])}}Mg.id="bubbleMap";Mg.defaults=as({},[$J,{dataElementType:Yf.id,datasetElementType:zc.id,showOutline:!0,clipMap:"outline+graticule"}]);Mg.overrides=as({},[zJ,{plugins:{tooltip:{callbacks:{title(){return""},label(e){var t,n,r,s;return e.formattedValue==null?(n=(t=e.chart.data)===null||t===void 0?void 0:t.labels)===null||n===void 0?void 0:n[e.dataIndex]:`${(s=(r=e.chart.data)===null||r===void 0?void 0:r.labels)===null||s===void 0?void 0:s[e.dataIndex]}: ${e.formattedValue}`}}}},scales:{size:{axis:"x",type:ad.id}},elements:{point:{radius(e){return e.dataIndex==null?null:e.chart.getDatasetMeta(e.datasetIndex).controller.indexToRadius(e.dataIndex)},hoverRadius(e){return e.dataIndex==null?null:e.chart.getDatasetMeta(e.datasetIndex).controller.indexToRadius(e.dataIndex)+1}}}}]);class PAe extends Rn{constructor(t,n){super(t,VJ("bubbleMap",n,Mg,zc,[ad,Yh]))}}PAe.id=Mg.id;function OAe(e){var n;return{...e,type:"bar",options:{...e==null?void 0:e.options,indexAxis:"y",scales:{x:{beginAtZero:!0,stack:1,reverse:!0},y:{stacked:!0,beginAtZero:!0}},plugins:{...(n=e==null?void 0:e.options)==null?void 0:n.plugins,legend:{position:"bottom",align:"center"}}}}}function LAe(e,t=!1){var r;return{...e,type:"bar",options:{...e==null?void 0:e.options,indexAxis:"y",scales:{x:{display:!0,beginAtZero:!1},y:{display:!0,stacked:t}},plugins:{...(r=e==null?void 0:e.options)==null?void 0:r.plugins,legend:{position:"bottom",align:"center"}}}}}function $Ae(e,t,n=!1){var s,o,i,a,c,u,d,f,h,p,g;return{...e,type:t==="stackedBar"?"bar":"line",options:{...e==null?void 0:e.options,scales:{x:{...(o=(s=e==null?void 0:e.options)==null?void 0:s.scales)==null?void 0:o.x,display:((c=(a=(i=e==null?void 0:e.options)==null?void 0:i.scales)==null?void 0:a.x)==null?void 0:c.display)??!0,stacked:!n},y:{...(d=(u=e==null?void 0:e.options)==null?void 0:u.scales)==null?void 0:d.y,display:((p=(h=(f=e==null?void 0:e.options)==null?void 0:f.scales)==null?void 0:h.y)==null?void 0:p.display)??!0,stacked:t==="stackedBar"}},plugins:{...(g=e==null?void 0:e.options)==null?void 0:g.plugins,legend:{display:!1,position:"bottom",align:"center"}}}}}function zAe(e,t){var r;return{...t,type:e,options:{...t==null?void 0:t.options,scales:{x:{display:!1},y:{display:!1}},plugins:{...(r=t==null?void 0:t.options)==null?void 0:r.plugins,legend:{position:"bottom",align:"center",maxHeight:0,labels:{useBorderRadius:!0,borderRadius:2}}},borderRadius:0}}}function BAe(e){var r,s;const t=m.useDashboardStore.getState().theme;let n={...e,type:"radar",options:{...e==null?void 0:e.options,scales:{x:{display:!1},y:{display:!1},r:{grid:{display:!0},angleLines:{},ticks:{}}},plugins:{...(r=e==null?void 0:e.options)==null?void 0:r.plugins,legend:{position:"bottom",align:"center"}}}};return t==="dark"&&(n={...n,options:{...n.options,scales:{...(s=n==null?void 0:n.options)==null?void 0:s.scales,r:{grid:{color:m.colors.slate[800]},angleLines:{color:m.colors.slate[800]},ticks:{color:m.colors.slate[800],showLabelBackdrop:!1}}}}}),n}const VAe=5,HAe=30,qM=5;function UAe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o,cardConfig:i,isDevMode:a=!1,card:c}){var R,B,z,U,Y,O,K,q,M,G,L;if(!e||e.length===0)return{type:s,data:{labels:[],datasets:[]}};const u=r==null?void 0:r.bubbleScatterConfig,d=WAe(e,u,i,a,s);if(!d.xKey||!d.yKey)return{type:s,data:{labels:[],datasets:[]}};const f=m.useDashboardStore.getState(),h=o??f.themeStyle,p=YAe(e,d,u,s),g=KAe(p,h,r,s),b=Da(g,n),x=JAe(r),y=mO(s),S=(B=(R=r==null?void 0:r.chartOptions)==null?void 0:R.plugins)==null?void 0:B.legend,w=UQ(y,S),C=!!(S!=null&&S.labels||(Y=(U=(z=t==null?void 0:t.options)==null?void 0:z.plugins)==null?void 0:U.legend)!=null&&Y.labels||(q=(K=(O=n==null?void 0:n.options)==null?void 0:O.plugins)==null?void 0:K.legend)!=null&&q.labels);(S==null?void 0:S.display)===void 0&&(w.display=d.grouping.enabled);const N=tRe(c);let k=XAe({resolvedKeys:d,formatConfig:x,preferences:r,cardType:s,legendConfig:w,hasCustomLegendLabels:C,hasDrillDown:N,card:c});k=pO(k,w);const{plugins:_=[],options:E}=kd((r==null?void 0:r.customVisualCode)||""),D=r!=null&&r.chartOptions?{...r.chartOptions,plugins:{...r.chartOptions.plugins??{},legend:(S==null?void 0:S.display)!==void 0?(M=r.chartOptions.plugins)==null?void 0:M.legend:{...((G=r.chartOptions.plugins)==null?void 0:G.legend)??{},display:w.display}}}:void 0,j=eRe([k,t==null?void 0:t.options,D,n==null?void 0:n.options,E]),I=es(((L=h==null?void 0:h.chart)==null?void 0:L.options)||{},j),T={type:s,data:{datasets:b},options:I,plugins:_},F=Cv(s,r),P=(r==null?void 0:r.dataLabelsConfig)??F;return T.options=Eg(T.options||{},P,r,s,c),T.options=jg.applyAxisConfig(T.options||{},s,r,c),T}function WAe(e,t,n,r,s){var w,C;const{metricKeys:o,keys:i}=pr(e),a=Object.keys((e==null?void 0:e[0])||{}),c=a.length>0?a:i,u=r?[]:((w=n==null?void 0:n.metricColumns)==null?void 0:w.map(N=>N.label||N.name||N.alias).filter(Boolean))||[],d=u.length>0?u:o,f=c[0],h=(C=n==null?void 0:n.groupByColumns)==null?void 0:C[0],p=(h==null?void 0:h.label)||(h==null?void 0:h.name)||(h==null?void 0:h.alias),g=r?(t==null?void 0:t.labelKey)??f??i[0]:(t==null?void 0:t.labelKey)??p??i[0],b=qAe(t,n,r,c);let x,y,S;if(r){const N=1+(b.enabled&&b.groupKey?1:0),k=c.slice(N);x=(t==null?void 0:t.xMetricKey)??k[0],y=(t==null?void 0:t.yMetricKey)??k[1],S=s==="bubble"?(t==null?void 0:t.radiusMetricKey)??k[2]:void 0,x||(x=k[0]),y||(y=k[1]??k[0]),s==="bubble"&&!S&&(S=k[2]??k[1]??k[0])}else x=(t==null?void 0:t.xMetricKey)??d[0],y=(t==null?void 0:t.yMetricKey)??d[1],S=s==="bubble"?(t==null?void 0:t.radiusMetricKey)??d[2]:void 0;return{labelKey:g,xKey:x,yKey:y,radiusKey:S,grouping:b}}function qAe(e,t,n,r){if((e==null?void 0:e.enableGrouping)!==void 0){const s=e.groupKey??(n?r[1]:void 0);return e.enableGrouping&&!s?{enabled:!1}:{enabled:e.enableGrouping,groupKey:s}}if(!n&&(t!=null&&t.groupByColumns)&&t.groupByColumns.length>=2){const s=t.groupByColumns[1],o=(s==null?void 0:s.label)||(s==null?void 0:s.name)||(s==null?void 0:s.alias);if(o)return{enabled:!0,groupKey:o}}return n?{enabled:!1}:{enabled:!1}}function YAe(e,t,n,r){const{labelKey:s,xKey:o,yKey:i,radiusKey:a,grouping:c}=t;let u=[];r==="bubble"&&a&&(u=e.map(y=>g1(y[a])).filter(y=>Number.isFinite(y)));const d={min:u.length>0?Math.min(...u):0,max:u.length>0?Math.max(...u):1},f=(n==null?void 0:n.minRadius)??VAe,h=(n==null?void 0:n.maxRadius)??HAe,p=(n==null?void 0:n.radiusScale)??"sqrt",g=(n==null?void 0:n.fixedRadius)??qM,b=y=>{const S=g1(y[o]),w=g1(y[i]);if(!Number.isFinite(S)||!Number.isFinite(w))return null;let C;if(r==="scatter")C=g;else if(p==="fixed")C=g;else if(a){const k=g1(y[a]);if(!Number.isFinite(k))return null;C=GAe(k,d,f,h,p)}else C=g;const N=hB(y[s]);return{x:S,y:w,r:C,label:N,meta:y}};if(c.enabled&&c.groupKey){const y=c.groupKey,S=new Map;for(const w of e){const C=hB(w[y]);S.has(C)||S.set(C,[]);const N=b(w);N&&S.get(C).push(N)}return Array.from(S.entries()).map(([w,C])=>({group:w,points:C}))}return[{group:"",points:e.map(b).filter(y=>y!==null)}]}function GAe(e,t,n,r,s){if(!Number.isFinite(e))return n;if(t.max===t.min)return(n+r)/2;const o=(e-t.min)/(t.max-t.min);let i;return s==="sqrt"?i=Math.sqrt(o):i=o,i*(r-n)+n}function KAe(e,t,n,r){var u,d,f,h;const s=qh().filter(Boolean),o=(((d=(u=t==null?void 0:t.chart)==null?void 0:u.dataset)==null?void 0:d.backgroundColor)||[]).filter(Boolean),i=(((h=(f=t==null?void 0:t.chart)==null?void 0:f.dataset)==null?void 0:h.borderColor)||[]).filter(Boolean),a=o.length>0?o:s.length>0?s:["#3b82f6"],c=i.length>0?i:a;return e.map((p,g)=>{var S,w;if(!p.group&&e.length===1){const C=p.points.map((_,E)=>{var I,T;const j=((T=(I=n==null?void 0:n.colorConfig)==null?void 0:I.segments)==null?void 0:T[_.label])||a[E%a.length]||"#3b82f6";return pB(j,.8)}),N=p.points.map((_,E)=>{var j,I;return((I=(j=n==null?void 0:n.colorConfig)==null?void 0:j.segments)==null?void 0:I[_.label])||c[E%c.length]||"#3b82f6"}),k={label:void 0,data:p.points.map(_=>({x:_.x,y:_.y,r:_.r,label:_.label,meta:_.meta})),backgroundColor:C,borderColor:N,borderWidth:1};return r==="scatter"&&(k.pointRadius=((S=p.points[0])==null?void 0:S.r)??qM),k}const x=ZAe({seriesKey:p.group,seriesIndex:g,preferences:n,backgroundPalette:a,borderPalette:c}),y={label:p.group||void 0,data:p.points.map(C=>({x:C.x,y:C.y,r:C.r,label:C.label,meta:C.meta})),backgroundColor:pB(x.backgroundColor,.8),borderColor:x.borderColor,borderWidth:1};return r==="scatter"&&(y.pointRadius=((w=p.points[0])==null?void 0:w.r)??qM),y})}function ZAe({seriesKey:e,seriesIndex:t,preferences:n,backgroundPalette:r,borderPalette:s}){var c,u;const o=r[t%r.length]||r[0]||"#3b82f6",i=s[t%s.length]||s[0]||o,a=e&&((u=(c=n==null?void 0:n.colorConfig)==null?void 0:c.segments)==null?void 0:u[e])||void 0;return{backgroundColor:a||o,borderColor:a||i}}function XAe({resolvedKeys:e,formatConfig:t,preferences:n,cardType:r,legendConfig:s,hasCustomLegendLabels:o,hasDrillDown:i,card:a}){var g,b,x,y,S,w,C,N;const c=((b=(g=n==null?void 0:n.xAxisConfig)==null?void 0:g.name)==null?void 0:b.enabled)??!1,u=((y=(x=n==null?void 0:n.yAxisConfig)==null?void 0:x.name)==null?void 0:y.enabled)??!1,d=((w=(S=n==null?void 0:n.xAxisConfig)==null?void 0:S.name)==null?void 0:w.text)||e.xKey,f=((N=(C=n==null?void 0:n.yAxisConfig)==null?void 0:C.name)==null?void 0:N.text)||e.yKey,h=!e.grouping.enabled&&!o;return{responsive:!0,maintainAspectRatio:!1,scales:{x:{type:"linear",position:"bottom",title:{display:c,text:d},ticks:{callback:k=>oN(Number(k),"x",t,n,a)}},y:{type:"linear",position:"left",title:{display:u,text:f},ticks:{callback:k=>oN(Number(k),"y",t,n,a)}}},plugins:{legend:{...s,...h?{labels:{generateLabels:rRe(e)}}:{}},tooltip:{displayColors:!1,callbacks:QAe(e,t,r,n,i,a)}}}}function QAe(e,t,n,r,s,o){const i=(a,c,u,d=!0)=>{const f=zy({card:o,metricKey:c,datasetLabel:c}),h=(d?WP({card:o,chartType:n,preferences:r,metric:f,axis:u}):v_({preferences:r,metric:f})).formatOptions;return h!=null&&h.type&&h.type!=="auto"?Fn(a,h.type,h):oN(a,u,t,r,o)};return{title:a=>{if(!a.length)return"";const c=a[0],u=c.dataset.label,d=c.raw,f=d==null?void 0:d.label;return u&&f?`${u} (${f})`:f||u||""},label:a=>{const c=a.raw,u=[],d=i(c.x,e.xKey,"x"),f=i(c.y,e.yKey,"y");if(u.push(`${e.xKey} (x): ${d}`),u.push(`${e.yKey} (y): ${f}`),n==="bubble"&&e.radiusKey){const h=c.meta;if(h&&e.radiusKey in h){const p=oN(h[e.radiusKey],"y",t,r,o),g=i(Number(h[e.radiusKey]),e.radiusKey,"y",!1);u.push(`${e.radiusKey} (size): ${g||p}`)}}return s&&(u.push("─────────────────"),u.push("Click to drill")),u}}}function JAe(e){const t=vv(e);return{format:(t==null?void 0:t.type)||"number",options:t??{}}}function g1(e){const t=Number(e);return Number.isFinite(t)?t:Number.NaN}function hB(e){return e==null||e===""?"(Blank)":String(e)}function eRe(e){return e.reduce((t,n)=>es(t,n||{}),{})}function oN(e,t,n,r,s){const o=kg({card:s,chartType:"bubble",axis:t,preferences:r,axisConfig:t==="x"?r==null?void 0:r.xAxisConfig:r==null?void 0:r.yAxisConfig}).formatOptions;if(o!=null&&o.type&&o.type!=="auto")return Fn(e,o.type,o);const i=vv(r);return i!=null&&i.type&&i.type!=="auto"?Fn(e,i.type,i):Fn(e,n.format,n.options)}function tRe(e){if(!(e!=null&&e.interactionConfig))return!1;const{drillHierarchies:t=[],interactions:n=[]}=e.interactionConfig;return t.length>0?!0:n.some(r=>["drillDown","drillToDetail","drillThrough","drillToURL"].includes(r.mode))}function nRe(e){return/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(e.trim())}function pB(e,t){if(!e||!nRe(e))return e;const n=e.trim(),r=n.length===7?n.slice(1):n.slice(1,9),s=r.length===8,o=r.slice(0,2),i=r.slice(2,4),a=r.slice(4,6),c=Math.round(t*255).toString(16).padStart(2,"0");return`#${o}${i}${a}${c}`}function rRe(e){return t=>{var c,u;const n=(u=(c=t==null?void 0:t.data)==null?void 0:c.datasets)==null?void 0:u[0];if(!n)return[];const r=n.data||[],s=n.backgroundColor,o=n.borderColor,i="#3b82f6",a=(d,f)=>Array.isArray(d)?d[f]||d[0]||i:d||i;return r.map((d,f)=>{var h;return{text:(d==null?void 0:d.label)??((h=d==null?void 0:d.meta)==null?void 0:h[e.labelKey])??`${e.labelKey||"Point"} ${f+1}`,fillStyle:a(s,f),strokeStyle:a(o,f),datasetIndex:0,index:f,hidden:!1}})}}function sRe(e,t,n){if(n==="percentOfFirst"){const s=t[0]??1;return s>0?(e/s*100).toFixed(2):"0.00"}const r=t.reduce((s,o)=>s+o,0);return r>0?(e/r*100).toFixed(2):"0.00"}function oRe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var U,Y,O,K,q,M,G,L,$;const i=(Y=(U=o==null?void 0:o.config)==null?void 0:U.metricColumns)==null?void 0:Y[0],a=v_({preferences:r,metric:i}).formatOptions,c=V=>By({value:V,formatOptions:a,preferences:r}),u=bv({card:o,chartType:"funnel",preferences:r,dataLabelsConfig:r==null?void 0:r.dataLabelsConfig}),d=V=>_g(u)?String(V):By({value:V,formatOptions:u.formatOptions,preferences:r}),f=((O=r==null?void 0:r.chartOptions)==null?void 0:O.indexAxis)||"y",h={...t,options:{indexAxis:f}},{keys:p}=pr(e),g=[p[1]],b=p==null?void 0:p[0],x=PZ(g,e,r,b),y=Da(x,n);y.forEach((V,H)=>{var A,W,X,Z,J,re,fe;V.shrinkAnchor=((X=(W=(A=n==null?void 0:n.data)==null?void 0:A.datasets)==null?void 0:W[H])==null?void 0:X.shrinkAnchor)||"top",V.shrinkFraction=((Z=r==null?void 0:r.funnelConfig)==null?void 0:Z.shrinkFraction)??((fe=(re=(J=n==null?void 0:n.data)==null?void 0:J.datasets)==null?void 0:re[H])==null?void 0:fe.shrinkFraction)??1});const{plugins:S,options:w}=kd((r==null?void 0:r.customVisualCode)||""),C=p[0],N=Qc(e,C),k=es((h==null?void 0:h.options)||{},(n==null?void 0:n.options)||{}),_=es(k,(r==null?void 0:r.chartOptions)||{}),E=(q=(K=_.plugins)==null?void 0:K.datalabels)==null?void 0:q.display;Array(y.length).fill(!0);const D=e.map(V=>V[C]),j=e.map(V=>V[g[0]]),I=(M=y[0])==null?void 0:M.backgroundColor.slice(),T=V=>{var W,X,Z,J,re;const H=(J=(Z=(X=(W=V==null?void 0:V.chart)==null?void 0:W.data)==null?void 0:X.datasets)==null?void 0:Z[(V==null?void 0:V.datasetIndex)||0])==null?void 0:J.data;return((H&&H.length>0?H:(re=V==null?void 0:V.dataset)==null?void 0:re.data)??j).map(fe=>Number(fe))},F={..._,plugins:{..._.plugins,legend:{...(G=_.plugins)==null?void 0:G.legend,labels:{generateLabels:V=>{const H=V.data.labels;return D.map((A,W)=>({text:A,fillStyle:I[W],hidden:!H.includes(A.toString()),index:W,datasetIndex:0,lineWidth:0}))}},onClick:(V,H,A)=>{const W=A.chart,X=H.index,Z=D[X],J=W.data.datasets[0],re=W.data.labels,fe=J.data,de=J.backgroundColor,Se=re.indexOf(Z.toString());Se>=0?(re.splice(Se,1),fe.splice(Se,1),de.splice(Se,1)):(re.splice(X,0,D[X].toString()),fe.splice(X,0,Number(j[X])),de.splice(X,0,I[X])),W.update()}},datalabels:{...(L=_.plugins)==null?void 0:L.datalabels,display:function(V){var A;if(E===!1)return!1;if(typeof E=="function")return E(V);const H=(((A=r==null?void 0:r.funnelConfig)==null?void 0:A.labelThreshold)??0)/100;if(H>0){const W=T(V),X=W[V.dataIndex],Z=W.reduce((re,fe)=>re+fe,0);return(Z>0?X/Z:0)>=H}return!0},anchor:V=>T(V)[V.dataIndex]<.02?"end":"start",align:V=>T(V)[V.dataIndex]<.02?"end":"center",textAlign:"center",font:{size:14},formatter:(V,H)=>d(Number(V))},tooltip:{...($=_.plugins)==null?void 0:$.tooltip,callbacks:{title:function(V){var Z,J,re,fe,de;const H=(J=(Z=V==null?void 0:V[0])==null?void 0:Z.dataset)==null?void 0:J.data,A=(re=V==null?void 0:V[0])==null?void 0:re.parsed[f==="x"?"y":"x"],W=((fe=r==null?void 0:r.funnelConfig)==null?void 0:fe.percentMode)??"percentOfTotal",X=sRe(A,H,W);return`${(de=V==null?void 0:V[0])==null?void 0:de.label} (${X}%)`},label:function(V){V.dataset.label;const H=V.dataset.data;H.reduce((fe,de)=>fe+de,0);const A=V.parsed[f==="x"?"y":"x"],W=H.indexOf(A),X=H[W-1],Z=c(Number(A));let J=0;return X!==void 0&&(J=Number((A/X*100).toFixed(2))),Z+(X!==void 0?` | Conversion: ${J}%`:"")},footer:function(V){var A,W,X,Z;return(((W=(A=o==null?void 0:o.interactionConfig)==null?void 0:A.drillHierarchies)==null?void 0:W.length)??0)>0||(((Z=(X=o==null?void 0:o.interactionConfig)==null?void 0:X.interactions)==null?void 0:Z.some(J=>J.mode==="drillDown"||J.mode==="drillToDetail"||J.mode==="drillThrough"||J.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},P=es(_,F),R=r!=null&&r.dataLabelsConfig?Eg(P,r.dataLabelsConfig,r,"funnel",o):P,B=es(R,w);return delete B.scales,{type:s,data:{labels:N,datasets:y},options:B,plugins:[...S]}}function iRe({data:e,cfg:t,customCfg:n,preferences:r,card:s}){var D,j;const o=bv({card:s,chartType:"range",preferences:r,dataLabelsConfig:r==null?void 0:r.dataLabelsConfig}),i=o.formatOptions,a=I=>_g(o)?String(I):By({value:I,formatOptions:i,preferences:r}),c=LAe(t),u=aRe(e),d=Da(u,n),{plugins:f,options:h}=kd((r==null?void 0:r.customVisualCode)||""),p=es((c==null?void 0:c.options)||{},(t==null?void 0:t.options)||{}),g=es(p,(r==null?void 0:r.chartOptions)||{}),b=es(g,(n==null?void 0:n.options)||{}),x={...b,plugins:{...b==null?void 0:b.plugins,tooltip:{...(D=b==null?void 0:b.plugins)==null?void 0:D.tooltip,callbacks:{label:function(I){if(Array.isArray(I.raw)&&I.raw.every(T=>T===null))return null},footer:function(I){var F,P,R,B;return(((P=(F=s==null?void 0:s.interactionConfig)==null?void 0:F.drillHierarchies)==null?void 0:P.length)??0)>0||(((B=(R=s==null?void 0:s.interactionConfig)==null?void 0:R.interactions)==null?void 0:B.some(z=>z.mode==="drillDown"||z.mode==="drillToDetail"||z.mode==="drillThrough"||z.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},y=es(x,h),S=qQ(t,r),w=es(y,S);let C;r!=null&&r.dataLabelsConfig?C=Eg(w,r.dataLabelsConfig,r,"range",s):C={...w,plugins:{...w==null?void 0:w.plugins,datalabels:{...(j=w==null?void 0:w.plugins)==null?void 0:j.datalabels,formatter:(I,T)=>I.map(P=>a(Number(P))).slice(0,2).join(" - ")}}};const{keys:N}=pr(e),k=N[0];return{type:"bar",data:{labels:[...new Set(Qc(e,k))],datasets:d},options:C,plugins:[...f]}}function aRe(e){var h,p,g,b;const{keys:t}=pr(e),n=t.slice(0,2),r=t.slice(2),s=m.useDashboardStore.getState().themeStyle,o=(p=(h=s==null?void 0:s.chart)==null?void 0:h.dataset)==null?void 0:p.backgroundColor,i=(b=(g=s==null?void 0:s.chart)==null?void 0:g.dataset)==null?void 0:b.borderColor,a=n[1],c=n[0],u=[...new Set(e.map(x=>x==null?void 0:x[c]))];return[...new Set(e.map(x=>x==null?void 0:x[a]))].map((x,y)=>{const S=e.filter(N=>(N==null?void 0:N[a])===x),C=u.map(N=>{const k=S.filter(_=>(_==null?void 0:_[c])===N);return k.length===0?[[null,null,null]]:k.map(_=>[_==null?void 0:_[r[0]],_==null?void 0:_[r[1]],_==null?void 0:_[r[2]],N])}).flat();return{label:x,data:C,backgroundColor:o==null?void 0:o[y%o.length],borderColor:i==null?void 0:i[y%i.length],borderSkipped:!1}})}function lRe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var C;const i=OAe(t),{keys:a}=pr(e),c=gv({dataArray:e,groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:u}=pr(c),d=u.slice(1),f=Ng(d,c,r),h=Da(f,n),p=u[0],g=Qc(c,p),{options:b,plugins:x}=sd({cardType:s,cfg:i,preferences:r,customCfg:n,card:o}),y={type:(n==null?void 0:n.type)||(i==null?void 0:i.type)||"bar",data:{labels:g,datasets:h},options:b,plugins:x},S="x2";return{...y,data:{...y.data,datasets:y.data.datasets.map((N,k)=>k===1?{...N,xAxisID:S}:N)},options:{...y.options,scales:{...(C=y==null?void 0:y.options)==null?void 0:C.scales,[S]:{beginAtZero:!0,stack:1}}}}}const mB={type:"treemap",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function cRe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s,card:o}){var k;if(!e||e.length===0)return mB;const{dimensionKeys:i,metricKeys:a,keys:c}=pr(e),u=i.length>0?i:c.slice(0,1);let d=a[0];if(d||(d=c.find(_=>!u.includes(_))||a[0]||c[1]),!d)return console.warn("Treemap chart could not determine a metric column."),mB;const f=hRe(e,u,d),h=s??m.useDashboardStore.getState().themeStyle,p=((k=r==null?void 0:r.chartOptions)==null?void 0:k.treemapColorMode)??"branch",g=pRe(f,u,r,h),b=mRe(r,o),x=uRe({tree:f,dimensionKeys:u,metricKey:d,colorLookups:g,formatConfig:b,themeStyle:h,preferences:r,colorMode:p}),y=dRe({dimensionKeys:u,metricKey:d,formatConfig:b}),{plugins:S,options:w}=kd((r==null?void 0:r.customVisualCode)||""),C=fRe([y,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,w]);return{type:"treemap",data:{datasets:[x]},options:C,plugins:S||[]}}function uRe({tree:e,dimensionKeys:t,metricKey:n,colorLookups:r,formatConfig:s,themeStyle:o,preferences:i,colorMode:a}){var p,g,b,x,y,S,w,C,N,k,_;const c=Cv("treemap",i),u=(i==null?void 0:i.dataLabelsConfig)??c,d=(u==null?void 0:u.enabled)!==!1&&(u==null?void 0:u.display)!==!1&&e.length>0,f=u!=null&&u.color&&u.color!=="auto"?u.color:void 0;return{tree:e,key:n,groups:t.length>1?t:void 0,data:[],spacing:1,borderWidth:1,borderColor:((b=(g=(p=o==null?void 0:o.chart)==null?void 0:p.dataset)==null?void 0:g.borderColor)==null?void 0:b[0])||"rgba(255,255,255,0.8)",labels:{display:d,align:"center",position:"middle",overflow:"fit",formatter:E=>{if(!d)return"";const D=E==null?void 0:E.raw,j=HJ(D,t),I=Number((D==null?void 0:D.v)??0),T=UJ(I,s);return j?`${j}
814
- ${T}`:T},color:E=>{if(f)return f;const D=E==null?void 0:E.raw,j=gB({raw:D,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a});return m.getContrastColor(j)},font:{size:((y=(x=o==null?void 0:o.chart)==null?void 0:x.font)==null?void 0:y.size)||((S=u==null?void 0:u.font)==null?void 0:S.size)||12,weight:((C=(w=o==null?void 0:o.chart)==null?void 0:w.font)==null?void 0:C.weight)||((N=u==null?void 0:u.font)==null?void 0:N.weight)||"bold",family:((_=(k=o==null?void 0:o.chart)==null?void 0:k.font)==null?void 0:_.family)||"Inter"}},backgroundColor:E=>{const D=E==null?void 0:E.raw;return gB({raw:D,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a})}}}function dRe({dimensionKeys:e,metricKey:t,formatConfig:n}){const r=Math.max(e.length-1,0);return{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},tooltip:{intersect:!0,mode:"point",filter:s=>{if(e.length<=1)return!0;const o=s.raw;return typeof(o==null?void 0:o.l)=="number"?o.l===r:!0},callbacks:{title:s=>{if(!(s!=null&&s.length))return"";const o=s[s.length-1];return bRe(o==null?void 0:o.raw,e)},label:s=>{const o=s==null?void 0:s.raw,i=HJ(o,e),a=Number((o==null?void 0:o.v)??0),c=UJ(a,n),u=t||"Value";return i?`${i} — ${u}: ${c}`:`${u}: ${c}`}}}}}}function fRe(e){return e.reduce((t,n)=>es(t,n||{}),{})}function hRe(e,t,n){return e.map(r=>{const s={...r};t.forEach(i=>{const a=r[i];(a==null||a==="")&&(s[i]="(Blank)")});const o=Number(r[n]);return s[n]=Number.isFinite(o)?o:0,s})}function pRe(e,t,n,r){var o,i,a;const s=((a=(i=(o=r==null?void 0:r.chart)==null?void 0:o.dataset)==null?void 0:i.backgroundColor)==null?void 0:a.filter(Boolean))??qh();return t.map((c,u)=>{const d=new Map;return u>0||Array.from(new Set(e.map(h=>h[c]).filter(h=>!!h))).forEach((h,p)=>{var g,b;if((b=(g=n==null?void 0:n.colorConfig)==null?void 0:g.segments)!=null&&b[h]){d.set(h,n.colorConfig.segments[h]);return}d.set(h,s[p%s.length])}),d})}function mRe(e,t){const n=bv({card:t,chartType:"treemap",preferences:e,dataLabelsConfig:e==null?void 0:e.dataLabelsConfig}),r=n.formatOptions||{};if(_g(n))return{format:"number",formatOptions:{},rawValue:!0};const s=["decimalPlaces","currency","locale","useSuffix","prefix","suffix","negativeInParentheses","multiplyBy"],o=Object.fromEntries(Object.entries(r).filter(([i])=>s.includes(i)));return{format:r.type||"number",formatOptions:o}}function HJ(e,t){var n;if(!e)return"";if((n=e._data)!=null&&n.label)return e._data.label;if(e.g)return e.g;if(e._data)return gRe(e._data,t);if(e.path){const r=e.path.split("."),s=r[r.length-1];if(s)return s}return""}function gRe(e,t){for(let n=t.length-1;n>=0;n-=1){const r=e[t[n]];if(r!=null&&r!=="")return r}return"(Blank)"}function bRe(e,t){var n;return(n=e==null?void 0:e._data)!=null&&n.path?e._data.path.split(".").filter(Boolean).join(" → "):e!=null&&e.path?e.path.split(".").filter(Boolean).join(" → "):e!=null&&e._data?t.map(r=>{var s;return((s=e._data)==null?void 0:s[r])??"(Blank)"}).filter(Boolean).join(" → "):e!=null&&e.g?e.g:""}function UJ(e,t){return t.rawValue?String(e):Fn(e,t.format,t.formatOptions)}function gB({raw:e,dimensionKeys:t,colorLookups:n,themeStyle:r,preferences:s,colorMode:o}){var g,b,x,y,S,w,C;if(!e)return"#999999";const i=((x=(b=(g=r==null?void 0:r.chart)==null?void 0:g.dataset)==null?void 0:b.backgroundColor)==null?void 0:x.filter(Boolean))??qh(),a=xRe(e,t),c=a[0]||((y=e._data)==null?void 0:y[t[0]])||e.g||"",u=((w=(S=s==null?void 0:s.colorConfig)==null?void 0:S.segments)==null?void 0:w[c])||((C=n[0])==null?void 0:C.get(c))||i[0]||"#999999",d=Math.max(t.length-1,0),f=typeof e.l=="number"?e.l:a.length-1,h=DO(f,0,d);if(h===0||o==="category")return u;const p=yRe(e);return vRe(u,p,h)}function xRe(e,t){var r;if(!e)return[];if((r=e._data)!=null&&r.path)return e._data.path.split(".").filter(Boolean);if(e.path)return e.path.split(".").filter(Boolean);const n=t.map(s=>{var o;return(o=e._data)==null?void 0:o[s]}).filter(s=>!!s);return n.length?n:e.g?[e.g]:[]}function yRe(e){if(!e)return 1;const t=Number(e.v??0),n=Number(e.gs??e.s??0);return n>0&&Number.isFinite(t)?DO(t/n,0,1):1}function vRe(e,t,n){const r=Math.min(n*.12,.35),s=Math.max(0,.25*(1-t)),o=Math.min(r+s,.6),i=Math.max(0,t-.85)*.4;let a=bB(e,"#ffffff",o);return a=bB(a,"#000000",i),a}function bB(e,t,n){const r=DO(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=xB(e),o=xB(t);if(!s||!o)return e;const i=Math.round(s.r+(o.r-s.r)*r),a=Math.round(s.g+(o.g-s.g)*r),c=Math.round(s.b+(o.b-s.b)*r);return wRe(i,a,c)}function xB(e){const t=e.replace("#","");if(t.length!==6)return null;const n=parseInt(t,16);return{r:n>>16&255,g:n>>8&255,b:n&255}}function wRe(e,t,n){const r=s=>s.toString(16).padStart(2,"0");return`#${r(RD(e))}${r(RD(t))}${r(RD(n))}`}function RD(e){return Math.min(255,Math.max(0,Math.round(e)))}function DO(e,t,n){return Math.max(t,Math.min(n,e))}function WJ(e,t){if(!e||t===1)return e;e=e.replace(/^#/,""),e.length===3&&(e=e.split("").map(o=>o+o).join(""));const n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16);return`rgba(${n}, ${r}, ${s}, ${t})`}function SRe(e,t,n,r){var a;if(e==null)return"";const s=Number(e);if(isNaN(s))return String(e);const o=t.format||"auto",i=t.formatOptions||{};switch(o){case"currency":return Fn(s,"currency",{currency:i.currency||"USD",decimalPlaces:i.decimalPlaces??2,useSuffix:i.useSuffix,locale:i.locale});case"number":return Fn(s,"number",{decimalPlaces:i.decimalPlaces??0,useSuffix:i.useSuffix,locale:i.locale});case"percent":return Fn(s,"percent",{decimalPlaces:i.decimalPlaces??1,locale:i.locale});case"none":return String(e);case"auto":default:return n!=null&&n.type&&n.type!=="auto"?Fn(s,n.type,n):(a=r==null?void 0:r.formatOptions)!=null&&a.type&&r.formatOptions.type!=="auto"?Fn(s,r.formatOptions.type,r.formatOptions):String(e)}}function T_(e,t,n,r){var p,g;if(!(e.enabled??!1))return{display:!1};const o=e.position||"auto";let i,a;if(o==="custom")i=e.anchor||"center",a=e.align||"center";else{const x=n==="horizontalBar"?{auto:{anchor:"end",align:"right"},top:{anchor:"end",align:"right"},center:{anchor:"center",align:"center"},bottom:{anchor:"start",align:"left"},left:{anchor:"start",align:"left"},right:{anchor:"end",align:"right"}}:{auto:{anchor:"end",align:"top"},top:{anchor:"end",align:"top"},center:{anchor:"center",align:"center"},bottom:{anchor:"start",align:"bottom"},left:{anchor:"start",align:"left"},right:{anchor:"end",align:"right"}},y=x[o]||x.auto;i=y.anchor,a=y.align}const c=e.color,u=b=>{var y,S,w,C,N,k;if(c&&c!=="auto")return c;if(o!=="center"||n==="line"||n==="area")return m.getContrastColor(m.getCanvasBackgroundColor((y=b==null?void 0:b.chart)==null?void 0:y.canvas));const x=((w=(S=b.dataset)==null?void 0:S.backgroundColor)==null?void 0:w[b.dataIndex])||((C=b.dataset)==null?void 0:C.backgroundColor)||m.getCanvasBackgroundColor((N=b==null?void 0:b.chart)==null?void 0:N.canvas);return m.getContrastColor(x,{baseColor:m.getCanvasBackgroundColor((k=b==null?void 0:b.chart)==null?void 0:k.canvas)})},d=((p=e.font)==null?void 0:p.size)||11,f=((g=e.font)==null?void 0:g.weight)||"normal",h=e.rotation||0;return{display:e.display==="auto"?"auto":!0,formatter:b=>SRe(b,e,r,t),anchor:i,align:a,color:u,font:{size:d,weight:f},rotation:h,clamp:e.clamp??!0,clip:e.clip??!1,offset:e.offset??4}}function M_(e,t){t&&(e.onHover=function(n,r){var o;const s=((o=n.native)==null?void 0:o.target)||n.target;r.length?s.style.cursor="pointer":s.style.cursor="default"})}function IO(e){switch(e){case"dashed":return[6,4];case"dotted":return[2,2];case"dash-dot":return[6,2,2,2];case"solid":default:return[]}}function A_(e,t){if(t!==void 0)return t.enabled===!1?{enabled:!1}:t.enabled===void 0?e!=null&&e.enabled?{...e,...t,enabled:!0,formatOptions:{...e.formatOptions,...t.formatOptions},font:{...e.font,...t.font}}:void 0:e?{enabled:!0,display:t.display??e.display,position:t.position??e.position,anchor:t.anchor??e.anchor,align:t.align??e.align,offset:t.offset??e.offset,rotation:t.rotation??e.rotation,clamp:t.clamp??e.clamp,clip:t.clip??e.clip,format:t.format??e.format,formatOptions:{...e.formatOptions,...t.formatOptions},font:{...e.font,...t.font},color:t.color??e.color}:t}function CRe(e,t){return Array.from({length:e},(n,r)=>({idx:r,fill:t&&r>0?"-1":"origin"}))}function NRe(e,t,n){const r=CRe(t,n);return!e||e.length===0?r:r.map(s=>{const o=e.find(i=>i.idx===s.idx);return o?{...s,...o,fill:o.fill??s.fill}:s})}function kRe(e,t,n,r,s){const o=n==null?void 0:n.lineStyleConfig,i=n==null?void 0:n.yAxisConfig;return e.map((a,c)=>{const u=t.find(g=>g.idx===c),d={...a};d.type="line",d.fill=(u==null?void 0:u.fill)??"origin",d.borderWidth=d.borderWidth??2,d.tension=d.tension??.1,d.pointRadius=(u==null?void 0:u.pointRadius)??(o==null?void 0:o.pointRadius)??3,d.pointStyle=(u==null?void 0:u.pointStyle)??(o==null?void 0:o.pointStyle)??"circle";const f=(u==null?void 0:u.pointRadius)??(o==null?void 0:o.pointRadius)??3;d.pointHoverRadius=(u==null?void 0:u.pointHoverRadius)??f+2,d.borderDash=IO((u==null?void 0:u.lineStyle)??(o==null?void 0:o.lineStyle));const h=d.borderColor||d.backgroundColor;h&&typeof h=="string"&&(d.backgroundColor=WJ(h,.5));const p=A_(n==null?void 0:n.dataLabelsConfig,u==null?void 0:u.dataLabels);if(p){const g=xv({card:s,preferences:n,dataLabelsConfig:p,datasetIndex:c,datasetLabel:a.label}).formatOptions;d.datalabels=T_(p,i,"area",g)}return d})}function _Re(e,t){var r,s;return{...e,x:{...e==null?void 0:e.x,display:((r=e==null?void 0:e.x)==null?void 0:r.display)??!0},y:{...e==null?void 0:e.y,display:((s=e==null?void 0:e.y)==null?void 0:s.display)??!0,stacked:t}}}function jRe({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var N,k;const{keys:i}=pr(t),a=Oy(i),c=a.length,u=o==="stackedArea",d=NRe(s==null?void 0:s.datasetOptions,c,u),f=i==null?void 0:i[0],h=Qc(t,f),p=Ng(a,t,s,1,"none",f,!1,Cg(t)),g=kRe(p,d,s,u,e),b=Da(g,r),{options:x,plugins:y}=sd({cardType:o||"area",cfg:n,preferences:s,customCfg:r,card:e}),S=_Re(x==null?void 0:x.scales,u),w={...x,scales:S},C=(((k=(N=e.interactionConfig)==null?void 0:N.interactions)==null?void 0:k.length)??0)>0;return M_(w,C),{type:"line",data:{labels:h,datasets:b},options:w,plugins:y}}const qJ=["poor","satisfactory","good"],FD={poor:"Poor",satisfactory:"Average",good:"Good"},ERe=["#F5F6F8","#E3E6EC","#CED4DD"],DRe=["#1F2933","#27323D","#303B47"];function IRe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s,card:o}){var fe,de,Se,ue,ve,xe,ke;if(!e||e.length===0)return{type:"bar",data:{labels:[],datasets:[]}};const{dimensionKeys:i,metricKeys:a,keys:c}=pr(e),u=i[0]??c[0];if(!u)return{type:"bar",data:{labels:[],datasets:[]}};const d=a[0]??c.find(se=>se!==u);if(!d)return{type:"bar",data:{labels:[],datasets:[]}};const f=r==null?void 0:r.bulletConfig,h=(f==null?void 0:f.targetMetricKey)??a.find(se=>se!==d),p=(f==null?void 0:f.comparativeMetricKey)??(f!=null&&f.disableAutoComparative?void 0:a.find(se=>se!==d&&se!==h)),g=m.useDashboardStore.getState(),b=s??g.themeStyle,x=g.theme==="dark",y=TRe({data:e,dimensionKey:u,actualKey:d,targetKey:h,comparativeKey:p,bulletConfig:f}),S=y.map(se=>se.label),w=(f==null?void 0:f.showRanges)??WRe(f),C=RRe(y,w),N=(fe=r==null?void 0:r.chartOptions)==null?void 0:fe.indexAxis,_=(N?N==="y"?"horizontal":"vertical":void 0)??(f==null?void 0:f.orientation)??"horizontal",E=_==="vertical"?"x":"y",D=r?{...r,chartOptions:{...r.chartOptions||{},indexAxis:E}}:{chartOptions:{indexAxis:E}},j=VRe(r,o,d),I=URe(f),T=HRe(x),F=qh().filter(Boolean),P=(((Se=(de=b==null?void 0:b.chart)==null?void 0:de.dataset)==null?void 0:Se.backgroundColor)||[]).filter(Boolean),R=(((ve=(ue=b==null?void 0:b.chart)==null?void 0:ue.dataset)==null?void 0:ve.borderColor)||[]).filter(Boolean),B=P.length>0?P:F.length>0?F:["#3b82f6"],z=R.length>0?R:B.length>0?B:["#111827"],U=OD({metricKey:d,metricIndex:0,preferences:r,backgroundPalette:B,borderPalette:z}),O=OD({metricKey:h||`${d}__target`,metricIndex:1,preferences:r,backgroundPalette:B,borderPalette:z}).borderColor||U.borderColor||"#111827",K=OD({metricKey:p,metricIndex:2,preferences:r,backgroundPalette:B,borderPalette:z}),q=w?FRe(y,T,_,x,I):[],M=PRe(y,U,_,d),G=ORe(y,K,_,p),L=[...q,M];G&&L.push(G);let $=LRe({orientation:_,chartMax:C,formatConfig:j,series:y,preferences:D,rangeLabelMap:I,showRanges:w,card:o});const V=(ke=(xe=r==null?void 0:r.chartOptions)==null?void 0:xe.plugins)==null?void 0:ke.legend;$=pO($,V);const{plugins:H=[],options:A}=kd((r==null?void 0:r.customVisualCode)||""),W=KRe([$,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,A]),X=y.some(se=>se.target!=null)&&C>0?BRe({series:y,orientation:_,color:O}):null,Z={type:"bar",data:{labels:S,datasets:L},options:W,plugins:X?[...H,X]:H},J=Cv("bullet",r),re=(r==null?void 0:r.dataLabelsConfig)??J;return Z.options=Eg(Z.options||{},re,D,"bar",o),Z.options=jg.applyAxisConfig(Z.options||{},"bar",D,o),Z.options=Z.options||{},Z.options.indexAxis=E,Z}function TRe({data:e,dimensionKey:t,actualKey:n,targetKey:r,comparativeKey:s,bulletConfig:o}){const i=e.map(c=>{const u=ARe(c[t]),d=$S(c[n]),f=r&&c[r]!=null?$S(c[r]):(o==null?void 0:o.targetValue)??null,h=s&&c[s]!=null?$S(c[s]):null;return{label:u,actual:d,target:f,comparative:h,row:c}}),a=i.reduce((c,u)=>{var d;return Math.max(c,u.actual,u.target??0,u.comparative??0,((d=o==null?void 0:o.ranges)==null?void 0:d.good)??0)},0);return i.map(c=>{const u=MRe({row:c.row,actual:c.actual,target:c.target,globalMax:a||c.actual||1,bulletConfig:o});return{label:c.label,actual:c.actual,target:c.target??void 0,comparative:c.comparative??void 0,ranges:u,actualKey:n,targetKey:r||void 0,comparativeKey:s||void 0}})}function MRe({row:e,actual:t,target:n,globalMax:r,bulletConfig:s}){const o=s==null?void 0:s.rangeKeys,i=s==null?void 0:s.ranges,a=Math.max(t,n??0,r),c={poor:PD("poor",e,o,i,a*.5,s,a),satisfactory:PD("satisfactory",e,o,i,a*.8,s,a),good:PD("good",e,o,i,a,s,a)};let u=0;return qJ.forEach(d=>{const f=c[d];if(!Number.isFinite(f)||f<0){c[d]=u;return}f<u?c[d]=u:u=f}),c}function PD(e,t,n,r,s,o,i){const a=n==null?void 0:n[e];if(a&&t[a]!=null)return $S(t[a]);if((r==null?void 0:r[e])!=null){const c=r[e];return o!=null&&o.rangesArePercentages?c*i:c}return s}function $S(e){const t=Number(e);return Number.isFinite(t)?t:0}function ARe(e){return e==null||e===""?"(Blank)":String(e)}function RRe(e,t){const n=e.reduce((r,s)=>{const o=[r,s.actual,s.target??0,s.comparative??0];return t&&o.push(s.ranges.good),Math.max(...o)},0);return n>0?n*1.1:1}function FRe(e,t,n,r,s){const o=[];return qJ.forEach((i,a)=>{const c=[],u=e.map(f=>{const h=f.ranges[i];return c.push({start:0,end:h}),h}),d={type:"bar",label:s[i],data:u,order:10,backgroundColor:YRe(t[a]??t[t.length-1],.35,r),borderWidth:0,borderSkipped:!1,barPercentage:n==="vertical"?.9:.85,categoryPercentage:.9,grouped:!1,datalabels:{display:!1},customRole:"range",rangeMeta:c};o.push(d)}),o}function PRe(e,t,n,r){return{type:"bar",label:r||"Actual",data:e.map(s=>s.actual),order:1,backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderRadius:n==="vertical"?{topLeft:4,topRight:4,bottomLeft:0,bottomRight:0}:4,barPercentage:n==="vertical"?.6:.4,categoryPercentage:.6,grouped:!1,stack:"actual",base:0,customRole:"actual"}}function ORe(e,t,n,r){return e.some(s=>s.comparative!=null)?{type:"bar",label:r||"Comparative",data:e.map(s=>s.comparative??null),order:2,borderColor:t.borderColor,backgroundColor:"transparent",borderWidth:2,borderSkipped:!1,barPercentage:n==="vertical"?.6:.4,categoryPercentage:.6,grouped:!1,stack:"comparative",base:0,datalabels:{display:!1},customRole:"comparative"}:null}function LRe({orientation:e,chartMax:t,formatConfig:n,series:r,preferences:s,rangeLabelMap:o,showRanges:i,card:a}){var h,p,g,b,x,y,S,w,C;const c={type:"linear",stacked:!1,beginAtZero:!0,suggestedMax:t,ticks:{callback:N=>Fn(Number(N),n.format,n.options)},grid:{drawOnChartArea:!0}},u={type:"category",stacked:!0,grid:{display:!1}};return{responsive:!0,maintainAspectRatio:!1,scales:{x:e==="vertical"?u:c,y:e==="vertical"?c:u},plugins:{legend:{display:((g=(p=(h=s==null?void 0:s.chartOptions)==null?void 0:h.plugins)==null?void 0:p.legend)==null?void 0:g.display)??!0,position:((y=(x=(b=s==null?void 0:s.chartOptions)==null?void 0:b.plugins)==null?void 0:x.legend)==null?void 0:y.position)??"top",align:((C=(w=(S=s==null?void 0:s.chartOptions)==null?void 0:S.plugins)==null?void 0:w.legend)==null?void 0:C.align)??"center"},tooltip:{filter:N=>{const k=N.dataset.customRole;return k?k!=="range":!0},callbacks:$Re(r,n,o,i,s,a)}},indexAxis:e==="vertical"?"x":"y"}}function $Re(e,t,n,r,s,o){const i=(a,c)=>{var f;const u=ed(o,{columnId:c,metricAlias:c}),d=WP({card:o,chartType:"bar",preferences:s,metric:u,axis:((f=s==null?void 0:s.chartOptions)==null?void 0:f.indexAxis)==="y"?"x":"y"}).formatOptions;return d!=null&&d.type&&d.type!=="auto"?Fn(a,d.type,d):Fn(a,t.format,t.options)};return{title:a=>{var c;return a.length?((c=e[a[0].dataIndex])==null?void 0:c.label)??"":""},label:a=>{const c=e[a.dataIndex];return c?`${c.actualKey||"Actual"}: ${i(c.actual,c.actualKey)}`:a.formattedValue},afterBody:a=>{if(!a.length)return[];const c=e[a[0].dataIndex];if(!c)return[];const u=[];if(c.target!=null){const h=i(c.target,c.targetKey),p=c.actual-c.target,g=i(p,c.actualKey),b=c.targetKey||"Target";u.push(`${b}: ${h} (${g})`)}const d=zRe(c,n);r&&d&&u.push(`Range: ${d}`);const f=c.comparative;return f!=null&&u.push(`Comparative: ${i(f,c.comparativeKey)}`),u}}}function zRe(e,t){const{actual:n,ranges:r}=e;return n<=r.poor?`${t.poor} (≤ ${r.poor.toLocaleString()})`:n<=r.satisfactory?`${t.satisfactory} (${r.poor.toLocaleString()} – ${r.satisfactory.toLocaleString()})`:`${t.good} (${r.satisfactory.toLocaleString()} – ${r.good.toLocaleString()})`}function BRe({series:e,orientation:t,color:n}){return{id:"bulletTargetMarkers",afterDatasetsDraw(r){const s=r.ctx,o=r.scales[t==="vertical"?"y":"x"],i=r.scales[t==="vertical"?"x":"y"];if(!o||!i)return;const a=r.config.data.datasets,c=a.findIndex(d=>d.customRole==="actual"),u=a.findIndex(d=>d.customRole==="range");s.save(),s.strokeStyle=n,s.lineWidth=2,e.forEach((d,f)=>{var x,y,S,w,C;if(d.target==null)return;const h=(x=r.data.labels)==null?void 0:x[f],p=((S=(y=r.getDatasetMeta(u>=0?u:c>=0?c:0))==null?void 0:y.data)==null?void 0:S[f])||((C=(w=r.getDatasetMeta(0))==null?void 0:w.data)==null?void 0:C[f]),g=p?t==="horizontal"?p.height??p.width??20:p.width??p.height??20:20,b=Math.max(Math.min(g/2,12),6);if(t==="horizontal"){const N=o.getPixelForValue(d.target),k=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(N,k-b),s.lineTo(N,k+b),s.stroke(),s.beginPath(),s.moveTo(N-4,k-b),s.lineTo(N+4,k-b),s.moveTo(N-4,k+b),s.lineTo(N+4,k+b),s.stroke()}else{const N=o.getPixelForValue(d.target),k=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(k-b,N),s.lineTo(k+b,N),s.stroke(),s.beginPath(),s.moveTo(k-b,N-4),s.lineTo(k-b,N+4),s.moveTo(k+b,N-4),s.lineTo(k+b,N+4),s.stroke()}}),s.restore()}}}function VRe(e,t,n){var a,c;const r=kg({card:t,chartType:"bar",axis:((a=e==null?void 0:e.chartOptions)==null?void 0:a.indexAxis)==="y"?"x":"y",preferences:e,axisConfig:((c=e==null?void 0:e.chartOptions)==null?void 0:c.indexAxis)==="y"?e==null?void 0:e.xAxisConfig:e==null?void 0:e.yAxisConfig}).formatOptions,s=ed(t,{columnId:n,metricAlias:n}),o=x_(s),i=r??o??(e==null?void 0:e.numberAxisFormat)??(e==null?void 0:e.formatNumber)??{};return{format:(r==null?void 0:r.type)||(o==null?void 0:o.type)||"number",options:i}}function HRe(e){return[...e?DRe:ERe]}function URe(e){var n,r,s;const t=(e==null?void 0:e.rangeLabels)||{};return{poor:((n=t.poor)==null?void 0:n.trim())||FD.poor,satisfactory:((r=t.satisfactory)==null?void 0:r.trim())||FD.satisfactory,good:((s=t.good)==null?void 0:s.trim())||FD.good}}function WRe(e){if(!e)return!1;const t=Object.values(e.rangeKeys||{}).some(r=>!!r),n=Object.values(e.ranges||{}).some(r=>r!=null);return t||n}function qRe(e,t,n){const r=YJ(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=yB(e),o=yB(t);if(!s||!o)return e;const i=Math.round(s.r+(o.r-s.r)*r),a=Math.round(s.g+(o.g-s.g)*r),c=Math.round(s.b+(o.b-s.b)*r);return GRe(i,a,c)}function YRe(e,t,n){return qRe(e,n?"#000000":"#ffffff",t)}function OD({metricKey:e,metricIndex:t,preferences:n,backgroundPalette:r,borderPalette:s}){var d,f;const o=r[t%r.length]||r[0]||"#3b82f6",i=s[t%s.length]||s[0]||o,a=e&&((f=(d=n==null?void 0:n.colorConfig)==null?void 0:d.segments)==null?void 0:f[e])||void 0;return{backgroundColor:a||o,borderColor:a||i}}function yB(e){const t=e.replace("#","");if(t.length!==6)return null;const n=parseInt(t,16);return{r:n>>16&255,g:n>>8&255,b:n&255}}function GRe(e,t,n){return`#${LD(e)}${LD(t)}${LD(n)}`}function LD(e){return YJ(Math.round(e),0,255).toString(16).padStart(2,"0")}function YJ(e,t,n){return Math.max(t,Math.min(n,e))}function KRe(e){return e.reduce((t,n)=>es(t,n||{}),{})}const YM={blue:{start:"#dbeafe",end:"#1d4ed8",label:"Blue"},green:{start:"#dcfce7",end:"#15803d",label:"Green"},purple:{start:"#ede9fe",end:"#6d28d9",label:"Purple"},orange:{start:"#ffedd5",end:"#c2410c",label:"Orange"}},GJ=["#dcfce7","#15803d"],b1={type:"matrix",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function ZRe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o,card:i}){var $,V,H;if(!Array.isArray(e)||e.length===0)return b1;const{dimensionKeys:a,metricKeys:c,keys:u}=pr(e),d=a[0]??u[0];if(!d)return b1;const f=a[1],h=u.find(A=>A!==d&&!c.includes(A)&&A!==f)??f,p=!f&&(!h||typeof(($=e[0])==null?void 0:$[h])!="string")&&c.length>1,g=c[0]??u.find(A=>A!==d&&A!==h);if(!g&&!p)return b1;const b=r==null?void 0:r.heatmapConfig,x=(b==null?void 0:b.legendPosition)??"bottom",y=p?QRe({data:e,dimensionKey:d,metricKeys:c}):XRe({data:e,xKey:d,yKey:h||g,metricKey:g});if(y.length===0)return b1;const S=p?c.map(Qm):$D(y.map(A=>A.x)),w=$D(p?e.map(A=>Qm(A==null?void 0:A[d])):y.map(A=>A.y)),C=JRe(y),N=o??m.useDashboardStore.getState().themeStyle,k=oFe({min:C.min,max:C.max,heatmapConfig:b,themeStyle:N}),_=eFe({points:y,xLabels:S,yLabels:w,fill:(b==null?void 0:b.fillMissingCells)!==!1}),E=uFe(r,i),j=["auto","number","currency","percent","none"].includes(E.format)?E.format:"auto",I=Cv("heatmap",r),T=I?{...I,format:I.format??j,formatOptions:I.formatOptions??E.options}:void 0,F=(r==null?void 0:r.dataLabelsConfig)??T,P=tFe({points:_,xLabels:S,yLabels:w,colorScale:k,datasetLabel:p?"Value":g||"Value",dataLabelPrefs:F,formatConfig:E,preferences:r,card:i}),R=nFe({xLabels:S,yLabels:w,heatmapConfig:b,formatConfig:E,themeStyle:N,legendPreferences:(H=(V=r==null?void 0:r.chartOptions)==null?void 0:V.plugins)==null?void 0:H.legend,cardType:s,legendPosition:x,preferences:r,card:i}),{plugins:B=[],options:z}=kd((r==null?void 0:r.customVisualCode)||""),U=dFe([R,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,z]),Y=(b==null?void 0:b.showLegend)===!1?null:iFe({stops:k.stops,min:C.min,max:C.max,formatConfig:E,position:x}),O={type:"matrix",data:{datasets:[P]},options:U,plugins:Y?[...B,Y]:B};O.options=Eg(O.options||{},F,r,"matrix",void 0);const K=fM(s??"heatmap","x"),q=fM(s??"heatmap","y"),M=hM(K,r==null?void 0:r.xAxisConfig),G=hM(q,r==null?void 0:r.yAxisConfig),L=M||G||r?{...r||{},...M?{xAxisConfig:M}:{},...G?{yAxisConfig:G}:{}}:r;return O.options=jg.applyAxisConfig(O.options||{},"heatmap",L,void 0),O}function XRe({data:e,xKey:t,yKey:n,metricKey:r}){const s=new Map;return e.forEach(o=>{const i=o==null?void 0:o[t],a=o==null?void 0:o[n];if(i===void 0||a===void 0)return;const c=Qm(i),u=Qm(a),d=`${c}__${u}`,f=KJ(o==null?void 0:o[r]);if(!s.has(d)){s.set(d,{x:c,y:u,v:f,raw:o});return}const h=s.get(d);h&&(h.v==null?h.v=f:f!=null&&(h.v+=f))}),Array.from(s.values())}function QRe({data:e,dimensionKey:t,metricKeys:n}){const r=[];return e.forEach(s=>{const o=s==null?void 0:s[t];if(o===void 0)return;const i=Qm(o);n.forEach(a=>{if(a===t)return;const c=KJ(s==null?void 0:s[a]),u=Qm(a);r.push({x:u,y:i,v:c,raw:{...s,_metricKey:a}})})}),r}function Qm(e){return e==null||e===""?"Unknown":String(e)}function KJ(e){const t=Number(e);return Number.isFinite(t)?t:null}function $D(e){const t=new Set,n=[];return e.forEach(r=>{t.has(r)||(t.add(r),n.push(r))}),n}function JRe(e){let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,r=!1;return e.forEach(s=>{s.v==null||s.v===0||(t=Math.min(t,s.v),n=Math.max(n,s.v),r=!0)}),r?{min:t,max:n}:{min:0,max:0}}function eFe({points:e,xLabels:t,yLabels:n,fill:r}){if(!r)return e;const s=new Map;e.forEach(i=>{s.set(`${i.x}__${i.y}`,i)});const o=[];return t.forEach(i=>{n.forEach(a=>{const c=`${i}__${a}`,u=s.get(c);u?o.push(u):o.push({x:i,y:a,v:null})})}),o}function tFe({points:e,xLabels:t,yLabels:n,colorScale:r,datasetLabel:s,dataLabelPrefs:o,formatConfig:i,preferences:a,card:c}){const u=OTe(e.length,o),d=Math.max(t.length||1,n.length||1);return{label:s,data:e,backgroundColor:h=>{const p=h==null?void 0:h.raw;return r.getColor((p==null?void 0:p.v)??null)},hoverBackgroundColor:h=>{const p=h==null?void 0:h.raw,g=r.getColor((p==null?void 0:p.v)??null);return cFe(g,.85)},borderWidth:1,borderColor:"rgba(255, 255, 255, 0.65)",width:({chart:h})=>{var p;return vB((p=h==null?void 0:h.chartArea)==null?void 0:p.width,t.length)},height:({chart:h})=>{var p;return vB((p=h==null?void 0:h.chartArea)==null?void 0:p.height,n.length)},datalabels:{display:u,anchor:"center",align:"center",formatter:h=>{let p=null,g;return typeof h=="number"?p=h:h&&typeof h=="object"&&"v"in h&&(g=h,p=Number(g.v)),p==null||Number.isNaN(p)?"":TO(p,QJ(g,i??{format:"number",options:{}},a,c))},color:h=>{const p=h==null?void 0:h.raw,g=r.getColor((p==null?void 0:p.v)??null)||"rgba(148,163,184,0.35)";return m.getContrastColor(lFe(g))},font:{size:Math.max(10,Math.min(14,120/d))}}}}function vB(e,t){return!e||t===0?0:Math.max(4,e/t-2)}function nFe({xLabels:e,yLabels:t,heatmapConfig:n,formatConfig:r,themeStyle:s,legendPreferences:o,cardType:i,legendPosition:a,preferences:c,card:u}){var b,x,y;const d=(n==null?void 0:n.showLegend)??!0,f=((y=(x=(b=s==null?void 0:s.chart)==null?void 0:b.options)==null?void 0:x.plugins)==null?void 0:y.tooltip)||{},h=mO(i??"heatmap"),p=UQ(h,o);return{responsive:!0,maintainAspectRatio:!1,layout:{padding:rFe(d,a)},plugins:{legend:p,tooltip:{...f,filter:S=>{const w=S==null?void 0:S.raw;return(w==null?void 0:w.v)!=null&&w.v!==0},callbacks:sFe(r,c,u)}},scales:{x:{type:"category",labels:e,offset:!0,grid:{display:!1},ticks:{autoSkip:!1}},y:{type:"category",labels:t,offset:!0,reverse:!1,grid:{display:!1},ticks:{autoSkip:!1}}}}}function rFe(e,t){const n={top:8,bottom:8,left:8,right:8};if(!e)return n;const r=36,s=48;switch(t){case"top":return{...n,top:n.top+r};case"bottom":return{...n,bottom:n.bottom+r};case"left":return{...n,left:n.left+s};case"right":return{...n,right:n.right+s};default:return n}}function sFe(e,t,n){return{title(r){var o;const s=(o=r==null?void 0:r[0])==null?void 0:o.raw;return s&&(s.y||s.x)||""},label(r){var c;const s=r==null?void 0:r.raw;if(!s||s.v==null)return"";const o=((c=r==null?void 0:r.dataset)==null?void 0:c.label)||s.x||"Value",i=s.x,a=TO(s.v,QJ(s,e,t,n));return i?`${i}: ${a}`:`${o}: ${a}`}}}function oFe({min:e,max:t,heatmapConfig:n,themeStyle:r}){var S,w;const s=((w=(S=r==null?void 0:r.chart)==null?void 0:S.dataset)==null?void 0:w.backgroundColor)||[],o=["#0ea5e9","#f97316"],i=(n==null?void 0:n.colorPalette)??"green",a=i!=="custom"?YM[i]??YM.blue:void 0,c=n==null?void 0:n.colorRange,u=c&&c[0]&&c[1]?c:a?[a.start,a.end]:i==="custom"?GJ:void 0,d=(u==null?void 0:u[0])??s[0]??o[0],f=(u==null?void 0:u[1])??s[1]??o[1],h=(n==null?void 0:n.colorMode)??"continuous",p=Math.max(3,(n==null?void 0:n.steps)??5),g=(n==null?void 0:n.nullFillColor)??"rgba(148, 163, 184, 0.25)",b=Math.max(t-e,Number.EPSILON),x=h==="continuous"?[{offset:0,color:Wd(d)},{offset:1,color:Wd(f)}]:Array.from({length:p}).map((C,N)=>{const k=p===1?0:N/(p-1||1);return{offset:k,color:wB(Wd(d),Wd(f),k)}}),y=h==="continuous"?null:x.map(C=>C.color);return{getColor(C){if(C==null||C===0)return g;if(h==="continuous"){const _=Jy((C-e)/b,0,1);return wB(Wd(d),Wd(f),_)}const N=Jy((C-e)/b,0,1),k=Math.min(p-1,Math.max(0,Math.floor(N*p)));return(y==null?void 0:y[k])??Wd(d)},stops:x}}function iFe({stops:e,min:t,max:n,formatConfig:r,position:s}){if(!e||e.length===0)return null;const o=i=>TO(i,r);return{id:"heatmapLegend",afterDraw(i){var g,b,x,y;const{ctx:a,chartArea:c}=i;if(!a||!c)return;a.save();const u=((y=(x=(b=(g=i.options)==null?void 0:g.plugins)==null?void 0:b.legend)==null?void 0:x.labels)==null?void 0:y.font)||{},d=u.size??12,f=u.family??"sans-serif",h=m.getContrastColor(m.getCanvasBackgroundColor(i.canvas)),p=24;if(a.font=`${d}px ${f}`,a.fillStyle=h,s==="bottom"||s==="top"){const w=c.left,C=c.right,N=s==="bottom"?c.bottom+p/2:c.top-10-p/2,k=a.createLinearGradient(w,0,C,0);e.forEach(E=>k.addColorStop(E.offset,E.color)),a.fillStyle=k,a.fillRect(w,N,C-w,10),a.fillStyle=h,a.textAlign="left",a.textBaseline=s==="bottom"?"top":"bottom";const _=s==="bottom"?N+10+4:N-4;a.fillText(o(t),w,_),a.textAlign="center",a.fillText(o(t+(n-t)/2),(w+C)/2,_),a.textAlign="right",a.fillText(o(n),C,_)}else{const w=c.top,C=c.bottom,N=s==="left"?c.left-10-p/2:c.right+p/2,k=a.createLinearGradient(0,w,0,C);e.forEach(E=>k.addColorStop(E.offset,E.color)),a.fillStyle=k,a.fillRect(N,w,10,C-w),a.fillStyle=h,a.textAlign=s==="left"?"right":"left",a.textBaseline="middle";const _=s==="left"?N-6:N+10+6;a.fillText(o(n),_,w),a.fillText(o(t+(n-t)/2),_,(w+C)/2),a.fillText(o(t),_,C)}a.restore()}}}function Wd(e){if(!e)return"#3b82f6";if(e.startsWith("rgb"))return e;if(e.startsWith("#")){const t=ZJ(e);return t?aFe(t.r,t.g,t.b,1):e}return e}function wB(e,t,n){const r=iN(e),s=iN(t);if(!r||!s)return e;const o=Jy(n,0,1),i=Math.round(r.r+(s.r-r.r)*o),a=Math.round(r.g+(s.g-r.g)*o),c=Math.round(r.b+(s.b-r.b)*o),u=r.a+(s.a-r.a)*o;return`rgba(${i}, ${a}, ${c}, ${u})`}function iN(e){if(e.startsWith("#")){const n=ZJ(e);return n?{...n,a:1}:null}const t=/rgba?\((?<r>\d+),\s*(?<g>\d+),\s*(?<b>\d+)(?:,\s*(?<a>[0-9.]+))?\)/i.exec(e);return!t||!t.groups?null:{r:Number(t.groups.r),g:Number(t.groups.g),b:Number(t.groups.b),a:t.groups.a!==void 0?Number(t.groups.a):1}}function ZJ(e){const t=e.replace("#","");if(![3,6].includes(t.length))return null;const n=t.length===3?t.split("").map(i=>i+i).join(""):t,r=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),o=parseInt(n.slice(4,6),16);return{r,g:s,b:o}}function aFe(e,t,n,r){return`rgba(${e}, ${t}, ${n}, ${r})`}function lFe(e){const t=iN(e);return t?`#${zD(t.r)}${zD(t.g)}${zD(t.b)}`:"#000000"}function zD(e){return Jy(Math.round(e),0,255).toString(16).padStart(2,"0")}function cFe(e,t){const n=iN(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${Jy(t,0,1)})`:e}function Jy(e,t,n){return Math.min(n,Math.max(t,e))}function TO(e,t){return e==null||Number.isNaN(e)?"—":t.rawValue?String(e):Fn(e,t.format,t.options)}function uFe(e,t){const n=bv({card:t,chartType:"heatmap",preferences:e,dataLabelsConfig:e==null?void 0:e.dataLabelsConfig});return XJ(n)}function XJ(e){const t=e.formatOptions||{};return _g(e)?{format:"number",options:{},rawValue:!0}:{format:t.type||"number",options:t}}function QJ(e,t,n,r){var i;const s=(i=e==null?void 0:e.raw)==null?void 0:i._metricKey;if(!s||!r)return t;const o=ed(r,{columnId:s,metricAlias:s});return o?XJ(AX({preferences:n,dataLabelsConfig:n==null?void 0:n.dataLabelsConfig,metric:o})):t}function dFe(e){return e.reduce((t,n)=>n?xl({},t,n):t,{})}function GM(){return{enabled:!0,position:"right",labels:{enabled:!0,rotation:"auto"},name:{enabled:!1}}}function fFe(e){return Array.from({length:e},(t,n)=>({idx:n,type:"bar",yAxisId:"y"}))}function hFe(e){return!e||e.length===0?!1:e.some(t=>t.yAxisId==="y2")}function pFe(e,t){var r,s,o,i,a,c,u,d,f,h,p,g,b,x;if(!t)return e||GM();const n=GM();return{...e,...t,name:{enabled:((r=t==null?void 0:t.name)==null?void 0:r.enabled)??((s=e==null?void 0:e.name)==null?void 0:s.enabled)??((o=n.name)==null?void 0:o.enabled)??!1,text:((i=t==null?void 0:t.name)==null?void 0:i.text)??((a=e==null?void 0:e.name)==null?void 0:a.text),fontSize:((c=t==null?void 0:t.name)==null?void 0:c.fontSize)??((u=e==null?void 0:e.name)==null?void 0:u.fontSize),fontWeight:((d=t==null?void 0:t.name)==null?void 0:d.fontWeight)??((f=e==null?void 0:e.name)==null?void 0:f.fontWeight)},labels:{enabled:((h=t==null?void 0:t.labels)==null?void 0:h.enabled)??((p=e==null?void 0:e.labels)==null?void 0:p.enabled)??((g=n.labels)==null?void 0:g.enabled)??!0,rotation:((b=t==null?void 0:t.labels)==null?void 0:b.rotation)??((x=e==null?void 0:e.labels)==null?void 0:x.rotation)},scale:{...e==null?void 0:e.scale,...t==null?void 0:t.scale},formatOptions:{...e==null?void 0:e.formatOptions,...t==null?void 0:t.formatOptions}}}function mFe(e,t){const n=fFe(t);return!e||e.length===0?n:n.map(r=>{const s=e.find(o=>o.idx===r.idx);return s?{...r,...s,type:s.type||r.type,yAxisId:s.yAxisId||r.yAxisId}:r})}function gFe(e,t,n,r){const s=n==null?void 0:n.yAxisConfig,o=n==null?void 0:n.secondaryYAxisConfig,i=n==null?void 0:n.dataLabelsConfig;return e.map((a,c)=>{const u=t.find(b=>b.idx===c),d={...a},f=(u==null?void 0:u.type)||"bar";d.type=f;const h=(u==null?void 0:u.fill)!==void 0&&(u==null?void 0:u.fill)!=="";if(f==="line"){if(d.borderWidth=d.borderWidth??2,d.tension=d.tension??.1,d.pointRadius=(u==null?void 0:u.pointRadius)??3,d.pointStyle=(u==null?void 0:u.pointStyle)??"circle",d.pointHoverRadius=(u==null?void 0:u.pointHoverRadius)??((u==null?void 0:u.pointRadius)??3)+2,d.borderDash=IO(u==null?void 0:u.lineStyle),h){const b=d.borderColor||d.backgroundColor;b&&typeof b=="string"&&(d.backgroundColor=WJ(b,.3)),d.fill=u.fill}d.order=0}else d.order=1;u!=null&&u.yAxisId&&(d.yAxisID=u.yAxisId);const p=(u==null?void 0:u.yAxisId)==="y2"?o:s,g=A_(i,u==null?void 0:u.dataLabels);if(g){const b=xv({card:r,preferences:n,dataLabelsConfig:g,datasetIndex:c,datasetLabel:a.label}).formatOptions;d.datalabels=T_(g,p,f==="line"?"line":"bar",b)}return d})}function bFe(e,t,n){var s,o,i,a;const r={...e,x:{...e==null?void 0:e.x,display:!0},y:{...e==null?void 0:e.y,display:!0,position:"left"}};if(t){const c=pFe(GM(),n==null?void 0:n.secondaryYAxisConfig);r.y2={...e==null?void 0:e.y2,type:"linear",display:c.enabled!==!1,position:c.position||"right",grid:{...(s=e==null?void 0:e.y2)==null?void 0:s.grid,drawOnChartArea:!1},ticks:{...(o=e==null?void 0:e.y2)==null?void 0:o.ticks,display:((i=c.labels)==null?void 0:i.enabled)!==!1},title:(a=c.name)!=null&&a.enabled?{display:!0,text:c.name.text||"",font:{size:c.name.fontSize||12,weight:c.name.fontWeight||"normal"}}:void 0},c.scale&&(c.scale.min!==void 0&&c.scale.min!=="auto"&&(r.y2.min=c.scale.min),c.scale.max!==void 0&&c.scale.max!=="auto"&&(r.y2.max=c.scale.max),c.scale.stepSize!==void 0&&c.scale.stepSize!=="auto"&&(r.y2.ticks={...r.y2.ticks,stepSize:c.scale.stepSize}))}return r}function xFe({card:e,data:t,cfg:n,customCfg:r,preferences:s}){var C,N;const{keys:o}=pr(t),i=Oy(o),a=i.length,c=mFe(s==null?void 0:s.datasetOptions,a),u=hFe(c),d=o==null?void 0:o[0],f=Qc(t,d),h=Ng(i,t,s,1,"none",d,!1,Cg(t)),p=gFe(h,c,s,e),g=Da(p,r),{options:b,plugins:x}=sd({cardType:"combo",cfg:n,preferences:s,customCfg:r,card:e}),y=bFe(b==null?void 0:b.scales,u,s),S={...b,scales:y},w=(((N=(C=e.interactionConfig)==null?void 0:C.interactions)==null?void 0:N.length)??0)>0;return M_(S,w),{type:"bar",data:{labels:f,datasets:g},options:S,plugins:x}}function yFe(e,t,n,r,s){const o=n==null?void 0:n.lineStyleConfig,i=n==null?void 0:n.yAxisConfig,a=(r==null?void 0:r.some(c=>c._forecast))??!1;return e.map((c,u)=>{const d=t.find(g=>g.idx===u),f={...c};f.type="line",f.fill=!1,f.borderWidth=f.borderWidth??2,f.tension=f.tension??.1;const h=(d==null?void 0:d.pointRadius)??(o==null?void 0:o.pointRadius)??3;f.pointRadius=h,f.pointStyle=(d==null?void 0:d.pointStyle)??(o==null?void 0:o.pointStyle)??"circle",f.pointHoverRadius=(d==null?void 0:d.pointHoverRadius)??h+2,f.borderDash=IO((d==null?void 0:d.lineStyle)??(o==null?void 0:o.lineStyle)),a&&r&&vFe(f,r,c.borderColor);const p=A_(n==null?void 0:n.dataLabelsConfig,d==null?void 0:d.dataLabels);if(p){const g=xv({card:s,preferences:n,dataLabelsConfig:p,datasetIndex:u,datasetLabel:c.label}).formatOptions;f.datalabels=T_(p,i,"line",g)}return f})}function vFe(e,t,n){const r=m.useDashboardStore.getState().theme==="dark";e.segment={borderDash:s=>{var a;const o=s.p0DataIndex;return((a=t[o])==null?void 0:a._forecast)?[2,4]:void 0},borderColor:s=>{var i;return((i=t[s.p0DataIndex])==null?void 0:i._forecast)?r?"white":"black":n}},e.pointBackgroundColor=s=>{var i;return((i=t[s.dataIndex])==null?void 0:i._forecast)?r?"white":"gray":e.borderColor},e.pointBorderColor=s=>{var i;return((i=t[s.dataIndex])==null?void 0:i._forecast)?r?"white":"gray":e.borderColor}}function wFe(e){var t,n;return{...e,x:{...e==null?void 0:e.x,display:((t=e==null?void 0:e.x)==null?void 0:t.display)??!0},y:{...e==null?void 0:e.y,display:((n=e==null?void 0:e.y)==null?void 0:n.display)??!0}}}function SFe({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var w,C;const{keys:i}=pr(t),a=Oy(i),c=(s==null?void 0:s.datasetOptions)||[],u=i==null?void 0:i[0],d=Qc(t,u),f=Ng(a,t,s,1,"none",u,!1,Cg(t)),h=yFe(f,c,s,t,e),p=Da(h,r),{options:g,plugins:b}=sd({cardType:o||"line",cfg:n,preferences:s,customCfg:r,card:e}),x=wFe(g==null?void 0:g.scales),y={...g,scales:x},S=(((C=(w=e.interactionConfig)==null?void 0:w.interactions)==null?void 0:C.length)??0)>0;return M_(y,S),{type:"line",data:{labels:d,datasets:p},options:y,plugins:b}}function CFe(e,t,n,r,s,o){const i=n==null?void 0:n.barStyleConfig,a=s==="horizontalBar"?n==null?void 0:n.xAxisConfig:n==null?void 0:n.yAxisConfig,c=(r==null?void 0:r.some(u=>u._forecast))??!1;return e.map((u,d)=>{const f=t.find(g=>g.idx===d),h={...u};h.borderRadius=(f==null?void 0:f.borderRadius)??(i==null?void 0:i.borderRadius)??0,h.borderWidth=(f==null?void 0:f.barBorderWidth)??(i==null?void 0:i.borderWidth)??0,h.barPercentage=(f==null?void 0:f.barPercentage)??(i==null?void 0:i.barPercentage)??.9,h.categoryPercentage=(f==null?void 0:f.categoryPercentage)??(i==null?void 0:i.categoryPercentage)??.8,c&&r&&NFe(h,r,u.backgroundColor);const p=A_(n==null?void 0:n.dataLabelsConfig,f==null?void 0:f.dataLabels);if(p){const g=s==="horizontalBar"?"horizontalBar":"bar",b=xv({card:o,preferences:n,dataLabelsConfig:p,datasetIndex:d,datasetLabel:u.label}).formatOptions;h.datalabels=T_(p,a,g,b)}return h})}function NFe(e,t,n){const r=n;e.backgroundColor=s=>{var i;return((i=t[s.dataIndex])==null?void 0:i._forecast)?r+"20":r}}function kFe(e,t,n=!1){var o,i;const r=t==="horizontalBar",s=t==="stackedBar";return{...e,x:{...e==null?void 0:e.x,display:((o=e==null?void 0:e.x)==null?void 0:o.display)??!0,...s&&{stacked:!n}},y:{...e==null?void 0:e.y,display:((i=e==null?void 0:e.y)==null?void 0:i.display)??!0,...s&&{stacked:!0}},...r&&{}}}function _Fe(e){return e==="horizontalBar"?"y":void 0}function BD({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var j,I,T,F;let i=t;const{keys:a}=pr(i),c=Oy(a),u=(s==null?void 0:s.datasetOptions)||[],d=a==null?void 0:a[0],f=Cg(i),h=o==="stackedBar",p=((j=e.config)==null?void 0:j.pivotByColumns)&&e.config.pivotByColumns.length>0,g=((I=e.config)==null?void 0:I.groupByColumns)&&e.config.groupByColumns.length>0;h&&!f&&(!p||!g)&&(i=gv({dataArray:i,groupKey:a[0],pivotKey:a[1],valueKey:a[2],sortChart:s==null?void 0:s.sortChart}));const b=Qc(i,d),x=Ng(h?Oy(pr(i).keys):c,i,s,1,"none",d,h,f),y=CFe(x,u,s,i,o,e),S=Da(y,r),{options:w,plugins:C}=sd({cardType:o||"bar",cfg:n,preferences:s,customCfg:r,card:e}),N=o||"bar",k=kFe(w==null?void 0:w.scales,N,f),_=_Fe(N),E={...w,scales:k,..._&&{indexAxis:_}},D=(((F=(T=e.interactionConfig)==null?void 0:T.interactions)==null?void 0:F.length)??0)>0;return M_(E,D),{type:"bar",data:{labels:b,datasets:S},options:E,plugins:C}}function Ag({card:e,data:t,cardType:n="bar",cfg:r,customCfg:s,provider:o="chartjs",userSettings:i,preferences:a,topoJson:c,queryConfig:u,isDevMode:d}){var x,y,S,w,C,N,k,_;const f=e.config,h=d??!!e.sql;let p=t;const g=f&&f.pivotByColumns&&f.pivotByColumns.length>0,b=f&&f.groupByColumns&&f.groupByColumns.length>0;if(g&&b&&(p=w_e(t,(f==null?void 0:f.metricColumns)||[])),n==="map"){if(!c)return null;const E=(x=a==null?void 0:a.mapVisualOptions)==null?void 0:x.objectKey;if(!E)return null;const D=IAe(c,(y=c==null?void 0:c.objects)==null?void 0:y[E]).features;if(!D)return null;const j={plugins:{datalabels:{display:!1}},scales:{x:{display:!1,grid:{display:!1}},y:{display:!1,grid:{display:!1}},projection:{axis:"x",projection:((S=a==null?void 0:a.mapVisualOptions)==null?void 0:S.projection)||"mercator",projectionScale:((w=a==null?void 0:a.mapVisualOptions)==null?void 0:w.projectionScale)||1,projectionOffset:((C=a==null?void 0:a.mapVisualOptions)==null?void 0:C.projectionOffset)||[0,0]},color:{axis:"x",interpolate:((N=a==null?void 0:a.mapVisualOptions)==null?void 0:N.colorScale)||"blues",quantize:5,legend:{position:"bottom-right",align:"right"}}}},{keys:I}=pr(p),T=D.map(U=>{var q;const Y=I==null?void 0:I[0],O=I==null?void 0:I[1],K=(q=p.find(M=>(M==null?void 0:M[Y])===U.properties.NAME||(M==null?void 0:M[Y])===U.properties.name))==null?void 0:q[O];return{feature:U,value:K}}),P=Da([{label:E,data:T,borderColor:"lightgray"}],s),R={type:"choropleth",data:{labels:D.map(U=>U.properties.NAME||U.properties.name),datasets:P},options:j},{options:B}=sd({cfg:R,preferences:a,customCfg:s,cardType:n});return{...R,options:B}}if(n==="bar")return BD({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="horizontalBar")return BD({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="funnel")return oRe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="tornado"||n==="pyramid")return lRe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="treemap")return cRe({data:p,cfg:r,customCfg:s,preferences:a,card:e});if(n==="heatmap")return ZRe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="bullet")return IRe({data:p,cfg:r,customCfg:s,preferences:a,card:e});if(n==="stackedBar")return BD({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="stackedLine"){const E=Cg(p),D=$Ae(r,n,E),{keys:j}=pr(p);return!E&&(!g||!b)&&(p=gv({dataArray:p,groupKey:j[0],pivotKey:j[1],valueKey:j[2],sortChart:a==null?void 0:a.sortChart})),jD({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}if(n==="line")return SFe({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="area"||n==="stackedArea")return jRe({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="combo")return xFe({card:e,data:p,cfg:r,customCfg:s,preferences:a});if(n==="range")return iRe({data:p,cfg:r,customCfg:s,preferences:a,card:e});if(n==="pie"||n==="doughnut"||n==="polarArea"){const E=zAe(n,r),{keys:D}=pr(p),j=D.slice(0,1),I=D.slice(1),T=PZ(I,p,a,j==null?void 0:j[0]),F=Da(T,s),{plugins:P,options:R}=kd((a==null?void 0:a.customVisualCode)||""),B=j[0],z=Qc(p,B),U=es((E==null?void 0:E.options)||{},(s==null?void 0:s.options)||{}),Y=es(U,(a==null?void 0:a.chartOptions)||{}),O=(A,W=0,X)=>{const Z=zy({card:e,datasetIndex:W,datasetLabel:X}),J=v_({preferences:a,metric:Z}).formatOptions;return By({value:A,formatOptions:J,preferences:a})},K=(A,W=0,X)=>{const Z=zy({card:e,datasetIndex:W,datasetLabel:X});return By({value:A,formatOptions:x_(Z),preferences:a})},q=(A,W=0,X)=>{const Z=xv({card:e,preferences:a,dataLabelsConfig:a==null?void 0:a.dataLabelsConfig,datasetIndex:W,datasetLabel:X}),J=Z.formatOptions;return _g(Z)?String(A):J!=null&&J.type&&J.type!=="auto"?Fn(A,J.type,J):O(A,W,X)},M={...Y,plugins:{...Y.plugins,datalabels:{...(k=Y.plugins)==null?void 0:k.datalabels,formatter:(A,W)=>{var X;return q(Number(A),(W==null?void 0:W.datasetIndex)??0,(X=W==null?void 0:W.dataset)==null?void 0:X.label)}},tooltip:{...(_=Y.plugins)==null?void 0:_.tooltip,callbacks:{label:function(A){var fe;A.dataset.label;const X=A.dataset.data.reduce((de,Se)=>de+Se,0),Z=A.parsed,J=O(Number(Z),A.datasetIndex,(fe=A.dataset)==null?void 0:fe.label),re=(Z/X*100).toFixed(2);return J+` (${re}%)`},footer:function(A){var X,Z,J,re;return(((Z=(X=e==null?void 0:e.interactionConfig)==null?void 0:X.drillHierarchies)==null?void 0:Z.length)??0)>0||(((re=(J=e==null?void 0:e.interactionConfig)==null?void 0:J.interactions)==null?void 0:re.some(fe=>fe.mode==="drillDown"||fe.mode==="drillToDetail"||fe.mode==="drillThrough"||fe.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},G=es(Y,M),{options:L}=sd({cfg:{options:G},preferences:a,customCfg:s,cardType:n,card:e}),$=es(L,R);return{type:n,data:{labels:z,datasets:F},options:$,plugins:[n==="doughnut"?{id:"doughnutLabel",beforeDatasetsDraw:function(A,W,X){var xe,ke;const{ctx:Z,data:J}=A;Z.save();const re=A.getDatasetMeta(0).data[0].x,fe=A.getDatasetMeta(0).data[0].y,de=m.getContrastColor(m.getCanvasBackgroundColor(A.canvas)),Se=window.getComputedStyle(Z.canvas).fontFamily;Z.font=`1em ${Se}`,Z.fontWeight="bolder",Z.fillStyle=de,Z.textAlign="center",Z.textBaseline="middle";const ue=J.datasets[0].data.reduce((se,be)=>se+be,0),ve=K(Number(ue),0,(ke=(xe=J.datasets)==null?void 0:xe[0])==null?void 0:ke.label);Z.fillText(ve,re,fe)}}:"",...P]}}if(n==="radar"){const E=BAe(r);return jD({card:e,data:p,cfg:E,customCfg:s,cardType:n,preferences:a})}return n==="bubble"||n==="scatter"?UAe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,cardConfig:f,isDevMode:h,card:e}):jD({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a})}function jFe({chart:e,elementIndex:t,datasetIndex:n,cardType:r,cfg:s,apply:o}){const i=m.useDashboardStore.getState().theme;if(!s)return;const a=i==="dark"?"rgb(238,238,238,0.2)":"rgb(238,238,238,0.8)";["bar","line","horizontalBar","bubble","scatter"].includes(r)&&DFe(e,t,s,o,a),["pie","doughnut","polarArea","funnel"].includes(r)&&IFe(e,t,s,o,a),["stackedBar","pyramid"].includes(r)&&EFe({chart:e,elementIndex:t,datasetIndex:n,cfg:s,apply:o,blurColor:a})}function EFe(e){var a,c,u,d;const{chart:t,elementIndex:n,datasetIndex:r,cfg:s,apply:o,blurColor:i}=e;o?(c=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null||c.forEach((f,h)=>{var p,g;typeof f.backgroundColor=="string"&&(f.backgroundColor=new Array(f.data.length).fill(f.backgroundColor),f.borderColor=new Array(f.data.length).fill(f.borderColor)),f.backgroundColor=(p=f==null?void 0:f.backgroundColor)==null?void 0:p.map((b,x)=>x===n&&h===r?b:i),f.borderColor=(g=f==null?void 0:f.borderColor)==null?void 0:g.map((b,x)=>x===n&&h===r?b:i)}):(d=(u=t==null?void 0:t.data)==null?void 0:u.datasets)==null||d.forEach((f,h)=>{var p,g,b,x,y,S;f.backgroundColor=new Array(f.data.length).fill((b=(g=(p=s==null?void 0:s.data)==null?void 0:p.datasets)==null?void 0:g[h])==null?void 0:b.backgroundColor),f.borderColor=new Array(f.data.length).fill((S=(y=(x=s==null?void 0:s.data)==null?void 0:x.datasets)==null?void 0:y[h])==null?void 0:S.borderColor)}),t==null||t.update()}function DFe(e,t,n,r,s){var o,i,a,c;r?(i=(o=e==null?void 0:e.data)==null?void 0:o.datasets)==null||i.forEach(u=>{var d,f;typeof u.backgroundColor=="string"&&(u.backgroundColor=new Array(u.data.length).fill(u.backgroundColor),u.borderColor=new Array(u.data.length).fill(u.borderColor)),u.backgroundColor=(d=u==null?void 0:u.backgroundColor)==null?void 0:d.map((h,p)=>p===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,p)=>p===t?h:s)}):(c=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||c.forEach((u,d)=>{var f,h,p,g,b,x;u.backgroundColor=new Array(u.data.length).fill((p=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:p.backgroundColor),u.borderColor=new Array(u.data.length).fill((x=(b=(g=n==null?void 0:n.data)==null?void 0:g.datasets)==null?void 0:b[d])==null?void 0:x.borderColor)}),e==null||e.update()}function IFe(e,t,n,r,s){var o,i,a,c;r?(i=(o=e==null?void 0:e.data)==null?void 0:o.datasets)==null||i.forEach(u=>{var d,f;u.backgroundColor=(d=u==null?void 0:u.backgroundColor)==null?void 0:d.map((h,p)=>p===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,p)=>p===t?h:s)}):(c=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||c.forEach((u,d)=>{var f,h,p,g,b,x,y,S;typeof u.backgroundColor=="string"&&(u.backgroundColor=(p=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:p.backgroundColor,u.borderColor=(x=(b=(g=n==null?void 0:n.data)==null?void 0:g.datasets)==null?void 0:b[d])==null?void 0:x.borderColor),u.backgroundColor=(y=u==null?void 0:u.backgroundColor)==null?void 0:y.map((w,C)=>{var N;return(N=n.data.datasets[d].backgroundColor)==null?void 0:N[C]}),u.borderColor=(S=u==null?void 0:u.borderColor)==null?void 0:S.map((w,C)=>{var N;return(N=n.data.datasets[d].borderColor)==null?void 0:N[C]})}),e==null||e.update()}function TFe({card:e,data:t,datasetIndex:n,clickIndex:r,value:s}){var o,i,a,c,u,d,f;try{if(!t)return;const{keys:h}=pr(t);if(e.type==="map"){const p=h[0],g=((i=(o=s==null?void 0:s.feature)==null?void 0:o.properties)==null?void 0:i.name)||((c=(a=s==null?void 0:s.feature)==null?void 0:a.properties)==null?void 0:c.NAME);return[{columnName:p,columnValue:g}]}if(["bar","horizontalBar","line","pie","doughnut","radar","polarArea","funnel"].includes(e.type)){const p=h[0],g=h.slice(1),b=(u=t[r])==null?void 0:u[p];return[{columnName:p,columnValue:b,metric:g[n],value:s}]}if(["stackedBar","pyramid"].includes(e.type)){const p=gv({dataArray:t,groupKey:h[0],pivotKey:h[1],valueKey:h[2]}),g=h[0],b=(d=p[r])==null?void 0:d[g],x=h[1],{keys:y}=pr(p),w=y.slice(1)[n];return[{columnName:g,columnValue:b,metric:h[2],value:s},{columnName:x,columnValue:w,metric:h[2],value:s}]}if(e.type==="bubble"||e.type==="scatter"){const p=h[0],g=(f=t[n])==null?void 0:f[p];return console.log(s,"bubble"),[{columnName:p,columnValue:g,metric1:h[1],value1:s.x,metric2:h[2],value2:s.y,metric3:h==null?void 0:h[3],value3:s==null?void 0:s.r}]}}catch(h){console.error("Error in getAdhocFilter",h)}}function kv(e){var a,c,u,d,f,h;const t=(((c=(a=e.preferences)==null?void 0:a.mapVisualOptions)==null?void 0:c.topoJsonUrl)==="custom"?(d=(u=e.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:d.customTopoJsonUrl:(h=(f=e.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:h.topoJsonUrl)||"",n=!!t&&e.type==="map",{data:r,isLoading:s,isFetching:o,isError:i}=On({queryKey:["topojson",t],queryFn:()=>fetch(t).then(p=>p.json()),enabled:n,staleTime:1/0});return{data:r,isLoading:s,isFetching:o,isError:i}}function MFe(e,t,n,r=s=>s){const s=r(e)||e,o=r(t)||t;if(s===o)return!0;const i=new Map;for(const u of n){const d=r(u.source.name)||u.source.name,f=r(u.target.name)||u.target.name;i.has(d)||i.set(d,new Set),i.get(d).add(f),i.has(f)||i.set(f,new Set),i.get(f).add(d)}const a=new Set,c=[s];for(a.add(s);c.length>0;){const u=c.shift(),d=i.get(u);if(d)for(const f of d){if(f===o)return!0;a.has(f)||(a.add(f),c.push(f))}}return!1}function sy(e){return(e==null?void 0:e.trim())||null}function AFe(e){const t=new Set,n=sy(e.table),r=sy(e.schema),s=sy(e.catalog);return n&&(t.add(n),r&&t.add(`${r}.${n}`),s&&t.add(`${s}.${n}`),s&&r&&t.add(`${s}.${r}.${n}`)),Array.from(t)}function RFe(e){const t=new Map;for(const r of e||[]){const s=sy(r.name);if(!s)continue;const o=new Set([s,...AFe(r)]);for(const i of o)t.has(i)||t.set(i,new Set),t.get(i).add(s)}const n=new Map;for(const[r,s]of t.entries())s.size===1&&n.set(r,Array.from(s)[0]);return n}function MO(e,t){var C,N,k,_,E,D,j,I;const{joinabilityMap:n,selectedFields:r,cardConfig:s,autoJoinMetadata:o,baseEntityName:i,datasetAliases:a}=t,c=RFe(a),u=T=>{const F=sy(T);if(F)return c.get(F)||F},d=u(e.entityName),f=r.some(T=>T.id&&e.id&&T.id===e.id?!0:u(T.entityName)===d&&T.name===e.name);if(!n)return{state:"draggable",isSelected:f};if(e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||Cr.isCalculatedField(e))return{state:"draggable",isSelected:f};const h=r.filter(T=>T.entityName!==Cr.CALCULATED_FIELD_ENTITY_MARKER&&!Cr.isCalculatedField(T));if(h.length===0)return{state:"draggable",tooltip:"Select to establish base dataset"};let p;const g=(N=(C=s==null?void 0:s.joinPlan)==null?void 0:C.baseEntity)==null?void 0:N.name,b=(_=(k=o==null?void 0:o.resolvedJoinPlan)==null?void 0:k.baseEntity)==null?void 0:_.name;if(g?p=g:b?p=b:i?p=i:p=[...new Set(h.map(F=>u(F.entityName)))].filter(F=>!!F)[0],p=u(p)||p,d===p)return{state:"base",tooltip:f?"Field already in query (base dataset)":"From base dataset",isSelected:f};const x=n[p];if(!x)return{state:"unreachable",tooltip:"No relationships defined for base dataset"};const y=x.canJoinTo.map(T=>u(T)).filter(Boolean);if(d&&y.includes(d))return{state:"draggable",tooltip:`Direct join from ${p}`,joinPath:[p,d],isSelected:f};const S=d&&((E=x.indirectJoins)==null?void 0:E[d])||((D=x.indirectJoins)==null?void 0:D[e.entityName]);if(S&&S.length>0){const T=[p,...S.map(F=>u(F)),d].filter(Boolean);return{state:"indirect",joinPath:T,tooltip:`Multi-hop join: ${T.join(" → ")}`,isSelected:f}}const w=d&&n[d]||n[e.entityName];if(w){if(w.canJoinTo.map(P=>u(P)).filter(Boolean).includes(p))return{state:"draggable",tooltip:`Direct join to ${p}`,joinPath:[d||e.entityName,p],isSelected:f};const F=(j=w.indirectJoins)==null?void 0:j[p];if(F&&F.length>0){const P=[d||e.entityName,...F.map(R=>u(R)),p].filter(Boolean);return{state:"indirect",joinPath:P,tooltip:`Multi-hop join: ${P.join(" → ")}`,isSelected:f}}}return(I=s==null?void 0:s.joinPlan)!=null&&I.joins&&s.joinPlan.joins.length>0&&MFe(p,e.entityName,s.joinPlan.joins,u)?{state:"draggable",tooltip:"Manual join configured",isSelected:f}:{state:"unreachable",tooltip:`Cannot join ${d||e.entityName} to ${p}`,isSelected:f}}function JJ(e,t,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:e===t||e===m.getQualifiedEntityName(n.baseEntity)||t===m.getQualifiedEntityName(n.baseEntity)?!0:n.joins.some(s=>{const o=m.getQualifiedEntityName(s.source),i=m.getQualifiedEntityName(s.target);return o===e&&i===t||o===t&&i===e})}function FFe(e,t,n){var u;const{joinPlan:r,joinabilityMap:s,semanticDomainId:o,datasetAliases:i}=n,a=t.filter(d=>d.entityName!==Cr.CALCULATED_FIELD_ENTITY_MARKER&&d.qualifiedEntityName!==m.CALCULATED_FIELDS_GROUP_NAME);if(a.length===0)return{isValid:!0};const c=a[0].qualifiedEntityName;if(!c)return{isValid:!0};if(c===e.qualifiedEntityName)return{isValid:!0};if(e.qualifiedEntityName){if(o&&s)return MO(e,{joinabilityMap:s,selectedFields:t,baseEntityName:(u=r==null?void 0:r.baseEntity)==null?void 0:u.name,datasetAliases:i}).state==="unreachable"?{isValid:!1,showError:!0}:{isValid:!0};if(!r)return{isValid:!1,showError:!0};if(!JJ(c,e.qualifiedEntityName,r))return{isValid:!1,showError:!0}}return{isValid:!0}}function eee(){ut.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function tee(e,t){return t.some(n=>{if(!(n.name===e.name&&n.qualifiedEntityName===e.qualifiedEntityName))return!1;if((e.role==="metric"||!e.role)&&n.role==="metric"){const s=e,o=n;if(s.aggregate!==o.aggregate||s.expression!==o.expression)return!1;if(s.parameters||o.parameters){const i=s.parameters||{},a=o.parameters||{},c=JSON.stringify(i),u=JSON.stringify(a);if(c!==u)return!1}return!1}return!0})}function PFe(e){if(e.role!=="metric")return e.label||e.name;const t=e,n=e.label||e.name;if(!t.parameters||!t.parameters.filters)return n;const r=t.parameters.filters;return typeof r=="string"?`${n} (${r})`:typeof r=="object"?(JSON.stringify(r),`${n} (Filtered)`):n}function OFe(e,t,n){const r=e.label||e.name,s=t.filter(o=>o.name===e.name&&o.qualifiedEntityName===e.qualifiedEntityName&&(o.role==="metric"||n==="metrics")).length;return s===0?r:`${r} (${s+1})`}const LFe=["SUM","COUNT","COUNTIF","AVG","MIN","MAX","MEDIAN","MODE","DISTINCT","STDDEV","STDDEV_POP","STDDEV_SAMP","VARIANCE","VAR_POP","VAR_SAMP","ANY_VALUE","BOOL_AND","BOOL_OR","BIT_AND","BIT_OR","BIT_XOR","EVERY","STRING_AGG","ARRAY_AGG","JSON_AGG","JSONB_AGG","OBJECT_AGG","MAP_AGG","LISTAGG","GROUP_CONCAT","COLLECT_LIST","COLLECT_SET","APPROX_COUNT_DISTINCT","APPROX_DISTINCT","APPROX_QUANTILES","APPROX_TOP_COUNT","APPROX_TOP_SUM","COUNT_DISTINCT","NDV","CORR","COVAR_POP","COVAR_SAMP","FIRST","LAST"],$Fe=new Set(LFe),zFe=/(?:_AGG$|^APPROX_COUNT_DISTINCT$|^APPROX_DISTINCT$|^COUNT_DISTINCT$|^HLL_(?:COUNT|ESTIMATE)$|^REGR_[A-Z_]+$)/;function BFe(e){const t=e.toUpperCase();return $Fe.has(t)?!0:zFe.test(t)}function nee(e){const t=/\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/g;let n;for(;(n=t.exec(e))!==null;){const r=n[1];if(r&&BFe(r))return!0}return!1}function AO(e){return m.getDataType(e||"")==="number"?"SUM":"COUNT"}const VFe="day",HFe="YYYY-MM-DD";function ree(e){return m.getDataType(e.dataType)!=="date"?e:{...e,granularity:e.granularity??VFe,dateFormat:e.dateFormat??HFe}}const SB="calculated_fields";function UFe(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function WFe(e){return e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName==="SEMAPHOR_CALCULATED_FIELD"||e.entityName===SB||e.qualifiedEntityName===SB||UFe(e.id)}function see(e,t){return`${e}-${t.qualifiedEntityName}-${t.name}-${Date.now()}`}function oee(e,t){const n=m.toTitleCase(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function qFe(e,t,n){const r=m.getDataType(e.dataType);return n==="detailTable"?"detailColumns":n==="kpi"?r==="date"?"groupBy":"metrics":t.length===0||r==="number"?"metrics":r==="date"||r==="string"||r==="boolean"?"groupBy":"metrics"}function iee(e,t,n=[]){const r=see(t,e),s=m.getDataType(e.dataType),o=s==="date",i=e.role==="metric"&&"expression"in e&&!!e.expression,a=e.role==="groupby"&&"expression"in e&&!!e.expression,c={id:r,name:e.name,dataType:e.dataType,label:m.toLabel(e.name),format:e.format,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityId:e.entityId,entityName:e.entityName,entityType:e.entityType};if(t==="metrics"){if(i){const h=e,p=e.expression||"";if(!WFe(h)){const y=!h.aggregate&&!nee(p),S=AO(s);return{...h,id:r,label:e.label||e.name,role:"metric",...y?{aggregate:S}:{}}}const{aggregate:b,...x}=h;return{...x,id:r,label:e.label||e.name,role:"metric"}}const u=s==="number"?"SUM":"COUNT",d=oee(e.label,u),f=OFe({...c,label:d},n,t);return{...c,role:"metric",label:f,aggregate:u}}if(t==="groupBy")return a?ree({...e,id:r,label:e.label||e.name,role:"groupby"}):{...c,role:"groupby",...o&&{granularity:"month",dateFormat:"YYYY-MM"}};if(t==="pivotBy")return{...c,role:"pivotby"};if(t==="detailColumns"){if(i){const{aggregate:u,parameters:d,aliasTemplate:f,valueAliases:h,...p}=e;return{...p,id:r,label:e.label||e.name,role:"detail"}}return a?{...e,id:r,label:e.label||e.name,role:"detail"}:{...c,role:"detail"}}return t==="sortBy"?{...c,role:"sortby",label:e.label,direction:"asc"}:null}function YFe(e){var o,i,a,c;const t=(o=e.config)==null?void 0:o.metricColumns,n=(i=e.config)==null?void 0:i.groupByColumns,r=(a=e.config)==null?void 0:a.pivotByColumns,s=(c=e.config)==null?void 0:c.detailColumns;return!!(t&&(t==null?void 0:t.length)>0||n&&(n==null?void 0:n.length)>0||r&&(r==null?void 0:r.length)>0||s&&(s==null?void 0:s.length)>0)}function GFe(e){var i,a;const[t]=v.useState({id:"",title:"",type:"bar"}),{getCard:n}=m.useDashboardActions(),r=n(e),s=_v(r||t),o={...r,data:((i=s==null?void 0:s.data)==null?void 0:i.records)||[]};return{...s,data:((a=s==null?void 0:s.data)==null?void 0:a.records)||[],card:o}}function _v(e){var R;const{onChartElementClicked:t}=Ct(),[n,r]=v.useState(0),s=m.useDashboardStore(B=>B.themeStyle),o=m.useDashboardStore(B=>B.filteringCards),i=m.useDashboardStore(B=>B.selectedSheetId),a=m.useDashboardStore(B=>B.selectedLensId),c=m.useDashboardStore(B=>B.filterValues),u=v.useRef(c),d=(R=e==null?void 0:e.preferences)==null?void 0:R.onClickFilter,{addFilteringCard:f,addOrUpdateFilterValues:h,removeFilterValues:p,removeFilteringCard:g}=m.useDashboardActions(),{data:b,fetchStatus:x,isLoading:y,isFetching:S,isError:w,isPending:C,queryKey:N,isFilteringCard:k,isSingleCardFrame:_,pagination:E,comparisonMetadata:D,resolvedPrimaryDateField:j}=$c(e),{data:I}=kv(e);let T;T=v.useMemo(()=>{if(!(!(b!=null&&b.records)||!(b!=null&&b.records.length)))return Ag({card:e,data:b==null?void 0:b.records,cardType:e.type,queryConfig:e.queryConfig,customCfg:e.customCfg,preferences:e.preferences,topoJson:I})},[b==null?void 0:b.records,e.type,e.queryConfig,e.customCfg,e.config,e.preferences,I,s]);const F=v.useRef({filteringCards:o});v.useEffect(()=>{e.connectionId&&!k&&(u.current=c)},[c,a,e.connectionId,k]),v.useEffect(()=>{var z;k&&(F.current.filteringCards=[...o||[]]),!k&&((z=F.current.filteringCards)==null?void 0:z.find(U=>U.id===e.id))&&_&&r(U=>U+1)},[k,_,e.id,o]);function P(B,z,U,Y){var q;if(YFe(e))return;let O=!1;if(!(b!=null&&b.records))return;const K=TFe({card:e,data:b==null?void 0:b.records,datasetIndex:z,clickIndex:U,value:Y});if(console.log("fieldValues",K),t==null||t(e,K),!!(((q=e==null?void 0:e.preferences)==null?void 0:q.onClickFilter)??[]).length){if(k){const M=e.id;p(M),g(e)}else{if(O=!0,!K)return;const M=[];K.forEach((G,L)=>{const $=d==null?void 0:d.find(H=>H.columnIndex===L);if(!$)return;const V={filterId:e.id+"-"+G.columnName+"-"+i,connectionId:e==null?void 0:e.connectionId,tableName:e.lastSelectedTable,name:G.columnName,expression:$.expression,valueType:m.resolveDataType(K[$.columnIndex].columnValue),operation:"=",values:[K[$.columnIndex].columnValue]};M.push(V)}),h(M),f(e)}jFe({chart:B,elementIndex:U,datasetIndex:z,cardType:e.type,cfg:T,apply:O})}}return{isPending:C,isError:w,isLoading:y,isFetching:S,fetchStatus:x,data:b,visualKey:n,handleDatapointClick:P,cfg:T,queryKey:N,pagination:E,comparisonMetadata:D,resolvedPrimaryDateField:j}}function VD(e,t){if(e==null)return"-";if(!t)return e.toString();const n=t.locale?new Intl.NumberFormat(t.locale).format(e):e.toFixed(t.decimalPlaces||0);return`${t.prefix||""}${n}${t.suffix||""}`}function CB(e,t){return t.map(n=>{const r=n.alias||n.name,s=e[r];return typeof s=="object"&&s!==null&&"label"in s?String(s.label??""):String(s??"")}).join(" | ")}function aee(e,t=0,n=[],r){if(!(e!=null&&e.length)||t>=e[0].fieldValues.length)return[];const s=c=>n.every((u,d)=>c.fieldValues[d]===u),o=e.filter(s),i=[],a=new Set;for(const c of o){const u=c.fieldValues[t];if(a.has(u))continue;a.add(u);const d=[...n,u],f=d.join(" | ");if(r&&!r.has(f))continue;if(t===c.fieldValues.length-1)i.push({name:u,level:t,rowKey:c.rowKey});else{const p=aee(o.filter(g=>g.fieldValues[t]===u),t+1,d,r);p.length>0&&i.push({name:u,level:t,children:p})}}return i}function KFe(e,t={},n){const r=e.records,s=e.pivotSchema||[],o=e.columnSubtotalMeta||[],i=e.groupByColumns||[],a=e.columnMetadata,c=s.filter(T=>T.isPivotColumn),u=s.filter(T=>T.isMetricColumn),d=()=>({rowHeaders:[],columnHeaders:[],cells:{},columnGroups:[],rowGroups:[],columnDisplayNames:{},groupByColumns:i,columnSubtotalMeta:o,columnMetadata:a});if(c.length===0&&u.length===0)return console.warn("No pivot or metric fields found in pivotSchema:",s),d();const{columnGroups:f,columnHeaders:h,columnDisplayNames:p}=ZFe(s,o,n==null?void 0:n.config);if(!r.length)return d();const g=r.filter(T=>T.isGrandTotal),b=r.filter(T=>T.isSubtotal&&!T.isGrandTotal),x=r.filter(T=>!T.isSubtotal&&!T.isGrandTotal),y=[],S=new Set;x.forEach(T=>{const F=CB(T,i),P=i.map(R=>{const B=R.alias||R.name,z=T[B];return typeof z=="object"&&z!==null&&"label"in z?String(z.label??""):String(z??"")});F&&!S.has(F)&&(S.add(F),y.push({rowKey:F,fieldValues:P}))}),y.sort((T,F)=>{const P=Math.min(T.fieldValues.length,F.fieldValues.length);for(let R=0;R<P;R++){const B=(T.fieldValues[R]||"").localeCompare(F.fieldValues[R]||"");if(B!==0)return B}return T.fieldValues.length-F.fieldValues.length});const w=[],C=[],N=new Set;for(let T=0;T<y.length;T++){const F=y[T];w.push(F),C.push(F.rowKey);const P=y[T+1];for(let R=i.length-1;R>=0;R--){const B=i[R];B.alias||B.name;let z=!1;if(!P)z=!0;else{z=F.fieldValues[R]!==P.fieldValues[R];for(let U=0;U<R&&!z;U++)F.fieldValues[U]!==P.fieldValues[U]&&(z=!0)}z&&b.filter(Y=>{const O=B.alias||B.name;if(Y.subtotalLevel!==O&&Y.subtotalLevel!==B.id)return!1;if(Y.subtotalContext){if(Y.subtotalContext.value!==F.fieldValues[R])return!1;const K=Y.subtotalContext.groupByValues||{};for(let q=0;q<R;q++){const M=i[q],G=M.alias||M.name;if(K[G]!==F.fieldValues[q])return!1}return!0}for(let K=0;K<R;K++){const q=i[K],M=q.alias||q.name,G=Y[M],L=F.fieldValues[K],$=typeof G=="object"&&(G!=null&&G.label)?G.label:String(G??"");if(L!==$)return!1}return!0}).forEach(Y=>{var G;const O=JSON.stringify({level:Y.subtotalLevel,context:Y.subtotalContext});if(N.has(O))return;const K=[...F.fieldValues],q=`${F.fieldValues[R]} Total`;K[R]=q;for(let L=R+1;L<K.length;L++)K[L]="";const M=K.join(" | ");w.push({rowKey:M,fieldValues:K,isSubtotal:!0,subtotalLevel:Y.subtotalLevel,aggregateDisplayLabel:Y.aggregate,aggregateFunction:(G=Y.aggregate)==null?void 0:G.toUpperCase(),subtotalContext:Y.subtotalContext}),C.push(M),N.add(O)})}}const k=w,_=C,E=new Set(k.map(T=>T.rowKey)),D=aee(k,0,[],E),j={};_.forEach(T=>{j[T]={},h.forEach(F=>{j[T][F]={value:null,metricId:"",formattedValue:"-"}})}),x.forEach(T=>{const F=CB(T,i);j[F]&&h.forEach(P=>{if(!(P in T))return;const R=T[P],B=s.find(z=>z.isMetricColumn&&P.startsWith(z.alias));j[F][P]={value:R,metricId:(B==null?void 0:B.metricId)||"",formattedValue:VD(R,t.numberFormat)}})}),b.forEach(T=>{const F=k.find(P=>P.isSubtotal&&P.subtotalLevel===T.subtotalLevel&&JSON.stringify(P.subtotalContext)===JSON.stringify(T.subtotalContext));if(F){const P=F.rowKey;j[P]||(j[P]={}),h.forEach(R=>{if(!(R in T))return;const B=T[R],z=s.find(U=>U.isMetricColumn&&R.startsWith(U.alias));j[P][R]={value:B,metricId:(z==null?void 0:z.metricId)||"",formattedValue:VD(B,t.numberFormat)}})}});const I=[];return g.forEach(T=>{const F={};h.forEach(U=>{if(U in T){const Y=T[U];F[U]={value:Y,metricId:"",formattedValue:VD(Y,t.numberFormat)}}});const P=T.aggregate||"Total";let R="SUM";const B=P.toUpperCase();["SUM","AVG","COUNT","MIN","MAX","MEDIAN"].includes(B)&&(R=B);const z=P.charAt(0).toUpperCase()+P.slice(1).toLowerCase();I.push({aggregateDisplayLabel:z,aggregateFunction:R,data:F})}),{rowHeaders:_,columnHeaders:h,cells:j,columnGroups:f,rowGroups:D,columnDisplayNames:p,groupByColumns:i,columnSubtotalMeta:o,columnMetadata:a,grandTotalRows:I,rowData:k}}function ZFe(e,t,n){const r=e.filter(p=>p.isPivotColumn),s=((n==null?void 0:n.pivotByColumns)||[]).map(p=>p.id),o=new Map;e.filter(p=>p.isMetricColumn).forEach(p=>{o.has(p.alias)||o.set(p.alias,p)});const i=Array.from(o.values());function a(p){return p.displayLabel||p.metricLabel||p.metricName||p.alias}function c(p,g){var b,x;return((x=(b=n==null?void 0:n.columnAggregates)==null?void 0:b.find(y=>y.function===p&&y.pivotLevel===g))==null?void 0:x.label)||p}function u(p,g,b){return p.subtotalScope==="grand-total"||p.pivotFieldId&&p.pivotFieldId!==g?!1:Array.isArray(p.pivotPath)&&p.pivotPath.length>0?p.pivotPath.length!==b.length?!1:p.pivotPath.every((x,y)=>String(x??"")===String(b[y]??"")):p.subtotalLevel===b[b.length-1]}function d(p,g=[]){if(p>=r.length){const y=[],S=[],w={};return i.forEach(C=>{const N=[C.alias,...g].join("_"),k=a(C);y.push({name:k,level:p,colspan:1,columnKey:N}),S.push(N),w[N]=k}),{groups:y,leafKeys:S,displayNames:w}}const b=r[p],x={groups:[],leafKeys:[],displayNames:{}};return b.pivotValues.forEach(y=>{const S=[...g,y],w=d(p+1,S),C=s[p];t.filter(k=>!!C&&u(k,C,S)).forEach(k=>{var D;const _=(D=k.aggregate)==null?void 0:D.toUpperCase(),E=c(_,k.pivotFieldId||C);w.groups.push({name:E,level:p+1,colspan:1,columnKey:k.columnName}),w.leafKeys.push(k.columnName),w.displayNames[k.columnName]=E}),x.groups.push({name:y,level:p,colspan:w.groups.reduce((k,_)=>k+(_.colspan||1),0),children:w.groups}),x.leafKeys.push(...w.leafKeys),Object.assign(x.displayNames,w.displayNames)}),x}const f=d(0),h=t.filter(p=>p.subtotalScope==="grand-total"||p.subtotalLevel==="grandTotal"||p.subtotalLevel==="ALL");return h.length>0&&h.forEach(p=>{var x;const g=(x=p.aggregate)==null?void 0:x.toUpperCase(),b=c(g,"ALL");f.groups.push({name:b,level:0,colspan:1,columnKey:p.columnName}),f.leafKeys.push(p.columnName),f.displayNames[p.columnName]=b}),{columnGroups:f.groups,columnHeaders:f.leafKeys,columnDisplayNames:f.displayNames}}function XFe({data:e,card:t}){var o;if(!t.config)throw new Error("Card configuration is required for pivot table");const n=e.records.some(i=>i.isGrandTotal),r=((o=t.config)==null?void 0:o.rowAggregates)&&t.config.rowAggregates.length>0,s={showRowTotals:!1,showColumnTotals:n||r,showGrandTotal:!1};return{type:"pivotTable",data:KFe(e,s,t),config:t.config,options:s,pivotSchema:e.pivotSchema}}function Gh(e,t){return v.useMemo(()=>!e||e.type!=="pivotTable"||!t||!Array.isArray(t.records)||t.records.length===0?null:XFe({card:e,data:{records:t.records||[],columnSubtotalMeta:t.columnSubtotalMeta,subtotalColumns:t.subtotalColumns,pivotSchema:t.pivotSchema||[],groupByColumns:t.groupByColumns}}),[e,t])}function lee(e){var y;const t=m.useDashboardStore(S=>S.dashboard),n=m.useDashboardStore(S=>S.dashboard.filters),r=m.useDashboardStore(S=>S.filterValues),s=m.useDashboardStore(S=>S.selectedSheetId),o=m.useDashboardStore(S=>S.dashboardInputValues),i=m.useDashboardStore(S=>S.dashboardInputValuesAreAuthoritative),a=m.useDashboardStore(S=>S.controlValues),c=m.useDashboardStore(S=>S.inlineFilterValuesMap),u=m.useDashboardStore(S=>S.cardControlValuesMap),d=m.useDashboardStore(S=>S.actions.getCard(e)),f=m.useEditorStore(S=>S.editorContext),h=m.useEditorStore(S=>S.card),g=(f==null?void 0:f.type)==="documentSection"&&f.cardId===e?f:void 0,b=g?h:d;if((!!((y=t.inputs)!=null&&y.length)||!!t.defaultInputValues)&&b){const S=$l({dashboard:t,sheetId:g?g.sheetId:s,sheetKind:g?"document":void 0,sectionId:g?g.sectionId:void 0,card:b,runtimeValues:{dashboardInputValues:o,dashboardInputValuesAreAuthoritative:i,filterValues:r,controlValues:a,inlineFilterValuesMap:c,cardControlValuesMap:u},mode:g?"editor":"interactive"}),w=QFe(S.inputs);return{cardFilters:S.inputs.flatMap(C=>C.kind==="filter"&&!w.has(C.filter.id)?[C.filter]:[]),cardFilterValues:S.activeFilters.filter(C=>!w.has(C.filterId))}}return g?{cardFilters:[],cardFilterValues:g.documentFilterValues||[]}:xP(n,r,s,e)}function QFe(e){return new Set(e.flatMap(t=>{var n;return t.kind==="filter"&&((n=t.compatibility)==null?void 0:n.source)==="cardInlineFilter"?[t.filter.id]:[]}))}const HD={dense:{rowPad:"py-1",cell:"text-[11px]",header:"text-[9px]"},compact:{rowPad:"py-2",cell:"text-[13px]",header:"text-[10px]"},standard:{rowPad:"py-2.5",cell:"text-[13px]",header:"text-[10px]"},comfortable:{rowPad:"py-3",cell:"text-[14px]",header:"text-[11px]"},spacious:{rowPad:"py-3.5",cell:"text-[16px]",header:"text-[12px]"}};function JFe(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(HD,e)?HD[e]:HD.compact}function ePe({currentOrder:e,draggingColId:t,dropTarget:n,pinnedStartIds:r=["select"]}){if(!t||!n||t===n.colId)return null;const s=e.indexOf(t),o=e.indexOf(n.colId);if(s===-1||o===-1)return null;const i=[...e];i.splice(s,1);const a=n.side==="before"?o>s?o-1:o:o>s?o:o+1;i.splice(a,0,t);for(let c=r.length-1;c>=0;c-=1){const u=r[c],d=i.indexOf(u);d>0&&(i.splice(d,1),i.unshift(u))}return i}function cee({rows:e,columns:t,columnSettings:n}){var c;const r=n??{},s=t.filter(u=>u.id!=="select");if(s.length===0)return{};const o={},i=new Set(s.filter(u=>tPe(e,u.id,r[u.id])).map(u=>u.id)),a=s.find(u=>!i.has(u.id))??s[0];o[a.id]="Total";for(const u of s){if(u.id===a.id||!i.has(u.id))continue;let d=0,f=0;for(const h of e){const p=(c=h.original)==null?void 0:c[u.id];if(p==null||p==="")continue;const g=typeof p=="number"?p:Number(p);Number.isFinite(g)&&(d+=g,f+=1)}o[u.id]=f===0?null:d}return o}function tPe(e,t,n){var s;if((n==null?void 0:n.type)==="number")return!0;if(n!=null&&n.type&&n.type!=="none")return!1;let r=!1;for(const o of e){const i=(s=o.original)==null?void 0:s[t];if(i==null||i==="")continue;r=!0;const a=typeof i=="number"?i:Number(i);if(!Number.isFinite(a))return!1}return r}function NB(e){return typeof e=="string"?e.trim().toLowerCase():""}function RO(e){return[e.alias,e.label,e.name,e.qualifiedFieldName,e.id].filter(t=>!!t)}function Jm(e,t,n=[]){const r=NB(t);return[...n,...RO(e)].some(s=>NB(s)===r)}function uee(e,t){return[e.alias,e.metricId,e.metricName,e.metricLabel,e.displayLabel].some(n=>Jm(t,n||""))}function kB(e,t){return t.findIndex(n=>uee(e,n))}function _B(e){return JSON.stringify({fields:e.pivotFields??[],values:e.pivotValues??[]})}function nPe(e,t,n,r){if(t===-1||n===-1||t===n)return null;const s=[...e],[o]=s.splice(t,1),i=r==="before"?n>t?n-1:n:n>t?n:n+1;return s.splice(i,0,o),s}function oy(e,t,n){if(!(e!=null&&e.length))return null;const r=e.findIndex(o=>Jm(o,t.draggingColumnId,(n==null?void 0:n(o))??[])),s=e.findIndex(o=>Jm(o,t.targetColumnId,(n==null?void 0:n(o))??[]));return nPe(e,r,s,t.side)}function iy(e,t,n){return n?{...e??{},[t]:n}:null}function rPe(e,t){const n=e.config;return e.type==="detailTable"?iy(n,"detailColumns",oy(n==null?void 0:n.detailColumns,t)):iy(n,"groupByColumns",oy(n==null?void 0:n.groupByColumns,t))??iy(n,"metricColumns",oy(n==null?void 0:n.metricColumns,t))}function eg(e){var t,n,r,s,o,i;return!e||e.sql?!1:e.type==="detailTable"?!!((n=(t=e.config)==null?void 0:t.detailColumns)!=null&&n.length):!!((s=(r=e.config)==null?void 0:r.groupByColumns)!=null&&s.length||(i=(o=e.config)==null?void 0:o.metricColumns)!=null&&i.length)}function jB(e,t,n,r){var a,c;const s=n.filter(u=>u.isMetricColumn),o=u=>t.filter(d=>Jm(d,u.alias||u.name||u.id)).flatMap(d=>RO(d)),i=u=>s.filter(d=>uee(d,u)).flatMap(d=>[d.alias,d.metricId,d.metricName,d.metricLabel,d.displayLabel].filter(f=>!!f));return iy(e.config,"groupByColumns",oy((a=e.config)==null?void 0:a.groupByColumns,r,o))??iy(e.config,"metricColumns",oy((c=e.config)==null?void 0:c.metricColumns,r,i))}function UD(e,t){return e!=null&&e.length?e.map(n=>RO(n).find(r=>t.includes(r))).filter(n=>!!n):[]}function FO(e,t,n){if(!(t!=null&&t.config))return e;const r=[],s=o=>{o&&e.includes(o)&&!r.includes(o)&&r.push(o)};return t.type==="detailTable"?UD(t.config.detailColumns,e).forEach(s):(UD(t.config.groupByColumns,e).forEach(s),UD(t.config.metricColumns,e).forEach(o=>{s(o),s(n==null?void 0:n(o))})),e.forEach(s),r}function dee(e,t){const n=t==null?void 0:t.groupByColumns;return n!=null&&n.length?[...e].sort((r,s)=>{const o=n.findIndex(a=>Jm(r,a.alias||a.name||a.id)),i=n.findIndex(a=>Jm(s,a.alias||a.name||a.id));return o===-1&&i===-1?0:o===-1?1:i===-1?-1:o-i}):e}function fee(e,t){const n=t==null?void 0:t.metricColumns;if(!(n!=null&&n.length))return e;const r=(i,a)=>{const c=kB(i,n),u=kB(a,n);return c===-1&&u===-1?0:c===-1?1:u===-1?-1:c-u},s=[];let o=0;for(;o<e.length;){const i=e[o];if(!i.isMetricColumn){s.push(i),o+=1;continue}const a=_B(i),c=[];for(;o<e.length&&e[o].isMetricColumn&&_B(e[o])===a;)c.push(e[o]),o+=1;s.push(...c.sort(r))}return s}function hee(e){switch(e){case"previous_period":return"Previous";case"same_period_last_year":return"Last Year";case"start_vs_end":return"Start";case"target":return"Target";default:return"Comparison"}}function pee(e,t){const n=hee(t);return`${e} (${n})`}function sPe(e,t){return`${e} Δ`}function oPe(e,t){if(e){if(t.id&&e[t.id])return e[t.id];if(e[t.name])return e[t.name];if(t.label&&e[t.label])return e[t.label]}}function iPe(e){var r;if((e==null?void 0:e.type)!=="table")return;const t=((r=e.config)==null?void 0:r.metricColumns)||[],n=new Map;return t.forEach(s=>{const o=s.comparisonType??"none";if(o==="none")return;const i=s.label||s.name;n.set(i,pee(i,o))}),s=>n.get(s)??null}function aPe(e){var t,n,r;return e!=null&&e.config?e.type==="detailTable"?!!((t=e.config.detailColumns)!=null&&t.length):!!((n=e.config.groupByColumns)!=null&&n.length||(r=e.config.metricColumns)!=null&&r.length):!1}function lPe({records:e,tablePreferences:t,card:n}){if(!e||e.length===0)return null;const r=(t==null?void 0:t.columnSettingsMap)||{},s=Object.keys(e[0]);let o=s;if(t!=null&&t.columnVisibility&&(o=s.filter(f=>{var h;return((h=t.columnVisibility)==null?void 0:h[f])!==!1})),aPe(n))o=FO(o,n,iPe(n));else if(t!=null&&t.columnSizing){const h=Object.keys(t.columnSizing).filter(g=>o.includes(g)),p=o.filter(g=>!h.includes(g));o=[...h,...p]}const i=f=>td({card:n,columnId:f,existingSettings:r[f]}),a=o.map(f=>{const h=i(f),g=((h==null?void 0:h.textAlign)||"left")==="right";return{text:f,colspan:1,rowspan:1,className:g?"numeric":"",columnId:f,isHeader:!0,isNumeric:g}}),c=e.map(f=>({cells:o.map(h=>{const p=i(h),g=mee(f[h],h,p,n),x=((p==null?void 0:p.textAlign)||"left")==="right";return{text:g,colspan:1,rowspan:1,className:x?"numeric":"",columnId:h,isHeader:!1,isNumeric:x}})})),u=o.map((f,h)=>{var p,g;return{index:h,columnId:f,label:f,isNumeric:(((p=i(f))==null?void 0:p.textAlign)||"left")==="right",measuredWidthPx:Number((g=t==null?void 0:t.columnSizing)==null?void 0:g[f])||void 0}}),d=cPe({records:e,visibleColumns:o,columnSettings:r,resolveSettings:i,tablePreferences:t,card:n});return{headers:[{cells:a}],rows:c,grandTotal:d,metadata:{tableType:"data",totalRows:c.length,totalColumns:o.length,columnOrder:o,columns:u,hasGrandTotal:!!d}}}function cPe({records:e,visibleColumns:t,columnSettings:n,resolveSettings:r,tablePreferences:s,card:o}){var u,d;if(!(((d=(u=s==null?void 0:s.tableStyle)==null?void 0:u.totals)==null?void 0:d.enabled)===!0||!!(o&&mv(o))))return null;const a=cee({rows:e.map(f=>({original:f})),columns:t.map(f=>({id:f})),columnSettings:n});return Object.keys(a).length===0?null:{cells:t.map(f=>{const h=r(f),p=a[f],g=typeof p=="number"?mee(p,f,h,o):p==null?"":String(p),b=(h==null?void 0:h.textAlign)||"left",x=typeof p=="number"||b==="right";return{text:g,colspan:1,rowspan:1,className:x?"numeric":"",columnId:f,isHeader:!1,isNumeric:x}})}}function mee(e,t,n,r){if(e==null)return"";if((n==null?void 0:n.type)==="number"&&typeof e=="number")try{const s=yv({card:r,columnId:t,existingSettings:n});return s!=null&&s.type&&s.type!=="auto"?Fn(e,s.type,s):Bn.formatNumberWithColumnSettings(e,n.numberFormat,n.numberFormat.locale||"en-US")||e.toLocaleString()}catch{return e.toLocaleString()}if((n==null?void 0:n.type)==="date")try{const s=n.dateFormat.timezone&&n.dateFormat.timezone!=="auto"?n.dateFormat.timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,o=n.dateFormat.useCustomFormat?n.dateFormat.customFormat:n.dateFormat.format;return Bn.formatDate(String(e),o,s,n.dateFormat.sourceTimezone||"auto")}catch{return String(e)}return typeof e=="number"?e.toLocaleString():String(e)}function uPe({records:e,groupByColumns:t=[],pivotSchema:n=[],card:r,columnSettings:s={}}){var x,y,S;if(!e||e.length===0)return null;const o=dee(t,r.config),i=fee(n,r.config),a=GP(e,o),c=KP(e),u=i.filter(w=>w.isMetricColumn),d=new Map;u.forEach((w,C)=>{d.set(w.alias,Yu({card:r,columnId:w.alias,metricIndex:C,groupByColumnCount:o.length,columnSettingsMap:s}))});const f=[...o.map(w=>({text:w.label||w.name,colspan:1,rowspan:1,className:"",columnId:w.alias||w.name,isHeader:!0,isNumeric:!1})),...u.map(w=>({text:w.metricLabel||w.metricName||w.alias,colspan:1,rowspan:1,className:"numeric",columnId:w.alias,isHeader:!0,isNumeric:!0}))],h=a.map(w=>{const C=[],N=w.isSubtotal&&!w.isGrandTotal;return o.forEach(k=>{var D,j,I;const _=k.alias||k.name;let E=w[_];if(N){const T=w.aggregate||"SUM",F=(I=(j=(D=r==null?void 0:r.config)==null?void 0:D.rowAggregates)==null?void 0:j.find(P=>P.groupLevel===w.subtotalLevel&&P.function===T))==null?void 0:I.label;E=PX(w,_,T,F)}else w.isGrandTotal&&(E="");C.push({text:E&&E!=="__TOTAL__"?String(E):"",colspan:1,rowspan:1,className:"",columnId:_,isHeader:!1,isNumeric:!1})}),u.forEach(k=>{const _=k.alias,E=d.get(_),D=EB(w[_],E);C.push({text:D,colspan:1,rowspan:1,className:"numeric",columnId:_,isHeader:!1,isNumeric:!0})}),{type:N?"subtotal":void 0,cells:C}});let p=null;if(c){const w=c.aggregate||"SUM",C=(S=(y=(x=r==null?void 0:r.config)==null?void 0:x.rowAggregates)==null?void 0:y.find(_=>_.groupLevel==="ALL"))==null?void 0:S.label,N=OX(w,C),k=[];o.forEach((_,E)=>{k.push({text:E===0?N:"",colspan:1,rowspan:1,className:"",isHeader:!1,isNumeric:!1})}),u.forEach(_=>{const E=_.alias,D=d.get(E);let j=c[E];(j==null||j==="")&&(j=e.filter(T=>!T.isSubtotal&&!T.isGrandTotal).reduce((T,F)=>{const P=qP(F[E]);return T+(P??0)},0));const I=EB(j,D);k.push({text:I,colspan:1,rowspan:1,className:"numeric",columnId:E,isHeader:!1,isNumeric:!0})}),p={cells:k}}const g=[...o.map(w=>w.alias||w.name),...u.map(w=>w.alias)],b=g.map((w,C)=>{var N,k,_;return{index:C,columnId:w,label:((N=o.find(E=>(E.alias||E.name)===w))==null?void 0:N.label)||((k=u.find(E=>E.alias===w))==null?void 0:k.metricLabel)||((_=u.find(E=>E.alias===w))==null?void 0:_.metricName)||w,isNumeric:u.some(E=>E.alias===w)}});return{headers:[{cells:f}],rows:h,grandTotal:p,metadata:{tableType:"aggregate",totalRows:h.length,totalColumns:f.length,groupByCount:o.length,hasGrandTotal:!!p,columnOrder:g,columns:b}}}function EB(e,t){if(e==null)return"";const n=YP(e,t);return n!==null?n:typeof e=="number"?e.toLocaleString():String(e)}function DB(e){return Array.isArray(e)?e.filter(t=>!(t!=null&&t.isGrandTotal)).length:0}function dPe({exportData:e,pivotTableConfig:t,pivotData:n}){var a;const r=Array.isArray(e==null?void 0:e.records)?e.records:Array.isArray(e)?e:[],s=DB(r);if(s>0)return s;const o=Array.isArray((a=t==null?void 0:t.data)==null?void 0:a.rowData)?t.data.rowData.length:0;if(o>0)return o;const i=Array.isArray(n==null?void 0:n.records)?n.records:[];return DB(i)}const IB=[10,20,50,100,500,1e3],fPe=50;function R_(e){return e&&e>0?e:fPe}function gee(e){const t=R_(e),n=[...IB];return IB.includes(t)||(n.push(t),n.sort((r,s)=>r-s)),n}function bee(e,t){var r,s,o,i;if(t==="table-print")return"disabled";if((s=(r=e.preferences)==null?void 0:r.tablePrefs)!=null&&s.forceClientPagination)return"client";const n=m.hasValidCardConfig(e.config);return e.sql&&!n?(i=(o=e.preferences)==null?void 0:o.tablePrefs)!=null&&i.enableDevModePagination?"server":"client":n&&iM(e)?"server":"client"}async function hPe({apiServiceUrl:e,authToken:t,connectionId:n,requestPayloadBase:r}){if(!n)throw new Error("No connection ID found for card");const s={connection_id:n,...r,exportMode:!0};return m.postRequestRegular(`${e}/v1/query`,t,s,"POST")}function xee(){const e={};return document.querySelectorAll('[data-spr-expand-id][aria-expanded="true"]').forEach(t=>{const n=t.getAttribute("data-spr-expand-id");n&&(e[n]=!0)}),e}async function yee(e,t,n){const r=await fetch(`${e}/v1/exports`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)}),s=await r.json();if(!r.ok){const o=s;throw new Rg(o.message||o.error||"Failed to create export",r.status,o)}return s}async function pPe(e,t,n){var o;const r=new URL(`${e}/v1/exports`);(o=n==null?void 0:n.status)!=null&&o.length&&r.searchParams.set("status",n.status.join(",")),n!=null&&n.limit&&r.searchParams.set("limit",String(n.limit));const s=await fetch(r.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)throw new Rg("Failed to fetch exports",s.status);return s.json()}async function mPe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new Rg("Failed to fetch export status",r.status);return r.json()}async function gPe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}/download`,{headers:{Authorization:`Bearer ${t}`}});if(r.ok){const s=await r.json();if(s.downloadUrl)return s.downloadUrl}throw new Rg("Failed to get download URL",r.status)}async function bPe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new Rg("Failed to cancel export",r.status)}class Rg extends Error{constructor(t,n,r){super(t),this.status=n,this.details=r,this.name="ExportError"}}function xPe(e){return["pending","processing","chunking","compacting"].includes(e)}function yPe(e){return["completed","failed","cancelled"].includes(e)}function vPe(e){return!e||e===0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}const wPe=[];function PO(e){var k;const t=m.useInteractionStore(_=>_.interactionStates),n=m.useDashboardStore(_=>_.dashboard),r=m.useDashboardStore(_=>_.dashboard.filters),s=m.useDashboardStore(_=>_.dashboard.controls),o=m.useDashboardStore(_=>_.filterValues),i=m.useDashboardStore(_=>_.controlValues),a=m.useDashboardStore(_=>_.cardControlValuesMap),c=m.useDashboardStore(_=>_.selectedSheetId),u=m.useDashboardStore(_=>{var E;return(E=_.dashboard)==null?void 0:E.id}),d=m.useDashboardStore(_=>_.isVisualEditing),f=m.useDashboardStore(_=>_.inlineFilterValuesMap),h=m.useDashboardStore(_=>_.dashboardInputValues),p=m.useDashboardStore(_=>_.dashboardInputValuesAreAuthoritative),g=m.useEditorStore(_=>_.inlineFilterValuesMap),b=m.useEditorStore(_=>_.editorContext),y=(b==null?void 0:b.type)==="documentSection"&&b.cardId===e.id?b:void 0,S=!!y,w=v.useMemo(()=>{if(y){const _=y.documentFilterValues||wPe,D=[...g[e.id]||[],..._];return D.length>0?{[e.id]:D}:{}}return d?{[e.id]:g[e.id]??f[e.id]}:f},[S,d,e.id,f,y,g]),C=!!((k=n.inputs)!=null&&k.length)||!!n.defaultInputValues,N=v.useMemo(()=>C?$l({dashboard:n,sheetId:y?y.sheetId:c,sheetKind:y?"document":void 0,sectionId:y?y.sectionId:void 0,card:e,runtimeValues:{dashboardInputValues:h,dashboardInputValuesAreAuthoritative:p,filterValues:o,controlValues:i,inlineFilterValuesMap:w,cardControlValuesMap:a},mode:y?"editor":"interactive"}):void 0,[e,a,i,n,h,p,y,o,w,S,c,C]);return v.useMemo(()=>{const _=S?[]:r,E=S?[]:o,D=S?{}:t,j=S?[]:s,I=S?{}:i,T=S?{}:a;return fv({card:e,interactionStates:D,currentDashboardId:u,filters:_,filterValues:E,selectedSheetId:y?y.sheetId:c,inlineFilterValuesMap:w,dashboardControls:j,dashboardControlValues:I,cardControlValuesMap:T,dashboardInputContext:N})},[e,t,u,r,s,o,i,a,N,c,w,S,y])}function SPe(e,t){var n;return{connectionId:t,connectionType:((n=e.dataSource)==null?void 0:n.connectionType)||"unknown",mode:"database",selectedEntities:[]}}function vee(e,t){var r,s,o;const n=((s=(r=e.dataSource)==null?void 0:r.connectionId)==null?void 0:s.trim())||((o=e.connectionId)==null?void 0:o.trim())||"";if(!n)throw new Error("No connection ID found for card");return{connectionId:n,requestPayloadBase:{...t,cardDataSource:t.cardDataSource||e.dataSource||SPe(e,n)}}}function CPe(e){const t=vee(e.card,e.requestPayloadBase),{cardId:n,...r}=t.requestPayloadBase;return{type:"card",dashboardId:e.dashboardId,cardId:e.card.id,title:e.title,connection_id:t.connectionId,...r,timezone:e.timezone,totalRows:e.totalRows,format:e.format,formatOptions:e.formatOptions}}function wee(e,t){return(e==null?void 0:e[t])!==!1}function See(e,t,n){const r={...e||{}};return n?delete r[t]:r[t]=!1,Object.keys(r).length>0?r:void 0}function NPe(){}function kPe(e,t){return e.filter(n=>wee(t,n))}const x1=1e4,WD=1e6,bp="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",y1="flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50";function _Pe(e,t){const n=new Map;for(const r of e||[])r!=null&&r.id&&n.set(r.id,r);for(const r of t||[])r!=null&&r.id&&n.set(r.id,r);return Array.from(n.values())}function jPe(e){var n,r,s;return eg(e)?(e.type==="detailTable"?((n=e.config)==null?void 0:n.detailColumns)||[]:[...((r=e.config)==null?void 0:r.groupByColumns)||[],...((s=e.config)==null?void 0:s.metricColumns)||[]]).map(o=>o.alias||o.label||o.name||o.qualifiedFieldName||o.id).filter(o=>!!o):[]}function EPe({card:e,records:t}){var i,a;const n=(a=(i=e.preferences)==null?void 0:i.tablePrefs)==null?void 0:a.columnVisibility;if(!n)return;const r=Object.keys(t[0]||{}),s=jPe(e),o=r.length>0?eg(e)?FO(r,e):r:s;return o.length===0?null:kPe(o,n)}function F_({isOpen:e,onClose:t,frame:n,card:r,data:s}){var H;const{authToken:o,tokenProps:i}=Ct(),{addExport:a}=xK(),c=r==null?void 0:r.type,u=v.useMemo(()=>c?$X(c):["pdf"],[c]),d=v.useMemo(()=>c?zX(c):"pdf",[c]),[f,h]=v.useState(!1),[p,g]=v.useState(!1),[b,x]=v.useState({format:d,pageSize:"letter",orientation:"portrait",protectPdf:!1,pdfPassword:"",delimiter:",",includeHeaders:!0,exportMode:"local"}),y=m.useDashboardStore(A=>{var W;return(W=A.dashboard)==null?void 0:W.id});m.useDashboardStore(A=>{var W;return(W=A.dashboard)==null?void 0:W.title});const S=m.useDashboardStore(A=>A.selectedLensId),w=m.useDashboardStore(A=>A.dashboard.filters),C=m.useDashboardStore(A=>A.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),{cardFilters:N,cardFilterValues:k}=lee((r==null?void 0:r.id)||""),_=v.useMemo(()=>[...k||[],...C||[]],[k,C]),E=v.useMemo(()=>_Pe(w,N),[w,N]),D={id:"",type:"table"},j=_v(r||D),I=PO(r||D),T=(H=r==null?void 0:r.preferences)==null?void 0:H.tablePrefs,F=c_(r?[r]:[],{authority:"runtime"}).payload,P=v.useMemo(()=>r?hv({card:r,cardConfig:I.queryRelevantConfig,semanticExecutionPayload:F}):null,[r,I.queryRelevantConfig,F]),R=v.useMemo(()=>r?CP(r,{finalFiltersKey:"",selectedLensId:S,cardFilterValues:_,controlValues:I.controlValues,controlDefinitions:I.controlDefinitions,cardControlDefinitions:I.cardControlDefinitions,controlBindings:I.controlBindings,queryRelevantConfig:I.queryRelevantConfig,filters:E,resolvedPrimaryDateField:P}):null,[_,r,I.cardControlDefinitions,I.controlBindings,I.controlDefinitions,I.controlValues,I.queryRelevantConfig,E,P,S]),B=r?(j==null?void 0:j.data)||s:null,z=Gh(r||D,B),U=(r==null?void 0:r.title)||"Visual Report",Y=CX(kZ({filters:E,filterValues:_||[]})),K=(r?bee(r):"client")==="server",q=v.useMemo(()=>{var X;if(!r||r.type!=="table"&&r.type!=="detailTable")return 0;const A=(j==null?void 0:j.data)||s;return K&&((X=j==null?void 0:j.pagination)!=null&&X.totalCount)?j.pagination.totalCount:(Array.isArray(A)?A:(A==null?void 0:A.records)||[]).length},[r,j==null?void 0:j.data,j==null?void 0:j.pagination,s,K]),M=v.useMemo(()=>!(!r||r.type!=="table"&&r.type!=="detailTable"||!K||q<=x1),[r,K,q]),G=q>WD;v.useEffect(()=>{b.format==="pdf"&&q>x1&&u.includes("csv")&&x(A=>({...A,format:"csv"}))},[q,b.format,u]);const L=()=>{x(A=>({...A,pdfPassword:"",protectPdf:!1,exportMode:"local"})),g(!1),t()},$=async()=>{var A,W,X,Z;if(!r||!y||!R){ut.error("Missing card or dashboard information");return}if(G){ut.error(`Export exceeds maximum of ${WD.toLocaleString()} rows. Please apply filters to reduce the dataset.`);return}h(!0);try{const J=(j==null?void 0:j.data)||s,re=Array.isArray(J)?J:Array.isArray(J==null?void 0:J.records)?J.records:[],fe=EPe({card:r,records:re});if(fe===null){ut.error("Column visibility could not be resolved yet. Run the table before exporting with hidden columns.");return}const de=Intl.DateTimeFormat().resolvedOptions().timeZone,Se=((W=(A=i==null?void 0:i.params)==null?void 0:A.calendarContext)==null?void 0:W.tz)||((X=i==null?void 0:i.params)==null?void 0:X.timezone)||de,ue={useFormattedValues:!0,timezone:Se,browserTimezone:de,isSqlCard:!!(r!=null&&r.sql),locale:navigator.language||"en-US",delimiter:b.delimiter,includeHeaders:b.includeHeaders,columnSettings:T==null?void 0:T.columnSettingsMap,visibleColumns:fe},ve=CPe({card:r,dashboardId:y,title:U,timezone:Se,totalRows:q,format:"csv",formatOptions:ue,requestPayloadBase:R.requestPayloadBase}),xe=await yee(i.apiServiceUrl,(o==null?void 0:o.accessToken)||"",ve);a({id:xe.exportId,status:xe.status==="pending"?"pending":"processing",progress:0,title:U,totalRows:xe.estimatedRows,totalChunks:xe.totalChunks,completedChunks:0,startedAt:new Date,lastUpdatedAt:new Date,expiresAt:new Date(Date.now()+24*60*60*1e3)}),xe.wasTruncated?ut.warning(`Export started for ${xe.estimatedRows.toLocaleString()} rows (truncated from ${(Z=xe.originalRows)==null?void 0:Z.toLocaleString()}). You'll be notified when it's ready.`,{duration:5e3}):ut.success(`Export started for ${xe.estimatedRows.toLocaleString()} rows. You'll be notified when it's ready.`,{duration:4e3,icon:l.jsx(SS,{className:"h-4 w-4"})}),L()}catch(J){console.error("Async export error:",J),ut.error(J.message||"Failed to start export. Please try again.")}finally{h(!1)}},V=async()=>{var J,re,fe,de,Se;if(b.exportMode==="async"&&M&&b.format==="csv"){await $();return}if(!r||!R){ut.error("No card selected");return}const A=(j==null?void 0:j.data)||s;if(!A){ut.error("No data to export");return}const X=!r||!["table","aggregateTable","pivotTable","detailTable"].includes(r.type)?0:r.type==="pivotTable"?dPe({exportData:A,pivotTableConfig:z,pivotData:B}):(Array.isArray(A==null?void 0:A.records)?A==null?void 0:A.records:Array.isArray(A)?A:[]).length;let Z=null;if(r.type==="table"||r.type==="detailTable"){const ue=Array.isArray(A)?A:Array.isArray(A==null?void 0:A.records)?A.records:[];ue.length>0&&(Z=lPe({records:ue,tablePreferences:T,card:r}))}else if(r.type==="aggregateTable"){const ue=Array.isArray(A)?A:Array.isArray(A==null?void 0:A.records)?A.records:[];if(ue.length>0){const ve=(A==null?void 0:A.groupByColumns)||((J=r.config)==null?void 0:J.groupByColumns)||[],xe=(A==null?void 0:A.pivotSchema)||[];Z=uPe({records:ue,groupByColumns:ve,pivotSchema:xe,card:r,columnSettings:T==null?void 0:T.columnSettingsMap})}}else if(r.type==="pivotTable"){const ue=$Z(n.id,"pivotTable"),ve=(ue==null?void 0:ue.rows.filter(xe=>Array.isArray(xe.cells)&&xe.cells.length>0).length)||0;ue&&ve===X&&(Z=ue)}h(!0);try{const ue=ve=>{if(ve){if(ve.usedBanding){const xe=ve.bandCount||1;ut.info(`PDF layout optimized for wide table: ${xe} column band${xe===1?"":"s"} (${ve.effectivePageSize||b.pageSize} ${ve.effectiveOrientation||b.orientation})`);return}ve.autoAdjustedLayout&&ut.info(`PDF layout auto-adjusted to ${ve.effectivePageSize||b.pageSize} ${ve.effectiveOrientation||b.orientation} for readability`)}};if(b.format==="csv"){let ve="";const xe=`${U.replace(/[^a-z0-9]/gi,"_")}.csv`,ke=(r==null?void 0:r.type)&&["table","aggregateTable","pivotTable","detailTable"].includes(r.type);if((r.type==="table"||r.type==="detailTable")&&K)try{const se=vee(r,R.requestPayloadBase),be=await hPe({apiServiceUrl:i.apiServiceUrl,authToken:(o==null?void 0:o.accessToken)||"",connectionId:se.connectionId,requestPayloadBase:se.requestPayloadBase});be.rowLimitExceeded&&ut.warning("Dataset exceeds 10,000 rows. Exporting first 10,000 records. Please apply filters to reduce dataset size.",{duration:5e3});const Ce=be.records||[];ez(Ce,xe,T,r,{delimiter:b.delimiter,includeHeaders:b.includeHeaders,useFormattedValues:!0}),ut.success("CSV exported successfully"),L();return}catch(se){ut.error(`Export failed: ${se.message||"Unknown error"}`),console.error("Export error:",se);return}if(ke)switch(r.type){case"table":case"detailTable":{const se=Array.isArray(A)?A:(A==null?void 0:A.records)||[];if(!se||se.length===0){ut.error("No data available to export");return}ez(se,xe,T,r,{delimiter:b.delimiter,includeHeaders:b.includeHeaders,useFormattedValues:!0}),ut.success("CSV exported successfully"),L();return}case"aggregateTable":{const se=Array.isArray(A)?A:(A==null?void 0:A.records)||[];if(!se||se.length===0){ut.error("No data available to export");return}const be=(A==null?void 0:A.groupByColumns)||((re=r.config)==null?void 0:re.groupByColumns)||[],Ce=(A==null?void 0:A.pivotSchema)||[],ge=GP(se,be),ee=KP(se),te=(de=(fe=r==null?void 0:r.preferences)==null?void 0:fe.tablePrefs)==null?void 0:de.columnSettingsMap,ce=FX(ge,ee,be,Ce,r,te);if(!ce){ut.error("Failed to generate CSV content");return}RC(ce,xe),ut.success("CSV exported successfully"),L();return}case"pivotTable":if(z){VX(z.data,r,xe,{delimiter:b.delimiter,includeHeaders:b.includeHeaders,includeSubtotals:!0,includeGrandTotal:!0,showRowTotals:(Se=z.options)==null?void 0:Se.showRowTotals}),ut.success("CSV exported successfully"),t();return}else{ut.error("Unable to export pivot table data");return}default:throw new Error(`Unsupported table type: ${r.type}`)}else{const se=Array.isArray(A)?A:(A==null?void 0:A.records)||[];if(!se||se.length===0){ut.error("No data available to export");return}const be=Object.keys(se[0]),Ce=ee=>{if(ee==null)return"";const te=String(ee);return te.includes(b.delimiter)||te.includes('"')||te.includes(`
814
+ ${T}`:T},color:E=>{if(f)return f;const D=E==null?void 0:E.raw,j=gB({raw:D,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a});return m.getContrastColor(j)},font:{size:((y=(x=o==null?void 0:o.chart)==null?void 0:x.font)==null?void 0:y.size)||((S=u==null?void 0:u.font)==null?void 0:S.size)||12,weight:((C=(w=o==null?void 0:o.chart)==null?void 0:w.font)==null?void 0:C.weight)||((N=u==null?void 0:u.font)==null?void 0:N.weight)||"bold",family:((_=(k=o==null?void 0:o.chart)==null?void 0:k.font)==null?void 0:_.family)||"Inter"}},backgroundColor:E=>{const D=E==null?void 0:E.raw;return gB({raw:D,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a})}}}function dRe({dimensionKeys:e,metricKey:t,formatConfig:n}){const r=Math.max(e.length-1,0);return{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},tooltip:{intersect:!0,mode:"point",filter:s=>{if(e.length<=1)return!0;const o=s.raw;return typeof(o==null?void 0:o.l)=="number"?o.l===r:!0},callbacks:{title:s=>{if(!(s!=null&&s.length))return"";const o=s[s.length-1];return bRe(o==null?void 0:o.raw,e)},label:s=>{const o=s==null?void 0:s.raw,i=HJ(o,e),a=Number((o==null?void 0:o.v)??0),c=UJ(a,n),u=t||"Value";return i?`${i} — ${u}: ${c}`:`${u}: ${c}`}}}}}}function fRe(e){return e.reduce((t,n)=>es(t,n||{}),{})}function hRe(e,t,n){return e.map(r=>{const s={...r};t.forEach(i=>{const a=r[i];(a==null||a==="")&&(s[i]="(Blank)")});const o=Number(r[n]);return s[n]=Number.isFinite(o)?o:0,s})}function pRe(e,t,n,r){var o,i,a;const s=((a=(i=(o=r==null?void 0:r.chart)==null?void 0:o.dataset)==null?void 0:i.backgroundColor)==null?void 0:a.filter(Boolean))??qh();return t.map((c,u)=>{const d=new Map;return u>0||Array.from(new Set(e.map(h=>h[c]).filter(h=>!!h))).forEach((h,p)=>{var g,b;if((b=(g=n==null?void 0:n.colorConfig)==null?void 0:g.segments)!=null&&b[h]){d.set(h,n.colorConfig.segments[h]);return}d.set(h,s[p%s.length])}),d})}function mRe(e,t){const n=bv({card:t,chartType:"treemap",preferences:e,dataLabelsConfig:e==null?void 0:e.dataLabelsConfig}),r=n.formatOptions||{};if(_g(n))return{format:"number",formatOptions:{},rawValue:!0};const s=["decimalPlaces","currency","locale","useSuffix","prefix","suffix","negativeInParentheses","multiplyBy"],o=Object.fromEntries(Object.entries(r).filter(([i])=>s.includes(i)));return{format:r.type||"number",formatOptions:o}}function HJ(e,t){var n;if(!e)return"";if((n=e._data)!=null&&n.label)return e._data.label;if(e.g)return e.g;if(e._data)return gRe(e._data,t);if(e.path){const r=e.path.split("."),s=r[r.length-1];if(s)return s}return""}function gRe(e,t){for(let n=t.length-1;n>=0;n-=1){const r=e[t[n]];if(r!=null&&r!=="")return r}return"(Blank)"}function bRe(e,t){var n;return(n=e==null?void 0:e._data)!=null&&n.path?e._data.path.split(".").filter(Boolean).join(" → "):e!=null&&e.path?e.path.split(".").filter(Boolean).join(" → "):e!=null&&e._data?t.map(r=>{var s;return((s=e._data)==null?void 0:s[r])??"(Blank)"}).filter(Boolean).join(" → "):e!=null&&e.g?e.g:""}function UJ(e,t){return t.rawValue?String(e):Fn(e,t.format,t.formatOptions)}function gB({raw:e,dimensionKeys:t,colorLookups:n,themeStyle:r,preferences:s,colorMode:o}){var g,b,x,y,S,w,C;if(!e)return"#999999";const i=((x=(b=(g=r==null?void 0:r.chart)==null?void 0:g.dataset)==null?void 0:b.backgroundColor)==null?void 0:x.filter(Boolean))??qh(),a=xRe(e,t),c=a[0]||((y=e._data)==null?void 0:y[t[0]])||e.g||"",u=((w=(S=s==null?void 0:s.colorConfig)==null?void 0:S.segments)==null?void 0:w[c])||((C=n[0])==null?void 0:C.get(c))||i[0]||"#999999",d=Math.max(t.length-1,0),f=typeof e.l=="number"?e.l:a.length-1,h=DO(f,0,d);if(h===0||o==="category")return u;const p=yRe(e);return vRe(u,p,h)}function xRe(e,t){var r;if(!e)return[];if((r=e._data)!=null&&r.path)return e._data.path.split(".").filter(Boolean);if(e.path)return e.path.split(".").filter(Boolean);const n=t.map(s=>{var o;return(o=e._data)==null?void 0:o[s]}).filter(s=>!!s);return n.length?n:e.g?[e.g]:[]}function yRe(e){if(!e)return 1;const t=Number(e.v??0),n=Number(e.gs??e.s??0);return n>0&&Number.isFinite(t)?DO(t/n,0,1):1}function vRe(e,t,n){const r=Math.min(n*.12,.35),s=Math.max(0,.25*(1-t)),o=Math.min(r+s,.6),i=Math.max(0,t-.85)*.4;let a=bB(e,"#ffffff",o);return a=bB(a,"#000000",i),a}function bB(e,t,n){const r=DO(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=xB(e),o=xB(t);if(!s||!o)return e;const i=Math.round(s.r+(o.r-s.r)*r),a=Math.round(s.g+(o.g-s.g)*r),c=Math.round(s.b+(o.b-s.b)*r);return wRe(i,a,c)}function xB(e){const t=e.replace("#","");if(t.length!==6)return null;const n=parseInt(t,16);return{r:n>>16&255,g:n>>8&255,b:n&255}}function wRe(e,t,n){const r=s=>s.toString(16).padStart(2,"0");return`#${r(RD(e))}${r(RD(t))}${r(RD(n))}`}function RD(e){return Math.min(255,Math.max(0,Math.round(e)))}function DO(e,t,n){return Math.max(t,Math.min(n,e))}function WJ(e,t){if(!e||t===1)return e;e=e.replace(/^#/,""),e.length===3&&(e=e.split("").map(o=>o+o).join(""));const n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),s=parseInt(e.substring(4,6),16);return`rgba(${n}, ${r}, ${s}, ${t})`}function SRe(e,t,n,r){var a;if(e==null)return"";const s=Number(e);if(isNaN(s))return String(e);const o=t.format||"auto",i=t.formatOptions||{};switch(o){case"currency":return Fn(s,"currency",{currency:i.currency||"USD",decimalPlaces:i.decimalPlaces??2,useSuffix:i.useSuffix,locale:i.locale});case"number":return Fn(s,"number",{decimalPlaces:i.decimalPlaces??0,useSuffix:i.useSuffix,locale:i.locale});case"percent":return Fn(s,"percent",{decimalPlaces:i.decimalPlaces??1,locale:i.locale});case"none":return String(e);case"auto":default:return n!=null&&n.type&&n.type!=="auto"?Fn(s,n.type,n):(a=r==null?void 0:r.formatOptions)!=null&&a.type&&r.formatOptions.type!=="auto"?Fn(s,r.formatOptions.type,r.formatOptions):String(e)}}function T_(e,t,n,r){var p,g;if(!(e.enabled??!1))return{display:!1};const o=e.position||"auto";let i,a;if(o==="custom")i=e.anchor||"center",a=e.align||"center";else{const x=n==="horizontalBar"?{auto:{anchor:"end",align:"right"},top:{anchor:"end",align:"right"},center:{anchor:"center",align:"center"},bottom:{anchor:"start",align:"left"},left:{anchor:"start",align:"left"},right:{anchor:"end",align:"right"}}:{auto:{anchor:"end",align:"top"},top:{anchor:"end",align:"top"},center:{anchor:"center",align:"center"},bottom:{anchor:"start",align:"bottom"},left:{anchor:"start",align:"left"},right:{anchor:"end",align:"right"}},y=x[o]||x.auto;i=y.anchor,a=y.align}const c=e.color,u=b=>{var y,S,w,C,N,k;if(c&&c!=="auto")return c;if(o!=="center"||n==="line"||n==="area")return m.getContrastColor(m.getCanvasBackgroundColor((y=b==null?void 0:b.chart)==null?void 0:y.canvas));const x=((w=(S=b.dataset)==null?void 0:S.backgroundColor)==null?void 0:w[b.dataIndex])||((C=b.dataset)==null?void 0:C.backgroundColor)||m.getCanvasBackgroundColor((N=b==null?void 0:b.chart)==null?void 0:N.canvas);return m.getContrastColor(x,{baseColor:m.getCanvasBackgroundColor((k=b==null?void 0:b.chart)==null?void 0:k.canvas)})},d=((p=e.font)==null?void 0:p.size)||11,f=((g=e.font)==null?void 0:g.weight)||"normal",h=e.rotation||0;return{display:e.display==="auto"?"auto":!0,formatter:b=>SRe(b,e,r,t),anchor:i,align:a,color:u,font:{size:d,weight:f},rotation:h,clamp:e.clamp??!0,clip:e.clip??!1,offset:e.offset??4}}function M_(e,t){t&&(e.onHover=function(n,r){var o;const s=((o=n.native)==null?void 0:o.target)||n.target;r.length?s.style.cursor="pointer":s.style.cursor="default"})}function IO(e){switch(e){case"dashed":return[6,4];case"dotted":return[2,2];case"dash-dot":return[6,2,2,2];case"solid":default:return[]}}function A_(e,t){if(t!==void 0)return t.enabled===!1?{enabled:!1}:t.enabled===void 0?e!=null&&e.enabled?{...e,...t,enabled:!0,formatOptions:{...e.formatOptions,...t.formatOptions},font:{...e.font,...t.font}}:void 0:e?{enabled:!0,display:t.display??e.display,position:t.position??e.position,anchor:t.anchor??e.anchor,align:t.align??e.align,offset:t.offset??e.offset,rotation:t.rotation??e.rotation,clamp:t.clamp??e.clamp,clip:t.clip??e.clip,format:t.format??e.format,formatOptions:{...e.formatOptions,...t.formatOptions},font:{...e.font,...t.font},color:t.color??e.color}:t}function CRe(e,t){return Array.from({length:e},(n,r)=>({idx:r,fill:t&&r>0?"-1":"origin"}))}function NRe(e,t,n){const r=CRe(t,n);return!e||e.length===0?r:r.map(s=>{const o=e.find(i=>i.idx===s.idx);return o?{...s,...o,fill:o.fill??s.fill}:s})}function kRe(e,t,n,r,s){const o=n==null?void 0:n.lineStyleConfig,i=n==null?void 0:n.yAxisConfig;return e.map((a,c)=>{const u=t.find(g=>g.idx===c),d={...a};d.type="line",d.fill=(u==null?void 0:u.fill)??"origin",d.borderWidth=d.borderWidth??2,d.tension=d.tension??.1,d.pointRadius=(u==null?void 0:u.pointRadius)??(o==null?void 0:o.pointRadius)??3,d.pointStyle=(u==null?void 0:u.pointStyle)??(o==null?void 0:o.pointStyle)??"circle";const f=(u==null?void 0:u.pointRadius)??(o==null?void 0:o.pointRadius)??3;d.pointHoverRadius=(u==null?void 0:u.pointHoverRadius)??f+2,d.borderDash=IO((u==null?void 0:u.lineStyle)??(o==null?void 0:o.lineStyle));const h=d.borderColor||d.backgroundColor;h&&typeof h=="string"&&(d.backgroundColor=WJ(h,.5));const p=A_(n==null?void 0:n.dataLabelsConfig,u==null?void 0:u.dataLabels);if(p){const g=xv({card:s,preferences:n,dataLabelsConfig:p,datasetIndex:c,datasetLabel:a.label}).formatOptions;d.datalabels=T_(p,i,"area",g)}return d})}function _Re(e,t){var r,s;return{...e,x:{...e==null?void 0:e.x,display:((r=e==null?void 0:e.x)==null?void 0:r.display)??!0},y:{...e==null?void 0:e.y,display:((s=e==null?void 0:e.y)==null?void 0:s.display)??!0,stacked:t}}}function jRe({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var N,k;const{keys:i}=pr(t),a=Oy(i),c=a.length,u=o==="stackedArea",d=NRe(s==null?void 0:s.datasetOptions,c,u),f=i==null?void 0:i[0],h=Qc(t,f),p=Ng(a,t,s,1,"none",f,!1,Cg(t)),g=kRe(p,d,s,u,e),b=Da(g,r),{options:x,plugins:y}=sd({cardType:o||"area",cfg:n,preferences:s,customCfg:r,card:e}),S=_Re(x==null?void 0:x.scales,u),w={...x,scales:S},C=(((k=(N=e.interactionConfig)==null?void 0:N.interactions)==null?void 0:k.length)??0)>0;return M_(w,C),{type:"line",data:{labels:h,datasets:b},options:w,plugins:y}}const qJ=["poor","satisfactory","good"],FD={poor:"Poor",satisfactory:"Average",good:"Good"},ERe=["#F5F6F8","#E3E6EC","#CED4DD"],DRe=["#1F2933","#27323D","#303B47"];function IRe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s,card:o}){var fe,de,Se,ue,ve,xe,ke;if(!e||e.length===0)return{type:"bar",data:{labels:[],datasets:[]}};const{dimensionKeys:i,metricKeys:a,keys:c}=pr(e),u=i[0]??c[0];if(!u)return{type:"bar",data:{labels:[],datasets:[]}};const d=a[0]??c.find(se=>se!==u);if(!d)return{type:"bar",data:{labels:[],datasets:[]}};const f=r==null?void 0:r.bulletConfig,h=(f==null?void 0:f.targetMetricKey)??a.find(se=>se!==d),p=(f==null?void 0:f.comparativeMetricKey)??(f!=null&&f.disableAutoComparative?void 0:a.find(se=>se!==d&&se!==h)),g=m.useDashboardStore.getState(),b=s??g.themeStyle,x=g.theme==="dark",y=TRe({data:e,dimensionKey:u,actualKey:d,targetKey:h,comparativeKey:p,bulletConfig:f}),S=y.map(se=>se.label),w=(f==null?void 0:f.showRanges)??WRe(f),C=RRe(y,w),N=(fe=r==null?void 0:r.chartOptions)==null?void 0:fe.indexAxis,_=(N?N==="y"?"horizontal":"vertical":void 0)??(f==null?void 0:f.orientation)??"horizontal",E=_==="vertical"?"x":"y",D=r?{...r,chartOptions:{...r.chartOptions||{},indexAxis:E}}:{chartOptions:{indexAxis:E}},j=VRe(r,o,d),I=URe(f),T=HRe(x),F=qh().filter(Boolean),P=(((Se=(de=b==null?void 0:b.chart)==null?void 0:de.dataset)==null?void 0:Se.backgroundColor)||[]).filter(Boolean),R=(((ve=(ue=b==null?void 0:b.chart)==null?void 0:ue.dataset)==null?void 0:ve.borderColor)||[]).filter(Boolean),B=P.length>0?P:F.length>0?F:["#3b82f6"],z=R.length>0?R:B.length>0?B:["#111827"],U=OD({metricKey:d,metricIndex:0,preferences:r,backgroundPalette:B,borderPalette:z}),O=OD({metricKey:h||`${d}__target`,metricIndex:1,preferences:r,backgroundPalette:B,borderPalette:z}).borderColor||U.borderColor||"#111827",K=OD({metricKey:p,metricIndex:2,preferences:r,backgroundPalette:B,borderPalette:z}),q=w?FRe(y,T,_,x,I):[],M=PRe(y,U,_,d),G=ORe(y,K,_,p),L=[...q,M];G&&L.push(G);let $=LRe({orientation:_,chartMax:C,formatConfig:j,series:y,preferences:D,rangeLabelMap:I,showRanges:w,card:o});const V=(ke=(xe=r==null?void 0:r.chartOptions)==null?void 0:xe.plugins)==null?void 0:ke.legend;$=pO($,V);const{plugins:H=[],options:A}=kd((r==null?void 0:r.customVisualCode)||""),W=KRe([$,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,A]),X=y.some(se=>se.target!=null)&&C>0?BRe({series:y,orientation:_,color:O}):null,Z={type:"bar",data:{labels:S,datasets:L},options:W,plugins:X?[...H,X]:H},J=Cv("bullet",r),re=(r==null?void 0:r.dataLabelsConfig)??J;return Z.options=Eg(Z.options||{},re,D,"bar",o),Z.options=jg.applyAxisConfig(Z.options||{},"bar",D,o),Z.options=Z.options||{},Z.options.indexAxis=E,Z}function TRe({data:e,dimensionKey:t,actualKey:n,targetKey:r,comparativeKey:s,bulletConfig:o}){const i=e.map(c=>{const u=ARe(c[t]),d=$S(c[n]),f=r&&c[r]!=null?$S(c[r]):(o==null?void 0:o.targetValue)??null,h=s&&c[s]!=null?$S(c[s]):null;return{label:u,actual:d,target:f,comparative:h,row:c}}),a=i.reduce((c,u)=>{var d;return Math.max(c,u.actual,u.target??0,u.comparative??0,((d=o==null?void 0:o.ranges)==null?void 0:d.good)??0)},0);return i.map(c=>{const u=MRe({row:c.row,actual:c.actual,target:c.target,globalMax:a||c.actual||1,bulletConfig:o});return{label:c.label,actual:c.actual,target:c.target??void 0,comparative:c.comparative??void 0,ranges:u,actualKey:n,targetKey:r||void 0,comparativeKey:s||void 0}})}function MRe({row:e,actual:t,target:n,globalMax:r,bulletConfig:s}){const o=s==null?void 0:s.rangeKeys,i=s==null?void 0:s.ranges,a=Math.max(t,n??0,r),c={poor:PD("poor",e,o,i,a*.5,s,a),satisfactory:PD("satisfactory",e,o,i,a*.8,s,a),good:PD("good",e,o,i,a,s,a)};let u=0;return qJ.forEach(d=>{const f=c[d];if(!Number.isFinite(f)||f<0){c[d]=u;return}f<u?c[d]=u:u=f}),c}function PD(e,t,n,r,s,o,i){const a=n==null?void 0:n[e];if(a&&t[a]!=null)return $S(t[a]);if((r==null?void 0:r[e])!=null){const c=r[e];return o!=null&&o.rangesArePercentages?c*i:c}return s}function $S(e){const t=Number(e);return Number.isFinite(t)?t:0}function ARe(e){return e==null||e===""?"(Blank)":String(e)}function RRe(e,t){const n=e.reduce((r,s)=>{const o=[r,s.actual,s.target??0,s.comparative??0];return t&&o.push(s.ranges.good),Math.max(...o)},0);return n>0?n*1.1:1}function FRe(e,t,n,r,s){const o=[];return qJ.forEach((i,a)=>{const c=[],u=e.map(f=>{const h=f.ranges[i];return c.push({start:0,end:h}),h}),d={type:"bar",label:s[i],data:u,order:10,backgroundColor:YRe(t[a]??t[t.length-1],.35,r),borderWidth:0,borderSkipped:!1,barPercentage:n==="vertical"?.9:.85,categoryPercentage:.9,grouped:!1,datalabels:{display:!1},customRole:"range",rangeMeta:c};o.push(d)}),o}function PRe(e,t,n,r){return{type:"bar",label:r||"Actual",data:e.map(s=>s.actual),order:1,backgroundColor:t.backgroundColor,borderColor:t.borderColor,borderRadius:n==="vertical"?{topLeft:4,topRight:4,bottomLeft:0,bottomRight:0}:4,barPercentage:n==="vertical"?.6:.4,categoryPercentage:.6,grouped:!1,stack:"actual",base:0,customRole:"actual"}}function ORe(e,t,n,r){return e.some(s=>s.comparative!=null)?{type:"bar",label:r||"Comparative",data:e.map(s=>s.comparative??null),order:2,borderColor:t.borderColor,backgroundColor:"transparent",borderWidth:2,borderSkipped:!1,barPercentage:n==="vertical"?.6:.4,categoryPercentage:.6,grouped:!1,stack:"comparative",base:0,datalabels:{display:!1},customRole:"comparative"}:null}function LRe({orientation:e,chartMax:t,formatConfig:n,series:r,preferences:s,rangeLabelMap:o,showRanges:i,card:a}){var h,p,g,b,x,y,S,w,C;const c={type:"linear",stacked:!1,beginAtZero:!0,suggestedMax:t,ticks:{callback:N=>Fn(Number(N),n.format,n.options)},grid:{drawOnChartArea:!0}},u={type:"category",stacked:!0,grid:{display:!1}};return{responsive:!0,maintainAspectRatio:!1,scales:{x:e==="vertical"?u:c,y:e==="vertical"?c:u},plugins:{legend:{display:((g=(p=(h=s==null?void 0:s.chartOptions)==null?void 0:h.plugins)==null?void 0:p.legend)==null?void 0:g.display)??!0,position:((y=(x=(b=s==null?void 0:s.chartOptions)==null?void 0:b.plugins)==null?void 0:x.legend)==null?void 0:y.position)??"top",align:((C=(w=(S=s==null?void 0:s.chartOptions)==null?void 0:S.plugins)==null?void 0:w.legend)==null?void 0:C.align)??"center"},tooltip:{filter:N=>{const k=N.dataset.customRole;return k?k!=="range":!0},callbacks:$Re(r,n,o,i,s,a)}},indexAxis:e==="vertical"?"x":"y"}}function $Re(e,t,n,r,s,o){const i=(a,c)=>{var f;const u=ed(o,{columnId:c,metricAlias:c}),d=WP({card:o,chartType:"bar",preferences:s,metric:u,axis:((f=s==null?void 0:s.chartOptions)==null?void 0:f.indexAxis)==="y"?"x":"y"}).formatOptions;return d!=null&&d.type&&d.type!=="auto"?Fn(a,d.type,d):Fn(a,t.format,t.options)};return{title:a=>{var c;return a.length?((c=e[a[0].dataIndex])==null?void 0:c.label)??"":""},label:a=>{const c=e[a.dataIndex];return c?`${c.actualKey||"Actual"}: ${i(c.actual,c.actualKey)}`:a.formattedValue},afterBody:a=>{if(!a.length)return[];const c=e[a[0].dataIndex];if(!c)return[];const u=[];if(c.target!=null){const h=i(c.target,c.targetKey),p=c.actual-c.target,g=i(p,c.actualKey),b=c.targetKey||"Target";u.push(`${b}: ${h} (${g})`)}const d=zRe(c,n);r&&d&&u.push(`Range: ${d}`);const f=c.comparative;return f!=null&&u.push(`Comparative: ${i(f,c.comparativeKey)}`),u}}}function zRe(e,t){const{actual:n,ranges:r}=e;return n<=r.poor?`${t.poor} (≤ ${r.poor.toLocaleString()})`:n<=r.satisfactory?`${t.satisfactory} (${r.poor.toLocaleString()} – ${r.satisfactory.toLocaleString()})`:`${t.good} (${r.satisfactory.toLocaleString()} – ${r.good.toLocaleString()})`}function BRe({series:e,orientation:t,color:n}){return{id:"bulletTargetMarkers",afterDatasetsDraw(r){const s=r.ctx,o=r.scales[t==="vertical"?"y":"x"],i=r.scales[t==="vertical"?"x":"y"];if(!o||!i)return;const a=r.config.data.datasets,c=a.findIndex(d=>d.customRole==="actual"),u=a.findIndex(d=>d.customRole==="range");s.save(),s.strokeStyle=n,s.lineWidth=2,e.forEach((d,f)=>{var x,y,S,w,C;if(d.target==null)return;const h=(x=r.data.labels)==null?void 0:x[f],p=((S=(y=r.getDatasetMeta(u>=0?u:c>=0?c:0))==null?void 0:y.data)==null?void 0:S[f])||((C=(w=r.getDatasetMeta(0))==null?void 0:w.data)==null?void 0:C[f]),g=p?t==="horizontal"?p.height??p.width??20:p.width??p.height??20:20,b=Math.max(Math.min(g/2,12),6);if(t==="horizontal"){const N=o.getPixelForValue(d.target),k=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(N,k-b),s.lineTo(N,k+b),s.stroke(),s.beginPath(),s.moveTo(N-4,k-b),s.lineTo(N+4,k-b),s.moveTo(N-4,k+b),s.lineTo(N+4,k+b),s.stroke()}else{const N=o.getPixelForValue(d.target),k=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(k-b,N),s.lineTo(k+b,N),s.stroke(),s.beginPath(),s.moveTo(k-b,N-4),s.lineTo(k-b,N+4),s.moveTo(k+b,N-4),s.lineTo(k+b,N+4),s.stroke()}}),s.restore()}}}function VRe(e,t,n){var a,c;const r=kg({card:t,chartType:"bar",axis:((a=e==null?void 0:e.chartOptions)==null?void 0:a.indexAxis)==="y"?"x":"y",preferences:e,axisConfig:((c=e==null?void 0:e.chartOptions)==null?void 0:c.indexAxis)==="y"?e==null?void 0:e.xAxisConfig:e==null?void 0:e.yAxisConfig}).formatOptions,s=ed(t,{columnId:n,metricAlias:n}),o=x_(s),i=r??o??(e==null?void 0:e.numberAxisFormat)??(e==null?void 0:e.formatNumber)??{};return{format:(r==null?void 0:r.type)||(o==null?void 0:o.type)||"number",options:i}}function HRe(e){return[...e?DRe:ERe]}function URe(e){var n,r,s;const t=(e==null?void 0:e.rangeLabels)||{};return{poor:((n=t.poor)==null?void 0:n.trim())||FD.poor,satisfactory:((r=t.satisfactory)==null?void 0:r.trim())||FD.satisfactory,good:((s=t.good)==null?void 0:s.trim())||FD.good}}function WRe(e){if(!e)return!1;const t=Object.values(e.rangeKeys||{}).some(r=>!!r),n=Object.values(e.ranges||{}).some(r=>r!=null);return t||n}function qRe(e,t,n){const r=YJ(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=yB(e),o=yB(t);if(!s||!o)return e;const i=Math.round(s.r+(o.r-s.r)*r),a=Math.round(s.g+(o.g-s.g)*r),c=Math.round(s.b+(o.b-s.b)*r);return GRe(i,a,c)}function YRe(e,t,n){return qRe(e,n?"#000000":"#ffffff",t)}function OD({metricKey:e,metricIndex:t,preferences:n,backgroundPalette:r,borderPalette:s}){var d,f;const o=r[t%r.length]||r[0]||"#3b82f6",i=s[t%s.length]||s[0]||o,a=e&&((f=(d=n==null?void 0:n.colorConfig)==null?void 0:d.segments)==null?void 0:f[e])||void 0;return{backgroundColor:a||o,borderColor:a||i}}function yB(e){const t=e.replace("#","");if(t.length!==6)return null;const n=parseInt(t,16);return{r:n>>16&255,g:n>>8&255,b:n&255}}function GRe(e,t,n){return`#${LD(e)}${LD(t)}${LD(n)}`}function LD(e){return YJ(Math.round(e),0,255).toString(16).padStart(2,"0")}function YJ(e,t,n){return Math.max(t,Math.min(n,e))}function KRe(e){return e.reduce((t,n)=>es(t,n||{}),{})}const YM={blue:{start:"#dbeafe",end:"#1d4ed8",label:"Blue"},green:{start:"#dcfce7",end:"#15803d",label:"Green"},purple:{start:"#ede9fe",end:"#6d28d9",label:"Purple"},orange:{start:"#ffedd5",end:"#c2410c",label:"Orange"}},GJ=["#dcfce7","#15803d"],b1={type:"matrix",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function ZRe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o,card:i}){var $,V,H;if(!Array.isArray(e)||e.length===0)return b1;const{dimensionKeys:a,metricKeys:c,keys:u}=pr(e),d=a[0]??u[0];if(!d)return b1;const f=a[1],h=u.find(A=>A!==d&&!c.includes(A)&&A!==f)??f,p=!f&&(!h||typeof(($=e[0])==null?void 0:$[h])!="string")&&c.length>1,g=c[0]??u.find(A=>A!==d&&A!==h);if(!g&&!p)return b1;const b=r==null?void 0:r.heatmapConfig,x=(b==null?void 0:b.legendPosition)??"bottom",y=p?QRe({data:e,dimensionKey:d,metricKeys:c}):XRe({data:e,xKey:d,yKey:h||g,metricKey:g});if(y.length===0)return b1;const S=p?c.map(Qm):$D(y.map(A=>A.x)),w=$D(p?e.map(A=>Qm(A==null?void 0:A[d])):y.map(A=>A.y)),C=JRe(y),N=o??m.useDashboardStore.getState().themeStyle,k=oFe({min:C.min,max:C.max,heatmapConfig:b,themeStyle:N}),_=eFe({points:y,xLabels:S,yLabels:w,fill:(b==null?void 0:b.fillMissingCells)!==!1}),E=uFe(r,i),j=["auto","number","currency","percent","none"].includes(E.format)?E.format:"auto",I=Cv("heatmap",r),T=I?{...I,format:I.format??j,formatOptions:I.formatOptions??E.options}:void 0,F=(r==null?void 0:r.dataLabelsConfig)??T,P=tFe({points:_,xLabels:S,yLabels:w,colorScale:k,datasetLabel:p?"Value":g||"Value",dataLabelPrefs:F,formatConfig:E,preferences:r,card:i}),R=nFe({xLabels:S,yLabels:w,heatmapConfig:b,formatConfig:E,themeStyle:N,legendPreferences:(H=(V=r==null?void 0:r.chartOptions)==null?void 0:V.plugins)==null?void 0:H.legend,cardType:s,legendPosition:x,preferences:r,card:i}),{plugins:B=[],options:z}=kd((r==null?void 0:r.customVisualCode)||""),U=dFe([R,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,z]),Y=(b==null?void 0:b.showLegend)===!1?null:iFe({stops:k.stops,min:C.min,max:C.max,formatConfig:E,position:x}),O={type:"matrix",data:{datasets:[P]},options:U,plugins:Y?[...B,Y]:B};O.options=Eg(O.options||{},F,r,"matrix",void 0);const K=fM(s??"heatmap","x"),q=fM(s??"heatmap","y"),M=hM(K,r==null?void 0:r.xAxisConfig),G=hM(q,r==null?void 0:r.yAxisConfig),L=M||G||r?{...r||{},...M?{xAxisConfig:M}:{},...G?{yAxisConfig:G}:{}}:r;return O.options=jg.applyAxisConfig(O.options||{},"heatmap",L,void 0),O}function XRe({data:e,xKey:t,yKey:n,metricKey:r}){const s=new Map;return e.forEach(o=>{const i=o==null?void 0:o[t],a=o==null?void 0:o[n];if(i===void 0||a===void 0)return;const c=Qm(i),u=Qm(a),d=`${c}__${u}`,f=KJ(o==null?void 0:o[r]);if(!s.has(d)){s.set(d,{x:c,y:u,v:f,raw:o});return}const h=s.get(d);h&&(h.v==null?h.v=f:f!=null&&(h.v+=f))}),Array.from(s.values())}function QRe({data:e,dimensionKey:t,metricKeys:n}){const r=[];return e.forEach(s=>{const o=s==null?void 0:s[t];if(o===void 0)return;const i=Qm(o);n.forEach(a=>{if(a===t)return;const c=KJ(s==null?void 0:s[a]),u=Qm(a);r.push({x:u,y:i,v:c,raw:{...s,_metricKey:a}})})}),r}function Qm(e){return e==null||e===""?"Unknown":String(e)}function KJ(e){const t=Number(e);return Number.isFinite(t)?t:null}function $D(e){const t=new Set,n=[];return e.forEach(r=>{t.has(r)||(t.add(r),n.push(r))}),n}function JRe(e){let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,r=!1;return e.forEach(s=>{s.v==null||s.v===0||(t=Math.min(t,s.v),n=Math.max(n,s.v),r=!0)}),r?{min:t,max:n}:{min:0,max:0}}function eFe({points:e,xLabels:t,yLabels:n,fill:r}){if(!r)return e;const s=new Map;e.forEach(i=>{s.set(`${i.x}__${i.y}`,i)});const o=[];return t.forEach(i=>{n.forEach(a=>{const c=`${i}__${a}`,u=s.get(c);u?o.push(u):o.push({x:i,y:a,v:null})})}),o}function tFe({points:e,xLabels:t,yLabels:n,colorScale:r,datasetLabel:s,dataLabelPrefs:o,formatConfig:i,preferences:a,card:c}){const u=OTe(e.length,o),d=Math.max(t.length||1,n.length||1);return{label:s,data:e,backgroundColor:h=>{const p=h==null?void 0:h.raw;return r.getColor((p==null?void 0:p.v)??null)},hoverBackgroundColor:h=>{const p=h==null?void 0:h.raw,g=r.getColor((p==null?void 0:p.v)??null);return cFe(g,.85)},borderWidth:1,borderColor:"rgba(255, 255, 255, 0.65)",width:({chart:h})=>{var p;return vB((p=h==null?void 0:h.chartArea)==null?void 0:p.width,t.length)},height:({chart:h})=>{var p;return vB((p=h==null?void 0:h.chartArea)==null?void 0:p.height,n.length)},datalabels:{display:u,anchor:"center",align:"center",formatter:h=>{let p=null,g;return typeof h=="number"?p=h:h&&typeof h=="object"&&"v"in h&&(g=h,p=Number(g.v)),p==null||Number.isNaN(p)?"":TO(p,QJ(g,i??{format:"number",options:{}},a,c))},color:h=>{const p=h==null?void 0:h.raw,g=r.getColor((p==null?void 0:p.v)??null)||"rgba(148,163,184,0.35)";return m.getContrastColor(lFe(g))},font:{size:Math.max(10,Math.min(14,120/d))}}}}function vB(e,t){return!e||t===0?0:Math.max(4,e/t-2)}function nFe({xLabels:e,yLabels:t,heatmapConfig:n,formatConfig:r,themeStyle:s,legendPreferences:o,cardType:i,legendPosition:a,preferences:c,card:u}){var b,x,y;const d=(n==null?void 0:n.showLegend)??!0,f=((y=(x=(b=s==null?void 0:s.chart)==null?void 0:b.options)==null?void 0:x.plugins)==null?void 0:y.tooltip)||{},h=mO(i??"heatmap"),p=UQ(h,o);return{responsive:!0,maintainAspectRatio:!1,layout:{padding:rFe(d,a)},plugins:{legend:p,tooltip:{...f,filter:S=>{const w=S==null?void 0:S.raw;return(w==null?void 0:w.v)!=null&&w.v!==0},callbacks:sFe(r,c,u)}},scales:{x:{type:"category",labels:e,offset:!0,grid:{display:!1},ticks:{autoSkip:!1}},y:{type:"category",labels:t,offset:!0,reverse:!1,grid:{display:!1},ticks:{autoSkip:!1}}}}}function rFe(e,t){const n={top:8,bottom:8,left:8,right:8};if(!e)return n;const r=36,s=48;switch(t){case"top":return{...n,top:n.top+r};case"bottom":return{...n,bottom:n.bottom+r};case"left":return{...n,left:n.left+s};case"right":return{...n,right:n.right+s};default:return n}}function sFe(e,t,n){return{title(r){var o;const s=(o=r==null?void 0:r[0])==null?void 0:o.raw;return s&&(s.y||s.x)||""},label(r){var c;const s=r==null?void 0:r.raw;if(!s||s.v==null)return"";const o=((c=r==null?void 0:r.dataset)==null?void 0:c.label)||s.x||"Value",i=s.x,a=TO(s.v,QJ(s,e,t,n));return i?`${i}: ${a}`:`${o}: ${a}`}}}function oFe({min:e,max:t,heatmapConfig:n,themeStyle:r}){var S,w;const s=((w=(S=r==null?void 0:r.chart)==null?void 0:S.dataset)==null?void 0:w.backgroundColor)||[],o=["#0ea5e9","#f97316"],i=(n==null?void 0:n.colorPalette)??"green",a=i!=="custom"?YM[i]??YM.blue:void 0,c=n==null?void 0:n.colorRange,u=c&&c[0]&&c[1]?c:a?[a.start,a.end]:i==="custom"?GJ:void 0,d=(u==null?void 0:u[0])??s[0]??o[0],f=(u==null?void 0:u[1])??s[1]??o[1],h=(n==null?void 0:n.colorMode)??"continuous",p=Math.max(3,(n==null?void 0:n.steps)??5),g=(n==null?void 0:n.nullFillColor)??"rgba(148, 163, 184, 0.25)",b=Math.max(t-e,Number.EPSILON),x=h==="continuous"?[{offset:0,color:Wd(d)},{offset:1,color:Wd(f)}]:Array.from({length:p}).map((C,N)=>{const k=p===1?0:N/(p-1||1);return{offset:k,color:wB(Wd(d),Wd(f),k)}}),y=h==="continuous"?null:x.map(C=>C.color);return{getColor(C){if(C==null||C===0)return g;if(h==="continuous"){const _=Jy((C-e)/b,0,1);return wB(Wd(d),Wd(f),_)}const N=Jy((C-e)/b,0,1),k=Math.min(p-1,Math.max(0,Math.floor(N*p)));return(y==null?void 0:y[k])??Wd(d)},stops:x}}function iFe({stops:e,min:t,max:n,formatConfig:r,position:s}){if(!e||e.length===0)return null;const o=i=>TO(i,r);return{id:"heatmapLegend",afterDraw(i){var g,b,x,y;const{ctx:a,chartArea:c}=i;if(!a||!c)return;a.save();const u=((y=(x=(b=(g=i.options)==null?void 0:g.plugins)==null?void 0:b.legend)==null?void 0:x.labels)==null?void 0:y.font)||{},d=u.size??12,f=u.family??"sans-serif",h=m.getContrastColor(m.getCanvasBackgroundColor(i.canvas)),p=24;if(a.font=`${d}px ${f}`,a.fillStyle=h,s==="bottom"||s==="top"){const w=c.left,C=c.right,N=s==="bottom"?c.bottom+p/2:c.top-10-p/2,k=a.createLinearGradient(w,0,C,0);e.forEach(E=>k.addColorStop(E.offset,E.color)),a.fillStyle=k,a.fillRect(w,N,C-w,10),a.fillStyle=h,a.textAlign="left",a.textBaseline=s==="bottom"?"top":"bottom";const _=s==="bottom"?N+10+4:N-4;a.fillText(o(t),w,_),a.textAlign="center",a.fillText(o(t+(n-t)/2),(w+C)/2,_),a.textAlign="right",a.fillText(o(n),C,_)}else{const w=c.top,C=c.bottom,N=s==="left"?c.left-10-p/2:c.right+p/2,k=a.createLinearGradient(0,w,0,C);e.forEach(E=>k.addColorStop(E.offset,E.color)),a.fillStyle=k,a.fillRect(N,w,10,C-w),a.fillStyle=h,a.textAlign=s==="left"?"right":"left",a.textBaseline="middle";const _=s==="left"?N-6:N+10+6;a.fillText(o(n),_,w),a.fillText(o(t+(n-t)/2),_,(w+C)/2),a.fillText(o(t),_,C)}a.restore()}}}function Wd(e){if(!e)return"#3b82f6";if(e.startsWith("rgb"))return e;if(e.startsWith("#")){const t=ZJ(e);return t?aFe(t.r,t.g,t.b,1):e}return e}function wB(e,t,n){const r=iN(e),s=iN(t);if(!r||!s)return e;const o=Jy(n,0,1),i=Math.round(r.r+(s.r-r.r)*o),a=Math.round(r.g+(s.g-r.g)*o),c=Math.round(r.b+(s.b-r.b)*o),u=r.a+(s.a-r.a)*o;return`rgba(${i}, ${a}, ${c}, ${u})`}function iN(e){if(e.startsWith("#")){const n=ZJ(e);return n?{...n,a:1}:null}const t=/rgba?\((?<r>\d+),\s*(?<g>\d+),\s*(?<b>\d+)(?:,\s*(?<a>[0-9.]+))?\)/i.exec(e);return!t||!t.groups?null:{r:Number(t.groups.r),g:Number(t.groups.g),b:Number(t.groups.b),a:t.groups.a!==void 0?Number(t.groups.a):1}}function ZJ(e){const t=e.replace("#","");if(![3,6].includes(t.length))return null;const n=t.length===3?t.split("").map(i=>i+i).join(""):t,r=parseInt(n.slice(0,2),16),s=parseInt(n.slice(2,4),16),o=parseInt(n.slice(4,6),16);return{r,g:s,b:o}}function aFe(e,t,n,r){return`rgba(${e}, ${t}, ${n}, ${r})`}function lFe(e){const t=iN(e);return t?`#${zD(t.r)}${zD(t.g)}${zD(t.b)}`:"#000000"}function zD(e){return Jy(Math.round(e),0,255).toString(16).padStart(2,"0")}function cFe(e,t){const n=iN(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${Jy(t,0,1)})`:e}function Jy(e,t,n){return Math.min(n,Math.max(t,e))}function TO(e,t){return e==null||Number.isNaN(e)?"—":t.rawValue?String(e):Fn(e,t.format,t.options)}function uFe(e,t){const n=bv({card:t,chartType:"heatmap",preferences:e,dataLabelsConfig:e==null?void 0:e.dataLabelsConfig});return XJ(n)}function XJ(e){const t=e.formatOptions||{};return _g(e)?{format:"number",options:{},rawValue:!0}:{format:t.type||"number",options:t}}function QJ(e,t,n,r){var i;const s=(i=e==null?void 0:e.raw)==null?void 0:i._metricKey;if(!s||!r)return t;const o=ed(r,{columnId:s,metricAlias:s});return o?XJ(AX({preferences:n,dataLabelsConfig:n==null?void 0:n.dataLabelsConfig,metric:o})):t}function dFe(e){return e.reduce((t,n)=>n?xl({},t,n):t,{})}function GM(){return{enabled:!0,position:"right",labels:{enabled:!0,rotation:"auto"},name:{enabled:!1}}}function fFe(e){return Array.from({length:e},(t,n)=>({idx:n,type:"bar",yAxisId:"y"}))}function hFe(e){return!e||e.length===0?!1:e.some(t=>t.yAxisId==="y2")}function pFe(e,t){var r,s,o,i,a,c,u,d,f,h,p,g,b,x;if(!t)return e||GM();const n=GM();return{...e,...t,name:{enabled:((r=t==null?void 0:t.name)==null?void 0:r.enabled)??((s=e==null?void 0:e.name)==null?void 0:s.enabled)??((o=n.name)==null?void 0:o.enabled)??!1,text:((i=t==null?void 0:t.name)==null?void 0:i.text)??((a=e==null?void 0:e.name)==null?void 0:a.text),fontSize:((c=t==null?void 0:t.name)==null?void 0:c.fontSize)??((u=e==null?void 0:e.name)==null?void 0:u.fontSize),fontWeight:((d=t==null?void 0:t.name)==null?void 0:d.fontWeight)??((f=e==null?void 0:e.name)==null?void 0:f.fontWeight)},labels:{enabled:((h=t==null?void 0:t.labels)==null?void 0:h.enabled)??((p=e==null?void 0:e.labels)==null?void 0:p.enabled)??((g=n.labels)==null?void 0:g.enabled)??!0,rotation:((b=t==null?void 0:t.labels)==null?void 0:b.rotation)??((x=e==null?void 0:e.labels)==null?void 0:x.rotation)},scale:{...e==null?void 0:e.scale,...t==null?void 0:t.scale},formatOptions:{...e==null?void 0:e.formatOptions,...t==null?void 0:t.formatOptions}}}function mFe(e,t){const n=fFe(t);return!e||e.length===0?n:n.map(r=>{const s=e.find(o=>o.idx===r.idx);return s?{...r,...s,type:s.type||r.type,yAxisId:s.yAxisId||r.yAxisId}:r})}function gFe(e,t,n,r){const s=n==null?void 0:n.yAxisConfig,o=n==null?void 0:n.secondaryYAxisConfig,i=n==null?void 0:n.dataLabelsConfig;return e.map((a,c)=>{const u=t.find(b=>b.idx===c),d={...a},f=(u==null?void 0:u.type)||"bar";d.type=f;const h=(u==null?void 0:u.fill)!==void 0&&(u==null?void 0:u.fill)!=="";if(f==="line"){if(d.borderWidth=d.borderWidth??2,d.tension=d.tension??.1,d.pointRadius=(u==null?void 0:u.pointRadius)??3,d.pointStyle=(u==null?void 0:u.pointStyle)??"circle",d.pointHoverRadius=(u==null?void 0:u.pointHoverRadius)??((u==null?void 0:u.pointRadius)??3)+2,d.borderDash=IO(u==null?void 0:u.lineStyle),h){const b=d.borderColor||d.backgroundColor;b&&typeof b=="string"&&(d.backgroundColor=WJ(b,.3)),d.fill=u.fill}d.order=0}else d.order=1;u!=null&&u.yAxisId&&(d.yAxisID=u.yAxisId);const p=(u==null?void 0:u.yAxisId)==="y2"?o:s,g=A_(i,u==null?void 0:u.dataLabels);if(g){const b=xv({card:r,preferences:n,dataLabelsConfig:g,datasetIndex:c,datasetLabel:a.label}).formatOptions;d.datalabels=T_(g,p,f==="line"?"line":"bar",b)}return d})}function bFe(e,t,n){var s,o,i,a;const r={...e,x:{...e==null?void 0:e.x,display:!0},y:{...e==null?void 0:e.y,display:!0,position:"left"}};if(t){const c=pFe(GM(),n==null?void 0:n.secondaryYAxisConfig);r.y2={...e==null?void 0:e.y2,type:"linear",display:c.enabled!==!1,position:c.position||"right",grid:{...(s=e==null?void 0:e.y2)==null?void 0:s.grid,drawOnChartArea:!1},ticks:{...(o=e==null?void 0:e.y2)==null?void 0:o.ticks,display:((i=c.labels)==null?void 0:i.enabled)!==!1},title:(a=c.name)!=null&&a.enabled?{display:!0,text:c.name.text||"",font:{size:c.name.fontSize||12,weight:c.name.fontWeight||"normal"}}:void 0},c.scale&&(c.scale.min!==void 0&&c.scale.min!=="auto"&&(r.y2.min=c.scale.min),c.scale.max!==void 0&&c.scale.max!=="auto"&&(r.y2.max=c.scale.max),c.scale.stepSize!==void 0&&c.scale.stepSize!=="auto"&&(r.y2.ticks={...r.y2.ticks,stepSize:c.scale.stepSize}))}return r}function xFe({card:e,data:t,cfg:n,customCfg:r,preferences:s}){var C,N;const{keys:o}=pr(t),i=Oy(o),a=i.length,c=mFe(s==null?void 0:s.datasetOptions,a),u=hFe(c),d=o==null?void 0:o[0],f=Qc(t,d),h=Ng(i,t,s,1,"none",d,!1,Cg(t)),p=gFe(h,c,s,e),g=Da(p,r),{options:b,plugins:x}=sd({cardType:"combo",cfg:n,preferences:s,customCfg:r,card:e}),y=bFe(b==null?void 0:b.scales,u,s),S={...b,scales:y},w=(((N=(C=e.interactionConfig)==null?void 0:C.interactions)==null?void 0:N.length)??0)>0;return M_(S,w),{type:"bar",data:{labels:f,datasets:g},options:S,plugins:x}}function yFe(e,t,n,r,s){const o=n==null?void 0:n.lineStyleConfig,i=n==null?void 0:n.yAxisConfig,a=(r==null?void 0:r.some(c=>c._forecast))??!1;return e.map((c,u)=>{const d=t.find(g=>g.idx===u),f={...c};f.type="line",f.fill=!1,f.borderWidth=f.borderWidth??2,f.tension=f.tension??.1;const h=(d==null?void 0:d.pointRadius)??(o==null?void 0:o.pointRadius)??3;f.pointRadius=h,f.pointStyle=(d==null?void 0:d.pointStyle)??(o==null?void 0:o.pointStyle)??"circle",f.pointHoverRadius=(d==null?void 0:d.pointHoverRadius)??h+2,f.borderDash=IO((d==null?void 0:d.lineStyle)??(o==null?void 0:o.lineStyle)),a&&r&&vFe(f,r,c.borderColor);const p=A_(n==null?void 0:n.dataLabelsConfig,d==null?void 0:d.dataLabels);if(p){const g=xv({card:s,preferences:n,dataLabelsConfig:p,datasetIndex:u,datasetLabel:c.label}).formatOptions;f.datalabels=T_(p,i,"line",g)}return f})}function vFe(e,t,n){const r=m.useDashboardStore.getState().theme==="dark";e.segment={borderDash:s=>{var a;const o=s.p0DataIndex;return((a=t[o])==null?void 0:a._forecast)?[2,4]:void 0},borderColor:s=>{var i;return((i=t[s.p0DataIndex])==null?void 0:i._forecast)?r?"white":"black":n}},e.pointBackgroundColor=s=>{var i;return((i=t[s.dataIndex])==null?void 0:i._forecast)?r?"white":"gray":e.borderColor},e.pointBorderColor=s=>{var i;return((i=t[s.dataIndex])==null?void 0:i._forecast)?r?"white":"gray":e.borderColor}}function wFe(e){var t,n;return{...e,x:{...e==null?void 0:e.x,display:((t=e==null?void 0:e.x)==null?void 0:t.display)??!0},y:{...e==null?void 0:e.y,display:((n=e==null?void 0:e.y)==null?void 0:n.display)??!0}}}function SFe({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var w,C;const{keys:i}=pr(t),a=Oy(i),c=(s==null?void 0:s.datasetOptions)||[],u=i==null?void 0:i[0],d=Qc(t,u),f=Ng(a,t,s,1,"none",u,!1,Cg(t)),h=yFe(f,c,s,t,e),p=Da(h,r),{options:g,plugins:b}=sd({cardType:o||"line",cfg:n,preferences:s,customCfg:r,card:e}),x=wFe(g==null?void 0:g.scales),y={...g,scales:x},S=(((C=(w=e.interactionConfig)==null?void 0:w.interactions)==null?void 0:C.length)??0)>0;return M_(y,S),{type:"line",data:{labels:d,datasets:p},options:y,plugins:b}}function CFe(e,t,n,r,s,o){const i=n==null?void 0:n.barStyleConfig,a=s==="horizontalBar"?n==null?void 0:n.xAxisConfig:n==null?void 0:n.yAxisConfig,c=(r==null?void 0:r.some(u=>u._forecast))??!1;return e.map((u,d)=>{const f=t.find(g=>g.idx===d),h={...u};h.borderRadius=(f==null?void 0:f.borderRadius)??(i==null?void 0:i.borderRadius)??0,h.borderWidth=(f==null?void 0:f.barBorderWidth)??(i==null?void 0:i.borderWidth)??0,h.barPercentage=(f==null?void 0:f.barPercentage)??(i==null?void 0:i.barPercentage)??.9,h.categoryPercentage=(f==null?void 0:f.categoryPercentage)??(i==null?void 0:i.categoryPercentage)??.8,c&&r&&NFe(h,r,u.backgroundColor);const p=A_(n==null?void 0:n.dataLabelsConfig,f==null?void 0:f.dataLabels);if(p){const g=s==="horizontalBar"?"horizontalBar":"bar",b=xv({card:o,preferences:n,dataLabelsConfig:p,datasetIndex:d,datasetLabel:u.label}).formatOptions;h.datalabels=T_(p,a,g,b)}return h})}function NFe(e,t,n){const r=n;e.backgroundColor=s=>{var i;return((i=t[s.dataIndex])==null?void 0:i._forecast)?r+"20":r}}function kFe(e,t,n=!1){var o,i;const r=t==="horizontalBar",s=t==="stackedBar";return{...e,x:{...e==null?void 0:e.x,display:((o=e==null?void 0:e.x)==null?void 0:o.display)??!0,...s&&{stacked:!n}},y:{...e==null?void 0:e.y,display:((i=e==null?void 0:e.y)==null?void 0:i.display)??!0,...s&&{stacked:!0}},...r&&{}}}function _Fe(e){return e==="horizontalBar"?"y":void 0}function BD({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var j,I,T,F;let i=t;const{keys:a}=pr(i),c=Oy(a),u=(s==null?void 0:s.datasetOptions)||[],d=a==null?void 0:a[0],f=Cg(i),h=o==="stackedBar",p=((j=e.config)==null?void 0:j.pivotByColumns)&&e.config.pivotByColumns.length>0,g=((I=e.config)==null?void 0:I.groupByColumns)&&e.config.groupByColumns.length>0;h&&!f&&(!p||!g)&&(i=gv({dataArray:i,groupKey:a[0],pivotKey:a[1],valueKey:a[2],sortChart:s==null?void 0:s.sortChart}));const b=Qc(i,d),x=Ng(h?Oy(pr(i).keys):c,i,s,1,"none",d,h,f),y=CFe(x,u,s,i,o,e),S=Da(y,r),{options:w,plugins:C}=sd({cardType:o||"bar",cfg:n,preferences:s,customCfg:r,card:e}),N=o||"bar",k=kFe(w==null?void 0:w.scales,N,f),_=_Fe(N),E={...w,scales:k,..._&&{indexAxis:_}},D=(((F=(T=e.interactionConfig)==null?void 0:T.interactions)==null?void 0:F.length)??0)>0;return M_(E,D),{type:"bar",data:{labels:b,datasets:S},options:E,plugins:C}}function Ag({card:e,data:t,cardType:n="bar",cfg:r,customCfg:s,provider:o="chartjs",userSettings:i,preferences:a,topoJson:c,queryConfig:u,isDevMode:d}){var x,y,S,w,C,N,k,_;const f=e.config,h=d??!!e.sql;let p=t;const g=f&&f.pivotByColumns&&f.pivotByColumns.length>0,b=f&&f.groupByColumns&&f.groupByColumns.length>0;if(g&&b&&(p=w_e(t,(f==null?void 0:f.metricColumns)||[])),n==="map"){if(!c)return null;const E=(x=a==null?void 0:a.mapVisualOptions)==null?void 0:x.objectKey;if(!E)return null;const D=IAe(c,(y=c==null?void 0:c.objects)==null?void 0:y[E]).features;if(!D)return null;const j={plugins:{datalabels:{display:!1}},scales:{x:{display:!1,grid:{display:!1}},y:{display:!1,grid:{display:!1}},projection:{axis:"x",projection:((S=a==null?void 0:a.mapVisualOptions)==null?void 0:S.projection)||"mercator",projectionScale:((w=a==null?void 0:a.mapVisualOptions)==null?void 0:w.projectionScale)||1,projectionOffset:((C=a==null?void 0:a.mapVisualOptions)==null?void 0:C.projectionOffset)||[0,0]},color:{axis:"x",interpolate:((N=a==null?void 0:a.mapVisualOptions)==null?void 0:N.colorScale)||"blues",quantize:5,legend:{position:"bottom-right",align:"right"}}}},{keys:I}=pr(p),T=D.map(U=>{var q;const Y=I==null?void 0:I[0],O=I==null?void 0:I[1],K=(q=p.find(M=>(M==null?void 0:M[Y])===U.properties.NAME||(M==null?void 0:M[Y])===U.properties.name))==null?void 0:q[O];return{feature:U,value:K}}),P=Da([{label:E,data:T,borderColor:"lightgray"}],s),R={type:"choropleth",data:{labels:D.map(U=>U.properties.NAME||U.properties.name),datasets:P},options:j},{options:B}=sd({cfg:R,preferences:a,customCfg:s,cardType:n});return{...R,options:B}}if(n==="bar")return BD({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="horizontalBar")return BD({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="funnel")return oRe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="tornado"||n==="pyramid")return lRe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="treemap")return cRe({data:p,cfg:r,customCfg:s,preferences:a,card:e});if(n==="heatmap")return ZRe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="bullet")return IRe({data:p,cfg:r,customCfg:s,preferences:a,card:e});if(n==="stackedBar")return BD({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="stackedLine"){const E=Cg(p),D=$Ae(r,n,E),{keys:j}=pr(p);return!E&&(!g||!b)&&(p=gv({dataArray:p,groupKey:j[0],pivotKey:j[1],valueKey:j[2],sortChart:a==null?void 0:a.sortChart})),jD({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}if(n==="line")return SFe({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="area"||n==="stackedArea")return jRe({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="combo")return xFe({card:e,data:p,cfg:r,customCfg:s,preferences:a});if(n==="range")return iRe({data:p,cfg:r,customCfg:s,preferences:a,card:e});if(n==="pie"||n==="doughnut"||n==="polarArea"){const E=zAe(n,r),{keys:D}=pr(p),j=D.slice(0,1),I=D.slice(1),T=PZ(I,p,a,j==null?void 0:j[0]),F=Da(T,s),{plugins:P,options:R}=kd((a==null?void 0:a.customVisualCode)||""),B=j[0],z=Qc(p,B),U=es((E==null?void 0:E.options)||{},(s==null?void 0:s.options)||{}),Y=es(U,(a==null?void 0:a.chartOptions)||{}),O=(A,W=0,X)=>{const Z=zy({card:e,datasetIndex:W,datasetLabel:X}),J=v_({preferences:a,metric:Z}).formatOptions;return By({value:A,formatOptions:J,preferences:a})},K=(A,W=0,X)=>{const Z=zy({card:e,datasetIndex:W,datasetLabel:X});return By({value:A,formatOptions:x_(Z),preferences:a})},q=(A,W=0,X)=>{const Z=xv({card:e,preferences:a,dataLabelsConfig:a==null?void 0:a.dataLabelsConfig,datasetIndex:W,datasetLabel:X}),J=Z.formatOptions;return _g(Z)?String(A):J!=null&&J.type&&J.type!=="auto"?Fn(A,J.type,J):O(A,W,X)},M={...Y,plugins:{...Y.plugins,datalabels:{...(k=Y.plugins)==null?void 0:k.datalabels,formatter:(A,W)=>{var X;return q(Number(A),(W==null?void 0:W.datasetIndex)??0,(X=W==null?void 0:W.dataset)==null?void 0:X.label)}},tooltip:{...(_=Y.plugins)==null?void 0:_.tooltip,callbacks:{label:function(A){var fe;A.dataset.label;const X=A.dataset.data.reduce((de,Se)=>de+Se,0),Z=A.parsed,J=O(Number(Z),A.datasetIndex,(fe=A.dataset)==null?void 0:fe.label),re=(Z/X*100).toFixed(2);return J+` (${re}%)`},footer:function(A){var X,Z,J,re;return(((Z=(X=e==null?void 0:e.interactionConfig)==null?void 0:X.drillHierarchies)==null?void 0:Z.length)??0)>0||(((re=(J=e==null?void 0:e.interactionConfig)==null?void 0:J.interactions)==null?void 0:re.some(fe=>fe.mode==="drillDown"||fe.mode==="drillToDetail"||fe.mode==="drillThrough"||fe.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},G=es(Y,M),{options:L}=sd({cfg:{options:G},preferences:a,customCfg:s,cardType:n,card:e}),$=es(L,R);return{type:n,data:{labels:z,datasets:F},options:$,plugins:[n==="doughnut"?{id:"doughnutLabel",beforeDatasetsDraw:function(A,W,X){var xe,ke;const{ctx:Z,data:J}=A;Z.save();const re=A.getDatasetMeta(0).data[0].x,fe=A.getDatasetMeta(0).data[0].y,de=m.getContrastColor(m.getCanvasBackgroundColor(A.canvas)),Se=window.getComputedStyle(Z.canvas).fontFamily;Z.font=`1em ${Se}`,Z.fontWeight="bolder",Z.fillStyle=de,Z.textAlign="center",Z.textBaseline="middle";const ue=J.datasets[0].data.reduce((se,be)=>se+be,0),ve=K(Number(ue),0,(ke=(xe=J.datasets)==null?void 0:xe[0])==null?void 0:ke.label);Z.fillText(ve,re,fe)}}:"",...P]}}if(n==="radar"){const E=BAe(r);return jD({card:e,data:p,cfg:E,customCfg:s,cardType:n,preferences:a})}return n==="bubble"||n==="scatter"?UAe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,cardConfig:f,isDevMode:h,card:e}):jD({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a})}function jFe({chart:e,elementIndex:t,datasetIndex:n,cardType:r,cfg:s,apply:o}){const i=m.useDashboardStore.getState().theme;if(!s)return;const a=i==="dark"?"rgb(238,238,238,0.2)":"rgb(238,238,238,0.8)";["bar","line","horizontalBar","bubble","scatter"].includes(r)&&DFe(e,t,s,o,a),["pie","doughnut","polarArea","funnel"].includes(r)&&IFe(e,t,s,o,a),["stackedBar","pyramid"].includes(r)&&EFe({chart:e,elementIndex:t,datasetIndex:n,cfg:s,apply:o,blurColor:a})}function EFe(e){var a,c,u,d;const{chart:t,elementIndex:n,datasetIndex:r,cfg:s,apply:o,blurColor:i}=e;o?(c=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null||c.forEach((f,h)=>{var p,g;typeof f.backgroundColor=="string"&&(f.backgroundColor=new Array(f.data.length).fill(f.backgroundColor),f.borderColor=new Array(f.data.length).fill(f.borderColor)),f.backgroundColor=(p=f==null?void 0:f.backgroundColor)==null?void 0:p.map((b,x)=>x===n&&h===r?b:i),f.borderColor=(g=f==null?void 0:f.borderColor)==null?void 0:g.map((b,x)=>x===n&&h===r?b:i)}):(d=(u=t==null?void 0:t.data)==null?void 0:u.datasets)==null||d.forEach((f,h)=>{var p,g,b,x,y,S;f.backgroundColor=new Array(f.data.length).fill((b=(g=(p=s==null?void 0:s.data)==null?void 0:p.datasets)==null?void 0:g[h])==null?void 0:b.backgroundColor),f.borderColor=new Array(f.data.length).fill((S=(y=(x=s==null?void 0:s.data)==null?void 0:x.datasets)==null?void 0:y[h])==null?void 0:S.borderColor)}),t==null||t.update()}function DFe(e,t,n,r,s){var o,i,a,c;r?(i=(o=e==null?void 0:e.data)==null?void 0:o.datasets)==null||i.forEach(u=>{var d,f;typeof u.backgroundColor=="string"&&(u.backgroundColor=new Array(u.data.length).fill(u.backgroundColor),u.borderColor=new Array(u.data.length).fill(u.borderColor)),u.backgroundColor=(d=u==null?void 0:u.backgroundColor)==null?void 0:d.map((h,p)=>p===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,p)=>p===t?h:s)}):(c=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||c.forEach((u,d)=>{var f,h,p,g,b,x;u.backgroundColor=new Array(u.data.length).fill((p=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:p.backgroundColor),u.borderColor=new Array(u.data.length).fill((x=(b=(g=n==null?void 0:n.data)==null?void 0:g.datasets)==null?void 0:b[d])==null?void 0:x.borderColor)}),e==null||e.update()}function IFe(e,t,n,r,s){var o,i,a,c;r?(i=(o=e==null?void 0:e.data)==null?void 0:o.datasets)==null||i.forEach(u=>{var d,f;u.backgroundColor=(d=u==null?void 0:u.backgroundColor)==null?void 0:d.map((h,p)=>p===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,p)=>p===t?h:s)}):(c=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||c.forEach((u,d)=>{var f,h,p,g,b,x,y,S;typeof u.backgroundColor=="string"&&(u.backgroundColor=(p=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:p.backgroundColor,u.borderColor=(x=(b=(g=n==null?void 0:n.data)==null?void 0:g.datasets)==null?void 0:b[d])==null?void 0:x.borderColor),u.backgroundColor=(y=u==null?void 0:u.backgroundColor)==null?void 0:y.map((w,C)=>{var N;return(N=n.data.datasets[d].backgroundColor)==null?void 0:N[C]}),u.borderColor=(S=u==null?void 0:u.borderColor)==null?void 0:S.map((w,C)=>{var N;return(N=n.data.datasets[d].borderColor)==null?void 0:N[C]})}),e==null||e.update()}function TFe({card:e,data:t,datasetIndex:n,clickIndex:r,value:s}){var o,i,a,c,u,d,f;try{if(!t)return;const{keys:h}=pr(t);if(e.type==="map"){const p=h[0],g=((i=(o=s==null?void 0:s.feature)==null?void 0:o.properties)==null?void 0:i.name)||((c=(a=s==null?void 0:s.feature)==null?void 0:a.properties)==null?void 0:c.NAME);return[{columnName:p,columnValue:g}]}if(["bar","horizontalBar","line","pie","doughnut","radar","polarArea","funnel"].includes(e.type)){const p=h[0],g=h.slice(1),b=(u=t[r])==null?void 0:u[p];return[{columnName:p,columnValue:b,metric:g[n],value:s}]}if(["stackedBar","pyramid"].includes(e.type)){const p=gv({dataArray:t,groupKey:h[0],pivotKey:h[1],valueKey:h[2]}),g=h[0],b=(d=p[r])==null?void 0:d[g],x=h[1],{keys:y}=pr(p),w=y.slice(1)[n];return[{columnName:g,columnValue:b,metric:h[2],value:s},{columnName:x,columnValue:w,metric:h[2],value:s}]}if(e.type==="bubble"||e.type==="scatter"){const p=h[0],g=(f=t[n])==null?void 0:f[p];return console.log(s,"bubble"),[{columnName:p,columnValue:g,metric1:h[1],value1:s.x,metric2:h[2],value2:s.y,metric3:h==null?void 0:h[3],value3:s==null?void 0:s.r}]}}catch(h){console.error("Error in getAdhocFilter",h)}}function kv(e){var a,c,u,d,f,h;const t=(((c=(a=e.preferences)==null?void 0:a.mapVisualOptions)==null?void 0:c.topoJsonUrl)==="custom"?(d=(u=e.preferences)==null?void 0:u.mapVisualOptions)==null?void 0:d.customTopoJsonUrl:(h=(f=e.preferences)==null?void 0:f.mapVisualOptions)==null?void 0:h.topoJsonUrl)||"",n=!!t&&e.type==="map",{data:r,isLoading:s,isFetching:o,isError:i}=On({queryKey:["topojson",t],queryFn:()=>fetch(t).then(p=>p.json()),enabled:n,staleTime:1/0});return{data:r,isLoading:s,isFetching:o,isError:i}}function MFe(e,t,n,r=s=>s){const s=r(e)||e,o=r(t)||t;if(s===o)return!0;const i=new Map;for(const u of n){const d=r(u.source.name)||u.source.name,f=r(u.target.name)||u.target.name;i.has(d)||i.set(d,new Set),i.get(d).add(f),i.has(f)||i.set(f,new Set),i.get(f).add(d)}const a=new Set,c=[s];for(a.add(s);c.length>0;){const u=c.shift(),d=i.get(u);if(d)for(const f of d){if(f===o)return!0;a.has(f)||(a.add(f),c.push(f))}}return!1}function sy(e){return(e==null?void 0:e.trim())||null}function AFe(e){const t=new Set,n=sy(e.table),r=sy(e.schema),s=sy(e.catalog);return n&&(t.add(n),r&&t.add(`${r}.${n}`),s&&t.add(`${s}.${n}`),s&&r&&t.add(`${s}.${r}.${n}`)),Array.from(t)}function RFe(e){const t=new Map;for(const r of e||[]){const s=sy(r.name);if(!s)continue;const o=new Set([s,...AFe(r)]);for(const i of o)t.has(i)||t.set(i,new Set),t.get(i).add(s)}const n=new Map;for(const[r,s]of t.entries())s.size===1&&n.set(r,Array.from(s)[0]);return n}function MO(e,t){var C,N,k,_,E,D,j,I;const{joinabilityMap:n,selectedFields:r,cardConfig:s,autoJoinMetadata:o,baseEntityName:i,datasetAliases:a}=t,c=RFe(a),u=T=>{const F=sy(T);if(F)return c.get(F)||F},d=u(e.entityName),f=r.some(T=>T.id&&e.id&&T.id===e.id?!0:u(T.entityName)===d&&T.name===e.name);if(!n)return{state:"draggable",isSelected:f};if(e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||Cr.isCalculatedField(e))return{state:"draggable",isSelected:f};const h=r.filter(T=>T.entityName!==Cr.CALCULATED_FIELD_ENTITY_MARKER&&!Cr.isCalculatedField(T));if(h.length===0)return{state:"draggable",tooltip:"Select to establish base dataset"};let p;const g=(N=(C=s==null?void 0:s.joinPlan)==null?void 0:C.baseEntity)==null?void 0:N.name,b=(_=(k=o==null?void 0:o.resolvedJoinPlan)==null?void 0:k.baseEntity)==null?void 0:_.name;if(g?p=g:b?p=b:i?p=i:p=[...new Set(h.map(F=>u(F.entityName)))].filter(F=>!!F)[0],p=u(p)||p,d===p)return{state:"base",tooltip:f?"Field already in query (base dataset)":"From base dataset",isSelected:f};const x=n[p];if(!x)return{state:"unreachable",tooltip:"No relationships defined for base dataset"};const y=x.canJoinTo.map(T=>u(T)).filter(Boolean);if(d&&y.includes(d))return{state:"draggable",tooltip:`Direct join from ${p}`,joinPath:[p,d],isSelected:f};const S=d&&((E=x.indirectJoins)==null?void 0:E[d])||((D=x.indirectJoins)==null?void 0:D[e.entityName]);if(S&&S.length>0){const T=[p,...S.map(F=>u(F)),d].filter(Boolean);return{state:"indirect",joinPath:T,tooltip:`Multi-hop join: ${T.join(" → ")}`,isSelected:f}}const w=d&&n[d]||n[e.entityName];if(w){if(w.canJoinTo.map(P=>u(P)).filter(Boolean).includes(p))return{state:"draggable",tooltip:`Direct join to ${p}`,joinPath:[d||e.entityName,p],isSelected:f};const F=(j=w.indirectJoins)==null?void 0:j[p];if(F&&F.length>0){const P=[d||e.entityName,...F.map(R=>u(R)),p].filter(Boolean);return{state:"indirect",joinPath:P,tooltip:`Multi-hop join: ${P.join(" → ")}`,isSelected:f}}}return(I=s==null?void 0:s.joinPlan)!=null&&I.joins&&s.joinPlan.joins.length>0&&MFe(p,e.entityName,s.joinPlan.joins,u)?{state:"draggable",tooltip:"Manual join configured",isSelected:f}:{state:"unreachable",tooltip:`Cannot join ${d||e.entityName} to ${p}`,isSelected:f}}function JJ(e,t,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:e===t||e===m.getQualifiedEntityName(n.baseEntity)||t===m.getQualifiedEntityName(n.baseEntity)?!0:n.joins.some(s=>{const o=m.getQualifiedEntityName(s.source),i=m.getQualifiedEntityName(s.target);return o===e&&i===t||o===t&&i===e})}function FFe(e,t,n){var u;const{joinPlan:r,joinabilityMap:s,semanticDomainId:o,datasetAliases:i}=n,a=t.filter(d=>d.entityName!==Cr.CALCULATED_FIELD_ENTITY_MARKER&&d.qualifiedEntityName!==m.CALCULATED_FIELDS_GROUP_NAME);if(a.length===0)return{isValid:!0};const c=a[0].qualifiedEntityName;if(!c)return{isValid:!0};if(c===e.qualifiedEntityName)return{isValid:!0};if(e.qualifiedEntityName){if(o&&s)return MO(e,{joinabilityMap:s,selectedFields:t,baseEntityName:(u=r==null?void 0:r.baseEntity)==null?void 0:u.name,datasetAliases:i}).state==="unreachable"?{isValid:!1,showError:!0}:{isValid:!0};if(!r)return{isValid:!1,showError:!0};if(!JJ(c,e.qualifiedEntityName,r))return{isValid:!1,showError:!0}}return{isValid:!0}}function eee(){ut.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function tee(e,t){return t.some(n=>{if(!(n.name===e.name&&n.qualifiedEntityName===e.qualifiedEntityName))return!1;if((e.role==="metric"||!e.role)&&n.role==="metric"){const s=e,o=n;if(s.aggregate!==o.aggregate||s.expression!==o.expression)return!1;if(s.parameters||o.parameters){const i=s.parameters||{},a=o.parameters||{},c=JSON.stringify(i),u=JSON.stringify(a);if(c!==u)return!1}return!1}return!0})}function PFe(e){if(e.role!=="metric")return e.label||e.name;const t=e,n=e.label||e.name;if(!t.parameters||!t.parameters.filters)return n;const r=t.parameters.filters;return typeof r=="string"?`${n} (${r})`:typeof r=="object"?(JSON.stringify(r),`${n} (Filtered)`):n}function OFe(e,t,n){const r=e.label||e.name,s=t.filter(o=>o.name===e.name&&o.qualifiedEntityName===e.qualifiedEntityName&&(o.role==="metric"||n==="metrics")).length;return s===0?r:`${r} (${s+1})`}const LFe=["SUM","COUNT","COUNTIF","AVG","MIN","MAX","MEDIAN","MODE","DISTINCT","STDDEV","STDDEV_POP","STDDEV_SAMP","VARIANCE","VAR_POP","VAR_SAMP","ANY_VALUE","BOOL_AND","BOOL_OR","BIT_AND","BIT_OR","BIT_XOR","EVERY","STRING_AGG","ARRAY_AGG","JSON_AGG","JSONB_AGG","OBJECT_AGG","MAP_AGG","LISTAGG","GROUP_CONCAT","COLLECT_LIST","COLLECT_SET","APPROX_COUNT_DISTINCT","APPROX_DISTINCT","APPROX_QUANTILES","APPROX_TOP_COUNT","APPROX_TOP_SUM","COUNT_DISTINCT","NDV","CORR","COVAR_POP","COVAR_SAMP","FIRST","LAST"],$Fe=new Set(LFe),zFe=/(?:_AGG$|^APPROX_COUNT_DISTINCT$|^APPROX_DISTINCT$|^COUNT_DISTINCT$|^HLL_(?:COUNT|ESTIMATE)$|^REGR_[A-Z_]+$)/;function BFe(e){const t=e.toUpperCase();return $Fe.has(t)?!0:zFe.test(t)}function nee(e){const t=/\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/g;let n;for(;(n=t.exec(e))!==null;){const r=n[1];if(r&&BFe(r))return!0}return!1}function AO(e){return m.getDataType(e||"")==="number"?"SUM":"COUNT"}const VFe="day",HFe="YYYY-MM-DD";function ree(e){return m.getDataType(e.dataType)!=="date"?e:{...e,granularity:e.granularity??VFe,dateFormat:e.dateFormat??HFe}}const SB="calculated_fields";function UFe(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function WFe(e){return e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName==="SEMAPHOR_CALCULATED_FIELD"||e.entityName===SB||e.qualifiedEntityName===SB||UFe(e.id)}function see(e,t){return`${e}-${t.qualifiedEntityName}-${t.name}-${Date.now()}`}function oee(e,t){const n=m.toTitleCase(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function qFe(e,t,n){const r=m.getDataType(e.dataType);return n==="detailTable"?"detailColumns":n==="kpi"?r==="date"?"groupBy":"metrics":t.length===0||r==="number"?"metrics":r==="date"||r==="string"||r==="boolean"?"groupBy":"metrics"}function iee(e,t,n=[]){const r=see(t,e),s=m.getDataType(e.dataType),o=s==="date",i=e.role==="metric"&&"expression"in e&&!!e.expression,a=e.role==="groupby"&&"expression"in e&&!!e.expression,c={id:r,name:e.name,dataType:e.dataType,label:m.toLabel(e.name),format:e.format,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityId:e.entityId,entityName:e.entityName,entityType:e.entityType};if(t==="metrics"){if(i){const h=e,p=e.expression||"";if(!WFe(h)){const y=!h.aggregate&&!nee(p),S=AO(s);return{...h,id:r,label:e.label||e.name,role:"metric",...y?{aggregate:S}:{}}}const{aggregate:b,...x}=h;return{...x,id:r,label:e.label||e.name,role:"metric"}}const u=e.aggregate||(s==="number"?"SUM":"COUNT"),d=oee(e.label,u),f=OFe({...c,label:d},n,t);return{...c,role:"metric",label:f,aggregate:u}}if(t==="groupBy")return a?ree({...e,id:r,label:e.label||e.name,role:"groupby"}):{...c,role:"groupby",...o&&{granularity:"month",dateFormat:"YYYY-MM"}};if(t==="pivotBy")return{...c,role:"pivotby"};if(t==="detailColumns"){if(i){const{aggregate:u,parameters:d,aliasTemplate:f,valueAliases:h,...p}=e;return{...p,id:r,label:e.label||e.name,role:"detail"}}return a?{...e,id:r,label:e.label||e.name,role:"detail"}:{...c,role:"detail"}}return t==="sortBy"?{...c,role:"sortby",label:e.label,direction:"asc"}:null}function YFe(e){var o,i,a,c;const t=(o=e.config)==null?void 0:o.metricColumns,n=(i=e.config)==null?void 0:i.groupByColumns,r=(a=e.config)==null?void 0:a.pivotByColumns,s=(c=e.config)==null?void 0:c.detailColumns;return!!(t&&(t==null?void 0:t.length)>0||n&&(n==null?void 0:n.length)>0||r&&(r==null?void 0:r.length)>0||s&&(s==null?void 0:s.length)>0)}function GFe(e){var i,a;const[t]=v.useState({id:"",title:"",type:"bar"}),{getCard:n}=m.useDashboardActions(),r=n(e),s=_v(r||t),o={...r,data:((i=s==null?void 0:s.data)==null?void 0:i.records)||[]};return{...s,data:((a=s==null?void 0:s.data)==null?void 0:a.records)||[],card:o}}function _v(e){var R;const{onChartElementClicked:t}=Ct(),[n,r]=v.useState(0),s=m.useDashboardStore(B=>B.themeStyle),o=m.useDashboardStore(B=>B.filteringCards),i=m.useDashboardStore(B=>B.selectedSheetId),a=m.useDashboardStore(B=>B.selectedLensId),c=m.useDashboardStore(B=>B.filterValues),u=v.useRef(c),d=(R=e==null?void 0:e.preferences)==null?void 0:R.onClickFilter,{addFilteringCard:f,addOrUpdateFilterValues:h,removeFilterValues:p,removeFilteringCard:g}=m.useDashboardActions(),{data:b,fetchStatus:x,isLoading:y,isFetching:S,isError:w,isPending:C,queryKey:N,isFilteringCard:k,isSingleCardFrame:_,pagination:E,comparisonMetadata:D,resolvedPrimaryDateField:j}=$c(e),{data:I}=kv(e);let T;T=v.useMemo(()=>{if(!(!(b!=null&&b.records)||!(b!=null&&b.records.length)))return Ag({card:e,data:b==null?void 0:b.records,cardType:e.type,queryConfig:e.queryConfig,customCfg:e.customCfg,preferences:e.preferences,topoJson:I})},[b==null?void 0:b.records,e.type,e.queryConfig,e.customCfg,e.config,e.preferences,I,s]);const F=v.useRef({filteringCards:o});v.useEffect(()=>{e.connectionId&&!k&&(u.current=c)},[c,a,e.connectionId,k]),v.useEffect(()=>{var z;k&&(F.current.filteringCards=[...o||[]]),!k&&((z=F.current.filteringCards)==null?void 0:z.find(U=>U.id===e.id))&&_&&r(U=>U+1)},[k,_,e.id,o]);function P(B,z,U,Y){var q;if(YFe(e))return;let O=!1;if(!(b!=null&&b.records))return;const K=TFe({card:e,data:b==null?void 0:b.records,datasetIndex:z,clickIndex:U,value:Y});if(console.log("fieldValues",K),t==null||t(e,K),!!(((q=e==null?void 0:e.preferences)==null?void 0:q.onClickFilter)??[]).length){if(k){const M=e.id;p(M),g(e)}else{if(O=!0,!K)return;const M=[];K.forEach((G,L)=>{const $=d==null?void 0:d.find(H=>H.columnIndex===L);if(!$)return;const V={filterId:e.id+"-"+G.columnName+"-"+i,connectionId:e==null?void 0:e.connectionId,tableName:e.lastSelectedTable,name:G.columnName,expression:$.expression,valueType:m.resolveDataType(K[$.columnIndex].columnValue),operation:"=",values:[K[$.columnIndex].columnValue]};M.push(V)}),h(M),f(e)}jFe({chart:B,elementIndex:U,datasetIndex:z,cardType:e.type,cfg:T,apply:O})}}return{isPending:C,isError:w,isLoading:y,isFetching:S,fetchStatus:x,data:b,visualKey:n,handleDatapointClick:P,cfg:T,queryKey:N,pagination:E,comparisonMetadata:D,resolvedPrimaryDateField:j}}function VD(e,t){if(e==null)return"-";if(!t)return e.toString();const n=t.locale?new Intl.NumberFormat(t.locale).format(e):e.toFixed(t.decimalPlaces||0);return`${t.prefix||""}${n}${t.suffix||""}`}function CB(e,t){return t.map(n=>{const r=n.alias||n.name,s=e[r];return typeof s=="object"&&s!==null&&"label"in s?String(s.label??""):String(s??"")}).join(" | ")}function aee(e,t=0,n=[],r){if(!(e!=null&&e.length)||t>=e[0].fieldValues.length)return[];const s=c=>n.every((u,d)=>c.fieldValues[d]===u),o=e.filter(s),i=[],a=new Set;for(const c of o){const u=c.fieldValues[t];if(a.has(u))continue;a.add(u);const d=[...n,u],f=d.join(" | ");if(r&&!r.has(f))continue;if(t===c.fieldValues.length-1)i.push({name:u,level:t,rowKey:c.rowKey});else{const p=aee(o.filter(g=>g.fieldValues[t]===u),t+1,d,r);p.length>0&&i.push({name:u,level:t,children:p})}}return i}function KFe(e,t={},n){const r=e.records,s=e.pivotSchema||[],o=e.columnSubtotalMeta||[],i=e.groupByColumns||[],a=e.columnMetadata,c=s.filter(T=>T.isPivotColumn),u=s.filter(T=>T.isMetricColumn),d=()=>({rowHeaders:[],columnHeaders:[],cells:{},columnGroups:[],rowGroups:[],columnDisplayNames:{},groupByColumns:i,columnSubtotalMeta:o,columnMetadata:a});if(c.length===0&&u.length===0)return console.warn("No pivot or metric fields found in pivotSchema:",s),d();const{columnGroups:f,columnHeaders:h,columnDisplayNames:p}=ZFe(s,o,n==null?void 0:n.config);if(!r.length)return d();const g=r.filter(T=>T.isGrandTotal),b=r.filter(T=>T.isSubtotal&&!T.isGrandTotal),x=r.filter(T=>!T.isSubtotal&&!T.isGrandTotal),y=[],S=new Set;x.forEach(T=>{const F=CB(T,i),P=i.map(R=>{const B=R.alias||R.name,z=T[B];return typeof z=="object"&&z!==null&&"label"in z?String(z.label??""):String(z??"")});F&&!S.has(F)&&(S.add(F),y.push({rowKey:F,fieldValues:P}))}),y.sort((T,F)=>{const P=Math.min(T.fieldValues.length,F.fieldValues.length);for(let R=0;R<P;R++){const B=(T.fieldValues[R]||"").localeCompare(F.fieldValues[R]||"");if(B!==0)return B}return T.fieldValues.length-F.fieldValues.length});const w=[],C=[],N=new Set;for(let T=0;T<y.length;T++){const F=y[T];w.push(F),C.push(F.rowKey);const P=y[T+1];for(let R=i.length-1;R>=0;R--){const B=i[R];B.alias||B.name;let z=!1;if(!P)z=!0;else{z=F.fieldValues[R]!==P.fieldValues[R];for(let U=0;U<R&&!z;U++)F.fieldValues[U]!==P.fieldValues[U]&&(z=!0)}z&&b.filter(Y=>{const O=B.alias||B.name;if(Y.subtotalLevel!==O&&Y.subtotalLevel!==B.id)return!1;if(Y.subtotalContext){if(Y.subtotalContext.value!==F.fieldValues[R])return!1;const K=Y.subtotalContext.groupByValues||{};for(let q=0;q<R;q++){const M=i[q],G=M.alias||M.name;if(K[G]!==F.fieldValues[q])return!1}return!0}for(let K=0;K<R;K++){const q=i[K],M=q.alias||q.name,G=Y[M],L=F.fieldValues[K],$=typeof G=="object"&&(G!=null&&G.label)?G.label:String(G??"");if(L!==$)return!1}return!0}).forEach(Y=>{var G;const O=JSON.stringify({level:Y.subtotalLevel,context:Y.subtotalContext});if(N.has(O))return;const K=[...F.fieldValues],q=`${F.fieldValues[R]} Total`;K[R]=q;for(let L=R+1;L<K.length;L++)K[L]="";const M=K.join(" | ");w.push({rowKey:M,fieldValues:K,isSubtotal:!0,subtotalLevel:Y.subtotalLevel,aggregateDisplayLabel:Y.aggregate,aggregateFunction:(G=Y.aggregate)==null?void 0:G.toUpperCase(),subtotalContext:Y.subtotalContext}),C.push(M),N.add(O)})}}const k=w,_=C,E=new Set(k.map(T=>T.rowKey)),D=aee(k,0,[],E),j={};_.forEach(T=>{j[T]={},h.forEach(F=>{j[T][F]={value:null,metricId:"",formattedValue:"-"}})}),x.forEach(T=>{const F=CB(T,i);j[F]&&h.forEach(P=>{if(!(P in T))return;const R=T[P],B=s.find(z=>z.isMetricColumn&&P.startsWith(z.alias));j[F][P]={value:R,metricId:(B==null?void 0:B.metricId)||"",formattedValue:VD(R,t.numberFormat)}})}),b.forEach(T=>{const F=k.find(P=>P.isSubtotal&&P.subtotalLevel===T.subtotalLevel&&JSON.stringify(P.subtotalContext)===JSON.stringify(T.subtotalContext));if(F){const P=F.rowKey;j[P]||(j[P]={}),h.forEach(R=>{if(!(R in T))return;const B=T[R],z=s.find(U=>U.isMetricColumn&&R.startsWith(U.alias));j[P][R]={value:B,metricId:(z==null?void 0:z.metricId)||"",formattedValue:VD(B,t.numberFormat)}})}});const I=[];return g.forEach(T=>{const F={};h.forEach(U=>{if(U in T){const Y=T[U];F[U]={value:Y,metricId:"",formattedValue:VD(Y,t.numberFormat)}}});const P=T.aggregate||"Total";let R="SUM";const B=P.toUpperCase();["SUM","AVG","COUNT","MIN","MAX","MEDIAN"].includes(B)&&(R=B);const z=P.charAt(0).toUpperCase()+P.slice(1).toLowerCase();I.push({aggregateDisplayLabel:z,aggregateFunction:R,data:F})}),{rowHeaders:_,columnHeaders:h,cells:j,columnGroups:f,rowGroups:D,columnDisplayNames:p,groupByColumns:i,columnSubtotalMeta:o,columnMetadata:a,grandTotalRows:I,rowData:k}}function ZFe(e,t,n){const r=e.filter(p=>p.isPivotColumn),s=((n==null?void 0:n.pivotByColumns)||[]).map(p=>p.id),o=new Map;e.filter(p=>p.isMetricColumn).forEach(p=>{o.has(p.alias)||o.set(p.alias,p)});const i=Array.from(o.values());function a(p){return p.displayLabel||p.metricLabel||p.metricName||p.alias}function c(p,g){var b,x;return((x=(b=n==null?void 0:n.columnAggregates)==null?void 0:b.find(y=>y.function===p&&y.pivotLevel===g))==null?void 0:x.label)||p}function u(p,g,b){return p.subtotalScope==="grand-total"||p.pivotFieldId&&p.pivotFieldId!==g?!1:Array.isArray(p.pivotPath)&&p.pivotPath.length>0?p.pivotPath.length!==b.length?!1:p.pivotPath.every((x,y)=>String(x??"")===String(b[y]??"")):p.subtotalLevel===b[b.length-1]}function d(p,g=[]){if(p>=r.length){const y=[],S=[],w={};return i.forEach(C=>{const N=[C.alias,...g].join("_"),k=a(C);y.push({name:k,level:p,colspan:1,columnKey:N}),S.push(N),w[N]=k}),{groups:y,leafKeys:S,displayNames:w}}const b=r[p],x={groups:[],leafKeys:[],displayNames:{}};return b.pivotValues.forEach(y=>{const S=[...g,y],w=d(p+1,S),C=s[p];t.filter(k=>!!C&&u(k,C,S)).forEach(k=>{var D;const _=(D=k.aggregate)==null?void 0:D.toUpperCase(),E=c(_,k.pivotFieldId||C);w.groups.push({name:E,level:p+1,colspan:1,columnKey:k.columnName}),w.leafKeys.push(k.columnName),w.displayNames[k.columnName]=E}),x.groups.push({name:y,level:p,colspan:w.groups.reduce((k,_)=>k+(_.colspan||1),0),children:w.groups}),x.leafKeys.push(...w.leafKeys),Object.assign(x.displayNames,w.displayNames)}),x}const f=d(0),h=t.filter(p=>p.subtotalScope==="grand-total"||p.subtotalLevel==="grandTotal"||p.subtotalLevel==="ALL");return h.length>0&&h.forEach(p=>{var x;const g=(x=p.aggregate)==null?void 0:x.toUpperCase(),b=c(g,"ALL");f.groups.push({name:b,level:0,colspan:1,columnKey:p.columnName}),f.leafKeys.push(p.columnName),f.displayNames[p.columnName]=b}),{columnGroups:f.groups,columnHeaders:f.leafKeys,columnDisplayNames:f.displayNames}}function XFe({data:e,card:t}){var o;if(!t.config)throw new Error("Card configuration is required for pivot table");const n=e.records.some(i=>i.isGrandTotal),r=((o=t.config)==null?void 0:o.rowAggregates)&&t.config.rowAggregates.length>0,s={showRowTotals:!1,showColumnTotals:n||r,showGrandTotal:!1};return{type:"pivotTable",data:KFe(e,s,t),config:t.config,options:s,pivotSchema:e.pivotSchema}}function Gh(e,t){return v.useMemo(()=>!e||e.type!=="pivotTable"||!t||!Array.isArray(t.records)||t.records.length===0?null:XFe({card:e,data:{records:t.records||[],columnSubtotalMeta:t.columnSubtotalMeta,subtotalColumns:t.subtotalColumns,pivotSchema:t.pivotSchema||[],groupByColumns:t.groupByColumns}}),[e,t])}function lee(e){var y;const t=m.useDashboardStore(S=>S.dashboard),n=m.useDashboardStore(S=>S.dashboard.filters),r=m.useDashboardStore(S=>S.filterValues),s=m.useDashboardStore(S=>S.selectedSheetId),o=m.useDashboardStore(S=>S.dashboardInputValues),i=m.useDashboardStore(S=>S.dashboardInputValuesAreAuthoritative),a=m.useDashboardStore(S=>S.controlValues),c=m.useDashboardStore(S=>S.inlineFilterValuesMap),u=m.useDashboardStore(S=>S.cardControlValuesMap),d=m.useDashboardStore(S=>S.actions.getCard(e)),f=m.useEditorStore(S=>S.editorContext),h=m.useEditorStore(S=>S.card),g=(f==null?void 0:f.type)==="documentSection"&&f.cardId===e?f:void 0,b=g?h:d;if((!!((y=t.inputs)!=null&&y.length)||!!t.defaultInputValues)&&b){const S=$l({dashboard:t,sheetId:g?g.sheetId:s,sheetKind:g?"document":void 0,sectionId:g?g.sectionId:void 0,card:b,runtimeValues:{dashboardInputValues:o,dashboardInputValuesAreAuthoritative:i,filterValues:r,controlValues:a,inlineFilterValuesMap:c,cardControlValuesMap:u},mode:g?"editor":"interactive"}),w=QFe(S.inputs);return{cardFilters:S.inputs.flatMap(C=>C.kind==="filter"&&!w.has(C.filter.id)?[C.filter]:[]),cardFilterValues:S.activeFilters.filter(C=>!w.has(C.filterId))}}return g?{cardFilters:[],cardFilterValues:g.documentFilterValues||[]}:xP(n,r,s,e)}function QFe(e){return new Set(e.flatMap(t=>{var n;return t.kind==="filter"&&((n=t.compatibility)==null?void 0:n.source)==="cardInlineFilter"?[t.filter.id]:[]}))}const HD={dense:{rowPad:"py-1",cell:"text-[11px]",header:"text-[9px]"},compact:{rowPad:"py-2",cell:"text-[13px]",header:"text-[10px]"},standard:{rowPad:"py-2.5",cell:"text-[13px]",header:"text-[10px]"},comfortable:{rowPad:"py-3",cell:"text-[14px]",header:"text-[11px]"},spacious:{rowPad:"py-3.5",cell:"text-[16px]",header:"text-[12px]"}};function JFe(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(HD,e)?HD[e]:HD.compact}function ePe({currentOrder:e,draggingColId:t,dropTarget:n,pinnedStartIds:r=["select"]}){if(!t||!n||t===n.colId)return null;const s=e.indexOf(t),o=e.indexOf(n.colId);if(s===-1||o===-1)return null;const i=[...e];i.splice(s,1);const a=n.side==="before"?o>s?o-1:o:o>s?o:o+1;i.splice(a,0,t);for(let c=r.length-1;c>=0;c-=1){const u=r[c],d=i.indexOf(u);d>0&&(i.splice(d,1),i.unshift(u))}return i}function cee({rows:e,columns:t,columnSettings:n}){var c;const r=n??{},s=t.filter(u=>u.id!=="select");if(s.length===0)return{};const o={},i=new Set(s.filter(u=>tPe(e,u.id,r[u.id])).map(u=>u.id)),a=s.find(u=>!i.has(u.id))??s[0];o[a.id]="Total";for(const u of s){if(u.id===a.id||!i.has(u.id))continue;let d=0,f=0;for(const h of e){const p=(c=h.original)==null?void 0:c[u.id];if(p==null||p==="")continue;const g=typeof p=="number"?p:Number(p);Number.isFinite(g)&&(d+=g,f+=1)}o[u.id]=f===0?null:d}return o}function tPe(e,t,n){var s;if((n==null?void 0:n.type)==="number")return!0;if(n!=null&&n.type&&n.type!=="none")return!1;let r=!1;for(const o of e){const i=(s=o.original)==null?void 0:s[t];if(i==null||i==="")continue;r=!0;const a=typeof i=="number"?i:Number(i);if(!Number.isFinite(a))return!1}return r}function NB(e){return typeof e=="string"?e.trim().toLowerCase():""}function RO(e){return[e.alias,e.label,e.name,e.qualifiedFieldName,e.id].filter(t=>!!t)}function Jm(e,t,n=[]){const r=NB(t);return[...n,...RO(e)].some(s=>NB(s)===r)}function uee(e,t){return[e.alias,e.metricId,e.metricName,e.metricLabel,e.displayLabel].some(n=>Jm(t,n||""))}function kB(e,t){return t.findIndex(n=>uee(e,n))}function _B(e){return JSON.stringify({fields:e.pivotFields??[],values:e.pivotValues??[]})}function nPe(e,t,n,r){if(t===-1||n===-1||t===n)return null;const s=[...e],[o]=s.splice(t,1),i=r==="before"?n>t?n-1:n:n>t?n:n+1;return s.splice(i,0,o),s}function oy(e,t,n){if(!(e!=null&&e.length))return null;const r=e.findIndex(o=>Jm(o,t.draggingColumnId,(n==null?void 0:n(o))??[])),s=e.findIndex(o=>Jm(o,t.targetColumnId,(n==null?void 0:n(o))??[]));return nPe(e,r,s,t.side)}function iy(e,t,n){return n?{...e??{},[t]:n}:null}function rPe(e,t){const n=e.config;return e.type==="detailTable"?iy(n,"detailColumns",oy(n==null?void 0:n.detailColumns,t)):iy(n,"groupByColumns",oy(n==null?void 0:n.groupByColumns,t))??iy(n,"metricColumns",oy(n==null?void 0:n.metricColumns,t))}function eg(e){var t,n,r,s,o,i;return!e||e.sql?!1:e.type==="detailTable"?!!((n=(t=e.config)==null?void 0:t.detailColumns)!=null&&n.length):!!((s=(r=e.config)==null?void 0:r.groupByColumns)!=null&&s.length||(i=(o=e.config)==null?void 0:o.metricColumns)!=null&&i.length)}function jB(e,t,n,r){var a,c;const s=n.filter(u=>u.isMetricColumn),o=u=>t.filter(d=>Jm(d,u.alias||u.name||u.id)).flatMap(d=>RO(d)),i=u=>s.filter(d=>uee(d,u)).flatMap(d=>[d.alias,d.metricId,d.metricName,d.metricLabel,d.displayLabel].filter(f=>!!f));return iy(e.config,"groupByColumns",oy((a=e.config)==null?void 0:a.groupByColumns,r,o))??iy(e.config,"metricColumns",oy((c=e.config)==null?void 0:c.metricColumns,r,i))}function UD(e,t){return e!=null&&e.length?e.map(n=>RO(n).find(r=>t.includes(r))).filter(n=>!!n):[]}function FO(e,t,n){if(!(t!=null&&t.config))return e;const r=[],s=o=>{o&&e.includes(o)&&!r.includes(o)&&r.push(o)};return t.type==="detailTable"?UD(t.config.detailColumns,e).forEach(s):(UD(t.config.groupByColumns,e).forEach(s),UD(t.config.metricColumns,e).forEach(o=>{s(o),s(n==null?void 0:n(o))})),e.forEach(s),r}function dee(e,t){const n=t==null?void 0:t.groupByColumns;return n!=null&&n.length?[...e].sort((r,s)=>{const o=n.findIndex(a=>Jm(r,a.alias||a.name||a.id)),i=n.findIndex(a=>Jm(s,a.alias||a.name||a.id));return o===-1&&i===-1?0:o===-1?1:i===-1?-1:o-i}):e}function fee(e,t){const n=t==null?void 0:t.metricColumns;if(!(n!=null&&n.length))return e;const r=(i,a)=>{const c=kB(i,n),u=kB(a,n);return c===-1&&u===-1?0:c===-1?1:u===-1?-1:c-u},s=[];let o=0;for(;o<e.length;){const i=e[o];if(!i.isMetricColumn){s.push(i),o+=1;continue}const a=_B(i),c=[];for(;o<e.length&&e[o].isMetricColumn&&_B(e[o])===a;)c.push(e[o]),o+=1;s.push(...c.sort(r))}return s}function hee(e){switch(e){case"previous_period":return"Previous";case"same_period_last_year":return"Last Year";case"start_vs_end":return"Start";case"target":return"Target";default:return"Comparison"}}function pee(e,t){const n=hee(t);return`${e} (${n})`}function sPe(e,t){return`${e} Δ`}function oPe(e,t){if(e){if(t.id&&e[t.id])return e[t.id];if(e[t.name])return e[t.name];if(t.label&&e[t.label])return e[t.label]}}function iPe(e){var r;if((e==null?void 0:e.type)!=="table")return;const t=((r=e.config)==null?void 0:r.metricColumns)||[],n=new Map;return t.forEach(s=>{const o=s.comparisonType??"none";if(o==="none")return;const i=s.label||s.name;n.set(i,pee(i,o))}),s=>n.get(s)??null}function aPe(e){var t,n,r;return e!=null&&e.config?e.type==="detailTable"?!!((t=e.config.detailColumns)!=null&&t.length):!!((n=e.config.groupByColumns)!=null&&n.length||(r=e.config.metricColumns)!=null&&r.length):!1}function lPe({records:e,tablePreferences:t,card:n}){if(!e||e.length===0)return null;const r=(t==null?void 0:t.columnSettingsMap)||{},s=Object.keys(e[0]);let o=s;if(t!=null&&t.columnVisibility&&(o=s.filter(f=>{var h;return((h=t.columnVisibility)==null?void 0:h[f])!==!1})),aPe(n))o=FO(o,n,iPe(n));else if(t!=null&&t.columnSizing){const h=Object.keys(t.columnSizing).filter(g=>o.includes(g)),p=o.filter(g=>!h.includes(g));o=[...h,...p]}const i=f=>td({card:n,columnId:f,existingSettings:r[f]}),a=o.map(f=>{const h=i(f),g=((h==null?void 0:h.textAlign)||"left")==="right";return{text:f,colspan:1,rowspan:1,className:g?"numeric":"",columnId:f,isHeader:!0,isNumeric:g}}),c=e.map(f=>({cells:o.map(h=>{const p=i(h),g=mee(f[h],h,p,n),x=((p==null?void 0:p.textAlign)||"left")==="right";return{text:g,colspan:1,rowspan:1,className:x?"numeric":"",columnId:h,isHeader:!1,isNumeric:x}})})),u=o.map((f,h)=>{var p,g;return{index:h,columnId:f,label:f,isNumeric:(((p=i(f))==null?void 0:p.textAlign)||"left")==="right",measuredWidthPx:Number((g=t==null?void 0:t.columnSizing)==null?void 0:g[f])||void 0}}),d=cPe({records:e,visibleColumns:o,columnSettings:r,resolveSettings:i,tablePreferences:t,card:n});return{headers:[{cells:a}],rows:c,grandTotal:d,metadata:{tableType:"data",totalRows:c.length,totalColumns:o.length,columnOrder:o,columns:u,hasGrandTotal:!!d}}}function cPe({records:e,visibleColumns:t,columnSettings:n,resolveSettings:r,tablePreferences:s,card:o}){var u,d;if(!(((d=(u=s==null?void 0:s.tableStyle)==null?void 0:u.totals)==null?void 0:d.enabled)===!0||!!(o&&mv(o))))return null;const a=cee({rows:e.map(f=>({original:f})),columns:t.map(f=>({id:f})),columnSettings:n});return Object.keys(a).length===0?null:{cells:t.map(f=>{const h=r(f),p=a[f],g=typeof p=="number"?mee(p,f,h,o):p==null?"":String(p),b=(h==null?void 0:h.textAlign)||"left",x=typeof p=="number"||b==="right";return{text:g,colspan:1,rowspan:1,className:x?"numeric":"",columnId:f,isHeader:!1,isNumeric:x}})}}function mee(e,t,n,r){if(e==null)return"";if((n==null?void 0:n.type)==="number"&&typeof e=="number")try{const s=yv({card:r,columnId:t,existingSettings:n});return s!=null&&s.type&&s.type!=="auto"?Fn(e,s.type,s):Bn.formatNumberWithColumnSettings(e,n.numberFormat,n.numberFormat.locale||"en-US")||e.toLocaleString()}catch{return e.toLocaleString()}if((n==null?void 0:n.type)==="date")try{const s=n.dateFormat.timezone&&n.dateFormat.timezone!=="auto"?n.dateFormat.timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,o=n.dateFormat.useCustomFormat?n.dateFormat.customFormat:n.dateFormat.format;return Bn.formatDate(String(e),o,s,n.dateFormat.sourceTimezone||"auto")}catch{return String(e)}return typeof e=="number"?e.toLocaleString():String(e)}function uPe({records:e,groupByColumns:t=[],pivotSchema:n=[],card:r,columnSettings:s={}}){var x,y,S;if(!e||e.length===0)return null;const o=dee(t,r.config),i=fee(n,r.config),a=GP(e,o),c=KP(e),u=i.filter(w=>w.isMetricColumn),d=new Map;u.forEach((w,C)=>{d.set(w.alias,Yu({card:r,columnId:w.alias,metricIndex:C,groupByColumnCount:o.length,columnSettingsMap:s}))});const f=[...o.map(w=>({text:w.label||w.name,colspan:1,rowspan:1,className:"",columnId:w.alias||w.name,isHeader:!0,isNumeric:!1})),...u.map(w=>({text:w.metricLabel||w.metricName||w.alias,colspan:1,rowspan:1,className:"numeric",columnId:w.alias,isHeader:!0,isNumeric:!0}))],h=a.map(w=>{const C=[],N=w.isSubtotal&&!w.isGrandTotal;return o.forEach(k=>{var D,j,I;const _=k.alias||k.name;let E=w[_];if(N){const T=w.aggregate||"SUM",F=(I=(j=(D=r==null?void 0:r.config)==null?void 0:D.rowAggregates)==null?void 0:j.find(P=>P.groupLevel===w.subtotalLevel&&P.function===T))==null?void 0:I.label;E=PX(w,_,T,F)}else w.isGrandTotal&&(E="");C.push({text:E&&E!=="__TOTAL__"?String(E):"",colspan:1,rowspan:1,className:"",columnId:_,isHeader:!1,isNumeric:!1})}),u.forEach(k=>{const _=k.alias,E=d.get(_),D=EB(w[_],E);C.push({text:D,colspan:1,rowspan:1,className:"numeric",columnId:_,isHeader:!1,isNumeric:!0})}),{type:N?"subtotal":void 0,cells:C}});let p=null;if(c){const w=c.aggregate||"SUM",C=(S=(y=(x=r==null?void 0:r.config)==null?void 0:x.rowAggregates)==null?void 0:y.find(_=>_.groupLevel==="ALL"))==null?void 0:S.label,N=OX(w,C),k=[];o.forEach((_,E)=>{k.push({text:E===0?N:"",colspan:1,rowspan:1,className:"",isHeader:!1,isNumeric:!1})}),u.forEach(_=>{const E=_.alias,D=d.get(E);let j=c[E];(j==null||j==="")&&(j=e.filter(T=>!T.isSubtotal&&!T.isGrandTotal).reduce((T,F)=>{const P=qP(F[E]);return T+(P??0)},0));const I=EB(j,D);k.push({text:I,colspan:1,rowspan:1,className:"numeric",columnId:E,isHeader:!1,isNumeric:!0})}),p={cells:k}}const g=[...o.map(w=>w.alias||w.name),...u.map(w=>w.alias)],b=g.map((w,C)=>{var N,k,_;return{index:C,columnId:w,label:((N=o.find(E=>(E.alias||E.name)===w))==null?void 0:N.label)||((k=u.find(E=>E.alias===w))==null?void 0:k.metricLabel)||((_=u.find(E=>E.alias===w))==null?void 0:_.metricName)||w,isNumeric:u.some(E=>E.alias===w)}});return{headers:[{cells:f}],rows:h,grandTotal:p,metadata:{tableType:"aggregate",totalRows:h.length,totalColumns:f.length,groupByCount:o.length,hasGrandTotal:!!p,columnOrder:g,columns:b}}}function EB(e,t){if(e==null)return"";const n=YP(e,t);return n!==null?n:typeof e=="number"?e.toLocaleString():String(e)}function DB(e){return Array.isArray(e)?e.filter(t=>!(t!=null&&t.isGrandTotal)).length:0}function dPe({exportData:e,pivotTableConfig:t,pivotData:n}){var a;const r=Array.isArray(e==null?void 0:e.records)?e.records:Array.isArray(e)?e:[],s=DB(r);if(s>0)return s;const o=Array.isArray((a=t==null?void 0:t.data)==null?void 0:a.rowData)?t.data.rowData.length:0;if(o>0)return o;const i=Array.isArray(n==null?void 0:n.records)?n.records:[];return DB(i)}const IB=[10,20,50,100,500,1e3],fPe=50;function R_(e){return e&&e>0?e:fPe}function gee(e){const t=R_(e),n=[...IB];return IB.includes(t)||(n.push(t),n.sort((r,s)=>r-s)),n}function bee(e,t){var r,s,o,i;if(t==="table-print")return"disabled";if((s=(r=e.preferences)==null?void 0:r.tablePrefs)!=null&&s.forceClientPagination)return"client";const n=m.hasValidCardConfig(e.config);return e.sql&&!n?(i=(o=e.preferences)==null?void 0:o.tablePrefs)!=null&&i.enableDevModePagination?"server":"client":n&&iM(e)?"server":"client"}async function hPe({apiServiceUrl:e,authToken:t,connectionId:n,requestPayloadBase:r}){if(!n)throw new Error("No connection ID found for card");const s={connection_id:n,...r,exportMode:!0};return m.postRequestRegular(`${e}/v1/query`,t,s,"POST")}function xee(){const e={};return document.querySelectorAll('[data-spr-expand-id][aria-expanded="true"]').forEach(t=>{const n=t.getAttribute("data-spr-expand-id");n&&(e[n]=!0)}),e}async function yee(e,t,n){const r=await fetch(`${e}/v1/exports`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)}),s=await r.json();if(!r.ok){const o=s;throw new Rg(o.message||o.error||"Failed to create export",r.status,o)}return s}async function pPe(e,t,n){var o;const r=new URL(`${e}/v1/exports`);(o=n==null?void 0:n.status)!=null&&o.length&&r.searchParams.set("status",n.status.join(",")),n!=null&&n.limit&&r.searchParams.set("limit",String(n.limit));const s=await fetch(r.toString(),{headers:{Authorization:`Bearer ${t}`}});if(!s.ok)throw new Rg("Failed to fetch exports",s.status);return s.json()}async function mPe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new Rg("Failed to fetch export status",r.status);return r.json()}async function gPe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}/download`,{headers:{Authorization:`Bearer ${t}`}});if(r.ok){const s=await r.json();if(s.downloadUrl)return s.downloadUrl}throw new Rg("Failed to get download URL",r.status)}async function bPe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new Rg("Failed to cancel export",r.status)}class Rg extends Error{constructor(t,n,r){super(t),this.status=n,this.details=r,this.name="ExportError"}}function xPe(e){return["pending","processing","chunking","compacting"].includes(e)}function yPe(e){return["completed","failed","cancelled"].includes(e)}function vPe(e){return!e||e===0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}const wPe=[];function PO(e){var k;const t=m.useInteractionStore(_=>_.interactionStates),n=m.useDashboardStore(_=>_.dashboard),r=m.useDashboardStore(_=>_.dashboard.filters),s=m.useDashboardStore(_=>_.dashboard.controls),o=m.useDashboardStore(_=>_.filterValues),i=m.useDashboardStore(_=>_.controlValues),a=m.useDashboardStore(_=>_.cardControlValuesMap),c=m.useDashboardStore(_=>_.selectedSheetId),u=m.useDashboardStore(_=>{var E;return(E=_.dashboard)==null?void 0:E.id}),d=m.useDashboardStore(_=>_.isVisualEditing),f=m.useDashboardStore(_=>_.inlineFilterValuesMap),h=m.useDashboardStore(_=>_.dashboardInputValues),p=m.useDashboardStore(_=>_.dashboardInputValuesAreAuthoritative),g=m.useEditorStore(_=>_.inlineFilterValuesMap),b=m.useEditorStore(_=>_.editorContext),y=(b==null?void 0:b.type)==="documentSection"&&b.cardId===e.id?b:void 0,S=!!y,w=v.useMemo(()=>{if(y){const _=y.documentFilterValues||wPe,D=[...g[e.id]||[],..._];return D.length>0?{[e.id]:D}:{}}return d?{[e.id]:g[e.id]??f[e.id]}:f},[S,d,e.id,f,y,g]),C=!!((k=n.inputs)!=null&&k.length)||!!n.defaultInputValues,N=v.useMemo(()=>C?$l({dashboard:n,sheetId:y?y.sheetId:c,sheetKind:y?"document":void 0,sectionId:y?y.sectionId:void 0,card:e,runtimeValues:{dashboardInputValues:h,dashboardInputValuesAreAuthoritative:p,filterValues:o,controlValues:i,inlineFilterValuesMap:w,cardControlValuesMap:a},mode:y?"editor":"interactive"}):void 0,[e,a,i,n,h,p,y,o,w,S,c,C]);return v.useMemo(()=>{const _=S?[]:r,E=S?[]:o,D=S?{}:t,j=S?[]:s,I=S?{}:i,T=S?{}:a;return fv({card:e,interactionStates:D,currentDashboardId:u,filters:_,filterValues:E,selectedSheetId:y?y.sheetId:c,inlineFilterValuesMap:w,dashboardControls:j,dashboardControlValues:I,cardControlValuesMap:T,dashboardInputContext:N})},[e,t,u,r,s,o,i,a,N,c,w,S,y])}function SPe(e,t){var n;return{connectionId:t,connectionType:((n=e.dataSource)==null?void 0:n.connectionType)||"unknown",mode:"database",selectedEntities:[]}}function vee(e,t){var r,s,o;const n=((s=(r=e.dataSource)==null?void 0:r.connectionId)==null?void 0:s.trim())||((o=e.connectionId)==null?void 0:o.trim())||"";if(!n)throw new Error("No connection ID found for card");return{connectionId:n,requestPayloadBase:{...t,cardDataSource:t.cardDataSource||e.dataSource||SPe(e,n)}}}function CPe(e){const t=vee(e.card,e.requestPayloadBase),{cardId:n,...r}=t.requestPayloadBase;return{type:"card",dashboardId:e.dashboardId,cardId:e.card.id,title:e.title,connection_id:t.connectionId,...r,timezone:e.timezone,totalRows:e.totalRows,format:e.format,formatOptions:e.formatOptions}}function wee(e,t){return(e==null?void 0:e[t])!==!1}function See(e,t,n){const r={...e||{}};return n?delete r[t]:r[t]=!1,Object.keys(r).length>0?r:void 0}function NPe(){}function kPe(e,t){return e.filter(n=>wee(t,n))}const x1=1e4,WD=1e6,bp="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",y1="flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50";function _Pe(e,t){const n=new Map;for(const r of e||[])r!=null&&r.id&&n.set(r.id,r);for(const r of t||[])r!=null&&r.id&&n.set(r.id,r);return Array.from(n.values())}function jPe(e){var n,r,s;return eg(e)?(e.type==="detailTable"?((n=e.config)==null?void 0:n.detailColumns)||[]:[...((r=e.config)==null?void 0:r.groupByColumns)||[],...((s=e.config)==null?void 0:s.metricColumns)||[]]).map(o=>o.alias||o.label||o.name||o.qualifiedFieldName||o.id).filter(o=>!!o):[]}function EPe({card:e,records:t}){var i,a;const n=(a=(i=e.preferences)==null?void 0:i.tablePrefs)==null?void 0:a.columnVisibility;if(!n)return;const r=Object.keys(t[0]||{}),s=jPe(e),o=r.length>0?eg(e)?FO(r,e):r:s;return o.length===0?null:kPe(o,n)}function F_({isOpen:e,onClose:t,frame:n,card:r,data:s}){var H;const{authToken:o,tokenProps:i}=Ct(),{addExport:a}=xK(),c=r==null?void 0:r.type,u=v.useMemo(()=>c?$X(c):["pdf"],[c]),d=v.useMemo(()=>c?zX(c):"pdf",[c]),[f,h]=v.useState(!1),[p,g]=v.useState(!1),[b,x]=v.useState({format:d,pageSize:"letter",orientation:"portrait",protectPdf:!1,pdfPassword:"",delimiter:",",includeHeaders:!0,exportMode:"local"}),y=m.useDashboardStore(A=>{var W;return(W=A.dashboard)==null?void 0:W.id});m.useDashboardStore(A=>{var W;return(W=A.dashboard)==null?void 0:W.title});const S=m.useDashboardStore(A=>A.selectedLensId),w=m.useDashboardStore(A=>A.dashboard.filters),C=m.useDashboardStore(A=>A.inlineFilterValuesMap[(r==null?void 0:r.id)||""]),{cardFilters:N,cardFilterValues:k}=lee((r==null?void 0:r.id)||""),_=v.useMemo(()=>[...k||[],...C||[]],[k,C]),E=v.useMemo(()=>_Pe(w,N),[w,N]),D={id:"",type:"table"},j=_v(r||D),I=PO(r||D),T=(H=r==null?void 0:r.preferences)==null?void 0:H.tablePrefs,F=c_(r?[r]:[],{authority:"runtime"}).payload,P=v.useMemo(()=>r?hv({card:r,cardConfig:I.queryRelevantConfig,semanticExecutionPayload:F}):null,[r,I.queryRelevantConfig,F]),R=v.useMemo(()=>r?CP(r,{finalFiltersKey:"",selectedLensId:S,cardFilterValues:_,controlValues:I.controlValues,controlDefinitions:I.controlDefinitions,cardControlDefinitions:I.cardControlDefinitions,controlBindings:I.controlBindings,queryRelevantConfig:I.queryRelevantConfig,filters:E,resolvedPrimaryDateField:P}):null,[_,r,I.cardControlDefinitions,I.controlBindings,I.controlDefinitions,I.controlValues,I.queryRelevantConfig,E,P,S]),B=r?(j==null?void 0:j.data)||s:null,z=Gh(r||D,B),U=(r==null?void 0:r.title)||"Visual Report",Y=CX(kZ({filters:E,filterValues:_||[]})),K=(r?bee(r):"client")==="server",q=v.useMemo(()=>{var X;if(!r||r.type!=="table"&&r.type!=="detailTable")return 0;const A=(j==null?void 0:j.data)||s;return K&&((X=j==null?void 0:j.pagination)!=null&&X.totalCount)?j.pagination.totalCount:(Array.isArray(A)?A:(A==null?void 0:A.records)||[]).length},[r,j==null?void 0:j.data,j==null?void 0:j.pagination,s,K]),M=v.useMemo(()=>!(!r||r.type!=="table"&&r.type!=="detailTable"||!K||q<=x1),[r,K,q]),G=q>WD;v.useEffect(()=>{b.format==="pdf"&&q>x1&&u.includes("csv")&&x(A=>({...A,format:"csv"}))},[q,b.format,u]);const L=()=>{x(A=>({...A,pdfPassword:"",protectPdf:!1,exportMode:"local"})),g(!1),t()},$=async()=>{var A,W,X,Z;if(!r||!y||!R){ut.error("Missing card or dashboard information");return}if(G){ut.error(`Export exceeds maximum of ${WD.toLocaleString()} rows. Please apply filters to reduce the dataset.`);return}h(!0);try{const J=(j==null?void 0:j.data)||s,re=Array.isArray(J)?J:Array.isArray(J==null?void 0:J.records)?J.records:[],fe=EPe({card:r,records:re});if(fe===null){ut.error("Column visibility could not be resolved yet. Run the table before exporting with hidden columns.");return}const de=Intl.DateTimeFormat().resolvedOptions().timeZone,Se=((W=(A=i==null?void 0:i.params)==null?void 0:A.calendarContext)==null?void 0:W.tz)||((X=i==null?void 0:i.params)==null?void 0:X.timezone)||de,ue={useFormattedValues:!0,timezone:Se,browserTimezone:de,isSqlCard:!!(r!=null&&r.sql),locale:navigator.language||"en-US",delimiter:b.delimiter,includeHeaders:b.includeHeaders,columnSettings:T==null?void 0:T.columnSettingsMap,visibleColumns:fe},ve=CPe({card:r,dashboardId:y,title:U,timezone:Se,totalRows:q,format:"csv",formatOptions:ue,requestPayloadBase:R.requestPayloadBase}),xe=await yee(i.apiServiceUrl,(o==null?void 0:o.accessToken)||"",ve);a({id:xe.exportId,status:xe.status==="pending"?"pending":"processing",progress:0,title:U,totalRows:xe.estimatedRows,totalChunks:xe.totalChunks,completedChunks:0,startedAt:new Date,lastUpdatedAt:new Date,expiresAt:new Date(Date.now()+24*60*60*1e3)}),xe.wasTruncated?ut.warning(`Export started for ${xe.estimatedRows.toLocaleString()} rows (truncated from ${(Z=xe.originalRows)==null?void 0:Z.toLocaleString()}). You'll be notified when it's ready.`,{duration:5e3}):ut.success(`Export started for ${xe.estimatedRows.toLocaleString()} rows. You'll be notified when it's ready.`,{duration:4e3,icon:l.jsx(SS,{className:"h-4 w-4"})}),L()}catch(J){console.error("Async export error:",J),ut.error(J.message||"Failed to start export. Please try again.")}finally{h(!1)}},V=async()=>{var J,re,fe,de,Se;if(b.exportMode==="async"&&M&&b.format==="csv"){await $();return}if(!r||!R){ut.error("No card selected");return}const A=(j==null?void 0:j.data)||s;if(!A){ut.error("No data to export");return}const X=!r||!["table","aggregateTable","pivotTable","detailTable"].includes(r.type)?0:r.type==="pivotTable"?dPe({exportData:A,pivotTableConfig:z,pivotData:B}):(Array.isArray(A==null?void 0:A.records)?A==null?void 0:A.records:Array.isArray(A)?A:[]).length;let Z=null;if(r.type==="table"||r.type==="detailTable"){const ue=Array.isArray(A)?A:Array.isArray(A==null?void 0:A.records)?A.records:[];ue.length>0&&(Z=lPe({records:ue,tablePreferences:T,card:r}))}else if(r.type==="aggregateTable"){const ue=Array.isArray(A)?A:Array.isArray(A==null?void 0:A.records)?A.records:[];if(ue.length>0){const ve=(A==null?void 0:A.groupByColumns)||((J=r.config)==null?void 0:J.groupByColumns)||[],xe=(A==null?void 0:A.pivotSchema)||[];Z=uPe({records:ue,groupByColumns:ve,pivotSchema:xe,card:r,columnSettings:T==null?void 0:T.columnSettingsMap})}}else if(r.type==="pivotTable"){const ue=$Z(n.id,"pivotTable"),ve=(ue==null?void 0:ue.rows.filter(xe=>Array.isArray(xe.cells)&&xe.cells.length>0).length)||0;ue&&ve===X&&(Z=ue)}h(!0);try{const ue=ve=>{if(ve){if(ve.usedBanding){const xe=ve.bandCount||1;ut.info(`PDF layout optimized for wide table: ${xe} column band${xe===1?"":"s"} (${ve.effectivePageSize||b.pageSize} ${ve.effectiveOrientation||b.orientation})`);return}ve.autoAdjustedLayout&&ut.info(`PDF layout auto-adjusted to ${ve.effectivePageSize||b.pageSize} ${ve.effectiveOrientation||b.orientation} for readability`)}};if(b.format==="csv"){let ve="";const xe=`${U.replace(/[^a-z0-9]/gi,"_")}.csv`,ke=(r==null?void 0:r.type)&&["table","aggregateTable","pivotTable","detailTable"].includes(r.type);if((r.type==="table"||r.type==="detailTable")&&K)try{const se=vee(r,R.requestPayloadBase),be=await hPe({apiServiceUrl:i.apiServiceUrl,authToken:(o==null?void 0:o.accessToken)||"",connectionId:se.connectionId,requestPayloadBase:se.requestPayloadBase});be.rowLimitExceeded&&ut.warning("Dataset exceeds 10,000 rows. Exporting first 10,000 records. Please apply filters to reduce dataset size.",{duration:5e3});const Ce=be.records||[];ez(Ce,xe,T,r,{delimiter:b.delimiter,includeHeaders:b.includeHeaders,useFormattedValues:!0}),ut.success("CSV exported successfully"),L();return}catch(se){ut.error(`Export failed: ${se.message||"Unknown error"}`),console.error("Export error:",se);return}if(ke)switch(r.type){case"table":case"detailTable":{const se=Array.isArray(A)?A:(A==null?void 0:A.records)||[];if(!se||se.length===0){ut.error("No data available to export");return}ez(se,xe,T,r,{delimiter:b.delimiter,includeHeaders:b.includeHeaders,useFormattedValues:!0}),ut.success("CSV exported successfully"),L();return}case"aggregateTable":{const se=Array.isArray(A)?A:(A==null?void 0:A.records)||[];if(!se||se.length===0){ut.error("No data available to export");return}const be=(A==null?void 0:A.groupByColumns)||((re=r.config)==null?void 0:re.groupByColumns)||[],Ce=(A==null?void 0:A.pivotSchema)||[],ge=GP(se,be),ee=KP(se),te=(de=(fe=r==null?void 0:r.preferences)==null?void 0:fe.tablePrefs)==null?void 0:de.columnSettingsMap,ce=FX(ge,ee,be,Ce,r,te);if(!ce){ut.error("Failed to generate CSV content");return}RC(ce,xe),ut.success("CSV exported successfully"),L();return}case"pivotTable":if(z){VX(z.data,r,xe,{delimiter:b.delimiter,includeHeaders:b.includeHeaders,includeSubtotals:!0,includeGrandTotal:!0,showRowTotals:(Se=z.options)==null?void 0:Se.showRowTotals}),ut.success("CSV exported successfully"),t();return}else{ut.error("Unable to export pivot table data");return}default:throw new Error(`Unsupported table type: ${r.type}`)}else{const se=Array.isArray(A)?A:(A==null?void 0:A.records)||[];if(!se||se.length===0){ut.error("No data available to export");return}const be=Object.keys(se[0]),Ce=ee=>{if(ee==null)return"";const te=String(ee);return te.includes(b.delimiter)||te.includes('"')||te.includes(`
815
815
  `)||te.includes("\r")?`"${te.replace(/"/g,'""')}"`:te},ge=[];b.includeHeaders&&ge.push(be.map(Ce).join(b.delimiter)),se.forEach(ee=>{const te=be.map(ce=>Ce(ee[ce]));ge.push(te.join(b.delimiter))}),ve=ge.join(`
816
816
  `)}if(!ve){ut.error("Failed to generate CSV content");return}RC(ve,xe),ut.success("CSV exported successfully"),L()}else{if(b.protectPdf&&!b.pdfPassword){ut.error("Please enter a password to protect the PDF");return}const ve=b.protectPdf?"Generating protected PDF... This may take up to 60 seconds depending on data size.":"Generating PDF... This may take up to 60 seconds depending on data size.";ut.info(ve);const xe={password:b.protectPdf?b.pdfPassword:void 0,pageSize:b.pageSize,orientation:b.orientation,wideTableStrategy:"auto",filterLine:Y,rowCount:X,tableStructure:Z,filterValues:_};let ke={success:!1};if(r.type&&["table","aggregateTable","pivotTable","detailTable"].includes(r.type)&&X>0&&X<=MP&&!K&&(r.type!=="pivotTable"||!!Z)&&(ke=await Mke(i.apiServiceUrl,o,r.id,n.id,U,r.type,xe),ue(ke.layoutApplied)),!ke.success){const Ce=xee(),ge=await Ike(i.apiServiceUrl,o,r.id,n.id,U,r.type,b.protectPdf?b.pdfPassword:void 0,b.pageSize,b.orientation,Y,_,Ce);ue(ge==null?void 0:ge.layoutApplied)}const be=b.protectPdf?"Protected PDF downloaded successfully":"PDF downloaded successfully";ut.success(be),L()}}catch(ue){console.error("Export error:",ue),ut.error("Failed to export",{description:m_(ue,"Please try again or contact support."),descriptionClassName:p_,closeButton:!0,duration:1/0})}finally{h(!1)}};return l.jsx(Oo,{open:e,onOpenChange:L,children:l.jsxs(mo,{className:"gap-0 overflow-hidden rounded-control border-border/60 p-0 sm:max-w-[420px] sm:rounded-control",children:[l.jsxs(na,{className:"border-b px-6 py-4 pr-12",children:[l.jsxs(go,{className:"text-[15px]",children:["Export ",U]}),l.jsx(si,{className:"text-[13px] leading-5",children:"Choose your export format and settings"})]}),l.jsxs("div",{className:"space-y-4 px-6 py-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:bp,children:"Export format"}),l.jsxs(Ia,{value:b.format,onValueChange:A=>x({...b,format:A}),className:"gap-1.5",children:[u.includes("pdf")&&q<=x1&&l.jsxs(m.Label,{htmlFor:"format-pdf",className:m.cn(y1,b.format==="pdf"&&"bg-muted/60"),children:[l.jsx(js,{value:"pdf",id:"format-pdf"}),l.jsx(vi,{className:"h-3.5 w-3.5 text-muted-foreground"}),"PDF document"]}),u.includes("csv")&&l.jsxs(m.Label,{htmlFor:"format-csv",className:m.cn(y1,b.format==="csv"&&"bg-muted/60"),children:[l.jsx(js,{value:"csv",id:"format-csv"}),l.jsx(gq,{className:"h-3.5 w-3.5 text-muted-foreground"}),"CSV"]})]})]}),l.jsx(m.Separator,{className:"bg-border/60"}),G&&l.jsxs(l.Fragment,{children:[l.jsxs(zP,{variant:"destructive",children:[l.jsx(ba,{className:"h-4 w-4"}),l.jsxs(BP,{children:["This dataset has ",q.toLocaleString()," rows, which exceeds the maximum of ",WD.toLocaleString()," ","rows. Please apply filters to reduce the dataset size."]})]}),l.jsx(m.Separator,{className:"bg-border/60"})]}),M&&b.format==="csv"&&!G&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-3",children:[l.jsx(m.Label,{className:bp,children:"Export size"}),l.jsxs("p",{className:"text-[12px] text-muted-foreground",children:["This dataset has ",q.toLocaleString()," rows"]}),l.jsxs(Ia,{value:b.exportMode,onValueChange:A=>x({...b,exportMode:A}),className:"gap-1.5",children:[l.jsxs(m.Label,{htmlFor:"export-local",className:m.cn(y1,"items-start",b.exportMode==="local"&&"bg-muted/60"),children:[l.jsx(js,{value:"local",id:"export-local",className:"mt-1"}),l.jsxs("div",{children:[l.jsxs("span",{className:"font-normal",children:[l.jsx("span",{className:"font-medium",children:"Download now"}),l.jsxs("span",{className:"ml-1 text-xs text-muted-foreground",children:["(limited to"," ",x1.toLocaleString()," rows)"]})]}),l.jsx("p",{className:"text-xs text-muted-foreground"})]})]}),l.jsxs(m.Label,{htmlFor:"export-async",className:m.cn(y1,"items-start",b.exportMode==="async"&&"bg-muted/60"),children:[l.jsx(js,{value:"async",id:"export-async",className:"mt-1"}),l.jsxs("div",{children:[l.jsxs("span",{className:"font-normal",children:[l.jsx("span",{className:"font-medium",children:"Export full dataset"}),l.jsxs("span",{className:"ml-1 text-xs text-muted-foreground",children:["(",q.toLocaleString()," rows)"]})]}),l.jsxs("p",{className:"flex items-center text-xs text-muted-foreground",children:[l.jsx(SS,{className:"mr-1 h-3 w-3"}),"You'll be notified when ready to download"]})]})]})]})]}),l.jsx(m.Separator,{className:"bg-border/60"})]}),b.format==="pdf"?l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{htmlFor:"pageSize",className:bp,children:"Page size"}),l.jsxs(m.Select,{value:b.pageSize,onValueChange:A=>x({...b,pageSize:A}),children:[l.jsx(m.SelectTrigger,{id:"pageSize",size:"sm",children:l.jsx(m.SelectValue,{})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"letter",children:'Letter (8.5" × 11")'}),l.jsx(m.SelectItem,{value:"a4",children:"A4 (210mm × 297mm)"})]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{htmlFor:"orientation",className:bp,children:"Orientation"}),l.jsxs(m.Select,{value:b.orientation,onValueChange:A=>x({...b,orientation:A}),children:[l.jsx(m.SelectTrigger,{id:"orientation",size:"sm",children:l.jsx(m.SelectValue,{})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"portrait",children:"Portrait"}),l.jsx(m.SelectItem,{value:"landscape",children:"Landscape"})]})]})]}),l.jsx(m.Separator,{className:"bg-border/60"}),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ln,{id:"protect-pdf",checked:b.protectPdf,onCheckedChange:A=>{x({...b,protectPdf:A,pdfPassword:A?b.pdfPassword:""}),A||g(!1)}}),l.jsxs(m.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[l.jsx(kk,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]})]}),b.protectPdf&&l.jsxs("div",{className:"ml-6 space-y-1.5",children:[l.jsx(m.Label,{htmlFor:"pdf-password",className:bp,children:"PDF password"}),l.jsxs("div",{className:"relative",children:[l.jsx(m.Input,{id:"pdf-password",type:p?"text":"password",value:b.pdfPassword,onChange:A=>x({...b,pdfPassword:A.target.value}),placeholder:"Enter password",className:"pr-10",size:"sm"}),l.jsx(m.Button,{type:"button",variant:"ghost",size:"sm",className:"absolute right-1 top-1/2 h-6 w-6 -translate-y-1/2 rounded-control p-0 hover:bg-muted",onClick:()=>g(!p),children:p?l.jsx(Nk,{className:"h-3.5 w-3.5 text-muted-foreground"}):l.jsx(tv,{className:"h-3.5 w-3.5 text-muted-foreground"})})]}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}):l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{htmlFor:"delimiter",className:bp,children:"Delimiter"}),l.jsxs(m.Select,{value:b.delimiter,onValueChange:A=>x({...b,delimiter:A}),children:[l.jsx(m.SelectTrigger,{id:"delimiter",size:"sm",children:l.jsx(m.SelectValue,{})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:",",children:"Comma (,)"}),l.jsx(m.SelectItem,{value:";",children:"Semicolon (;)"}),l.jsx(m.SelectItem,{value:" ",children:"Tab"})]})]})]}),l.jsx("div",{className:"space-y-2",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ln,{id:"include-headers",checked:b.includeHeaders,onCheckedChange:A=>x({...b,includeHeaders:A})}),l.jsx(m.Label,{htmlFor:"include-headers",className:"cursor-pointer text-[13px] font-normal",children:"Include column headers"})]})})]})]}),l.jsxs(Gc,{className:"border-t bg-muted/20 px-6 py-4 sm:justify-end sm:space-x-2",children:[l.jsx(m.Button,{variant:"outline",size:"xs",onClick:L,disabled:f,children:"Cancel"}),l.jsx(m.Button,{size:"xs",onClick:V,disabled:f||G,children:f?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),b.exportMode==="async"?"Starting...":"Exporting..."]}):b.exportMode==="async"?l.jsxs(l.Fragment,{children:[l.jsx(SS,{className:"h-3.5 w-3.5"}),"Start Export"]}):l.jsxs(l.Fragment,{children:[l.jsx(qc,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function DPe(e,t,n,r=!0,s,o=Intl.DateTimeFormat().resolvedOptions().timeZone,i=!0,a){if(e.length===0)return"";const c=n,u=[];return r&&u.push(c.map(TB).join(",")),e.forEach(d=>{const f=c.map(h=>{const p=d[h],g=IPe(p,h,t[h],s,o,i,a);return TB(g)});u.push(f.join(","))}),u.join(`
817
817
  `)}function IPe(e,t,n,r,s,o=!0,i){var c,u,d,f,h,p,g;const a=s||Intl.DateTimeFormat().resolvedOptions().timeZone;if(e==null)return"";if(typeof e=="number")try{const b=yv({card:i,columnId:t,existingSettings:n});if(b!=null&&b.type&&b.type!=="auto")return Fn(e,b.type,b)}catch{}if(!n)return String(e);if(n.type==="number"&&typeof e=="number")try{return Bn.formatNumberWithColumnSettings(e,n.numberFormat,((c=n.numberFormat)==null?void 0:c.locale)||"en-US")||e.toLocaleString()}catch{return e.toLocaleString()}else if(n.type==="date"&&e)try{if(!o)return String(e);if((u=n.dateFormat)!=null&&u.useRelativeTime)return Bn.formatRelativeTime(String(e),((d=n.dateFormat)==null?void 0:d.sourceTimezone)||"auto");{const b=VP(o,(f=n.dateFormat)==null?void 0:f.timezone,a,r),x=(h=n.dateFormat)!=null&&h.useCustomFormat?n.dateFormat.customFormat:((p=n.dateFormat)==null?void 0:p.format)||"MM/dd/yyyy";return Bn.formatDate(String(e),x,b,((g=n.dateFormat)==null?void 0:g.sourceTimezone)||"auto")}}catch{return String(e)}else{if(n.type==="badge")return String(e);if(n.type==="progress"&&typeof e=="number")return`${Math.min(Math.max(0,e),100)}%`;if(n.type==="link")return String(e)}return String(e)}function TB(e){return/[",\n\r]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function TPe(e,t,n){const r=new Blob([e],{type:n}),s=URL.createObjectURL(r),o=document.createElement("a");o.href=s,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(s)}function MPe(e,t,n,r="export.csv",s,o,i=!0,a){const c=DPe(e,t,n,!0,s,o,i,a);TPe(c,r,"text/csv;charset=utf-8;")}const zl=Q.forwardRef(({className:e,children:t,style:n,...r},s)=>l.jsxs(m.Root$1,{style:n,className:m.cn("relative overflow-hidden",e),children:[l.jsx(m.Viewport,{ref:s,...r,className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),l.jsx(m.ScrollBar,{className:"z-20"}),l.jsx(m.Corner,{})]}));zl.displayName=m.Root$1.displayName;/**
@@ -1297,7 +1297,7 @@ ${(e*100).toLocaleString()}%`}}},scales:{_index_:{display:!1,padding:10,grid:{di
1297
1297
  To pick up a draggable item, press the space bar.
1298
1298
  While dragging, use the arrow keys to move the item.
1299
1299
  Press space again to drop the item in its new position, or press escape to cancel.
1300
- `},iZe={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function aZe(e){let{announcements:t=iZe,container:n,hiddenTextDescribedById:r,screenReaderInstructions:s=oZe}=e;const{announce:o,announcement:i}=nZe(),a=tw("DndLiveRegion"),[c,u]=v.useState(!1);if(v.useEffect(()=>{u(!0)},[]),rZe(v.useMemo(()=>({onDragStart(f){let{active:h}=f;o(t.onDragStart({active:h}))},onDragMove(f){let{active:h,over:p}=f;t.onDragMove&&o(t.onDragMove({active:h,over:p}))},onDragOver(f){let{active:h,over:p}=f;o(t.onDragOver({active:h,over:p}))},onDragEnd(f){let{active:h,over:p}=f;o(t.onDragEnd({active:h,over:p}))},onDragCancel(f){let{active:h,over:p}=f;o(t.onDragCancel({active:h,over:p}))}}),[o,t])),!c)return null;const d=v.createElement(v.Fragment,null,v.createElement(eZe,{id:r,value:s.draggable}),v.createElement(tZe,{id:a,announcement:i}));return n?Sr.createPortal(d,n):d}var ps;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(ps||(ps={}));function KN(){}function cg(e,t){return v.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function Tj(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return v.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const Fa=Object.freeze({x:0,y:0});function oae(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function lZe(e,t){const n=GN(e);if(!n)return"0 0";const r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+"% "+r.y+"%"}function iae(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function cZe(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function k7(e){let{left:t,top:n,height:r,width:s}=e;return[{x:t,y:n},{x:t+s,y:n},{x:t,y:n+r},{x:t+s,y:n+r}]}function aae(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function _7(e,t,n){return t===void 0&&(t=e.left),n===void 0&&(n=e.top),{x:t+e.width*.5,y:n+e.height*.5}}const nw=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=_7(t,t.left,t.top),o=[];for(const i of r){const{id:a}=i,c=n.get(a);if(c){const u=oae(_7(c),s);o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(iae)},uZe=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=k7(t),o=[];for(const i of r){const{id:a}=i,c=n.get(a);if(c){const u=k7(c),d=s.reduce((h,p,g)=>h+oae(u[g],p),0),f=Number((d/4).toFixed(4));o.push({id:a,data:{droppableContainer:i,value:f}})}}return o.sort(iae)};function dZe(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),s=Math.min(t.left+t.width,e.left+e.width),o=Math.min(t.top+t.height,e.top+e.height),i=s-r,a=o-n;if(r<s&&n<o){const c=t.width*t.height,u=e.width*e.height,d=i*a,f=d/(c+u-d);return Number(f.toFixed(4))}return 0}const fZe=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=[];for(const o of r){const{id:i}=o,a=n.get(i);if(a){const c=dZe(a,t);c>0&&s.push({id:i,data:{droppableContainer:o,value:c}})}}return s.sort(cZe)};function hZe(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function lae(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Fa}function pZe(e){return function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s.reduce((i,a)=>({...i,top:i.top+e*a.y,bottom:i.bottom+e*a.y,left:i.left+e*a.x,right:i.right+e*a.x}),{...n})}}const mZe=pZe(1);function cae(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function gZe(e,t,n){const r=cae(t);if(!r)return e;const{scaleX:s,scaleY:o,x:i,y:a}=r,c=e.left-i-(1-s)*parseFloat(n),u=e.top-a-(1-o)*parseFloat(n.slice(n.indexOf(" ")+1)),d=s?e.width/s:e.width,f=o?e.height/o:e.height;return{width:d,height:f,top:u,right:c+d,bottom:u+f,left:c}}const bZe={ignoreTransform:!1};function lb(e,t){t===void 0&&(t=bZe);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:d}=Lo(e).getComputedStyle(e);u&&(n=gZe(n,u,d))}const{top:r,left:s,width:o,height:i,bottom:a,right:c}=n;return{top:r,left:s,width:o,height:i,bottom:a,right:c}}function j7(e){return lb(e,{ignoreTransform:!0})}function xZe(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function yZe(e,t){return t===void 0&&(t=Lo(e).getComputedStyle(e)),t.position==="fixed"}function vZe(e,t){t===void 0&&(t=Lo(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(s=>{const o=t[s];return typeof o=="string"?n.test(o):!1})}function Mj(e,t){const n=[];function r(s){if(t!=null&&n.length>=t||!s)return n;if(VL(s)&&s.scrollingElement!=null&&!n.includes(s.scrollingElement))return n.push(s.scrollingElement),n;if(!Jv(s)||nae(s)||n.includes(s))return n;const o=Lo(e).getComputedStyle(s);return s!==e&&vZe(s,o)&&n.push(s),yZe(s,o)?n:r(s.parentNode)}return e?r(e):n}function uae(e){const[t]=Mj(e,1);return t??null}function gT(e){return!Ej||!e?null:ib(e)?e:BL(e)?VL(e)||e===ab(e).scrollingElement?window:Jv(e)?e:null:null}function dae(e){return ib(e)?e.scrollX:e.scrollLeft}function fae(e){return ib(e)?e.scrollY:e.scrollTop}function fR(e){return{x:dae(e),y:fae(e)}}var ws;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(ws||(ws={}));function hae(e){return!Ej||!e?!1:e===document.scrollingElement}function pae(e){const t={x:0,y:0},n=hae(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},s=e.scrollTop<=t.y,o=e.scrollLeft<=t.x,i=e.scrollTop>=r.y,a=e.scrollLeft>=r.x;return{isTop:s,isLeft:o,isBottom:i,isRight:a,maxScroll:r,minScroll:t}}const wZe={x:.2,y:.2};function SZe(e,t,n,r,s){let{top:o,left:i,right:a,bottom:c}=n;r===void 0&&(r=10),s===void 0&&(s=wZe);const{isTop:u,isBottom:d,isLeft:f,isRight:h}=pae(e),p={x:0,y:0},g={x:0,y:0},b={height:t.height*s.y,width:t.width*s.x};return!u&&o<=t.top+b.height?(p.y=ws.Backward,g.y=r*Math.abs((t.top+b.height-o)/b.height)):!d&&c>=t.bottom-b.height&&(p.y=ws.Forward,g.y=r*Math.abs((t.bottom-b.height-c)/b.height)),!h&&a>=t.right-b.width?(p.x=ws.Forward,g.x=r*Math.abs((t.right-b.width-a)/b.width)):!f&&i<=t.left+b.width&&(p.x=ws.Backward,g.x=r*Math.abs((t.left+b.width-i)/b.width)),{direction:p,speed:g}}function CZe(e){if(e===document.scrollingElement){const{innerWidth:o,innerHeight:i}=window;return{top:0,left:0,right:o,bottom:i,width:o,height:i}}const{top:t,left:n,right:r,bottom:s}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:s,width:e.clientWidth,height:e.clientHeight}}function mae(e){return e.reduce((t,n)=>mm(t,fR(n)),Fa)}function NZe(e){return e.reduce((t,n)=>t+dae(n),0)}function kZe(e){return e.reduce((t,n)=>t+fae(n),0)}function gae(e,t){if(t===void 0&&(t=lb),!e)return;const{top:n,left:r,bottom:s,right:o}=t(e);uae(e)&&(s<=0||o<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const _Ze=[["x",["left","right"],NZe],["y",["top","bottom"],kZe]];class HL{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=Mj(n),s=mae(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,i,a]of _Ze)for(const c of i)Object.defineProperty(this,c,{get:()=>{const u=a(r),d=s[o]-u;return this.rect[c]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class by{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var s;(s=this.target)==null||s.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function jZe(e){const{EventTarget:t}=Lo(e);return e instanceof t?e:ab(e)}function bT(e,t){const n=Math.abs(e.x),r=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var Li;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Li||(Li={}));function E7(e){e.preventDefault()}function EZe(e){e.stopPropagation()}var In;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(In||(In={}));const bae={start:[In.Space,In.Enter],cancel:[In.Esc],end:[In.Space,In.Enter,In.Tab]},DZe=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case In.Right:return{...n,x:n.x+25};case In.Left:return{...n,x:n.x-25};case In.Down:return{...n,y:n.y+25};case In.Up:return{...n,y:n.y-25}}};class rw{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new by(ab(n)),this.windowListeners=new by(Lo(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Li.Resize,this.handleCancel),this.windowListeners.add(Li.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Li.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&gae(r),n(Fa)}handleKeyDown(t){if(Ij(t)){const{active:n,context:r,options:s}=this.props,{keyboardCodes:o=bae,coordinateGetter:i=DZe,scrollBehavior:a="smooth"}=s,{code:c}=t;if(o.end.includes(c)){this.handleEnd(t);return}if(o.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:Fa;this.referenceCoordinates||(this.referenceCoordinates=d);const f=i(t,{active:n,context:r.current,currentCoordinates:d});if(f){const h=k0(f,d),p={x:0,y:0},{scrollableAncestors:g}=r.current;for(const b of g){const x=t.code,{isTop:y,isRight:S,isLeft:w,isBottom:C,maxScroll:N,minScroll:k}=pae(b),_=CZe(b),E={x:Math.min(x===In.Right?_.right-_.width/2:_.right,Math.max(x===In.Right?_.left:_.left+_.width/2,f.x)),y:Math.min(x===In.Down?_.bottom-_.height/2:_.bottom,Math.max(x===In.Down?_.top:_.top+_.height/2,f.y))},D=x===In.Right&&!S||x===In.Left&&!w,j=x===In.Down&&!C||x===In.Up&&!y;if(D&&E.x!==f.x){const I=b.scrollLeft+h.x,T=x===In.Right&&I<=N.x||x===In.Left&&I>=k.x;if(T&&!h.y){b.scrollTo({left:I,behavior:a});return}T?p.x=b.scrollLeft-I:p.x=x===In.Right?b.scrollLeft-N.x:b.scrollLeft-k.x,p.x&&b.scrollBy({left:-p.x,behavior:a});break}else if(j&&E.y!==f.y){const I=b.scrollTop+h.y,T=x===In.Down&&I<=N.y||x===In.Up&&I>=k.y;if(T&&!h.x){b.scrollTo({top:I,behavior:a});return}T?p.y=b.scrollTop-I:p.y=x===In.Down?b.scrollTop-N.y:b.scrollTop-k.y,p.y&&b.scrollBy({top:-p.y,behavior:a});break}}this.handleMove(t,mm(k0(f,this.referenceCoordinates),p))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}rw.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=bae,onActivation:s}=t,{active:o}=n;const{code:i}=e.nativeEvent;if(r.start.includes(i)){const a=o.activatorNode.current;return a&&e.target!==a?!1:(e.preventDefault(),s==null||s({event:e.nativeEvent}),!0)}return!1}}];function D7(e){return!!(e&&"distance"in e)}function I7(e){return!!(e&&"delay"in e)}class UL{constructor(t,n,r){var s;r===void 0&&(r=jZe(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:o}=t,{target:i}=o;this.props=t,this.events=n,this.document=ab(i),this.documentListeners=new by(this.document),this.listeners=new by(r),this.windowListeners=new by(Lo(i)),this.initialCoordinates=(s=GN(o))!=null?s:Fa,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(Li.Resize,this.handleCancel),this.windowListeners.add(Li.DragStart,E7),this.windowListeners.add(Li.VisibilityChange,this.handleCancel),this.windowListeners.add(Li.ContextMenu,E7),this.documentListeners.add(Li.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(I7(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(D7(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:s}=this.props;s(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(Li.Click,EZe,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Li.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:s,props:o}=this,{onMove:i,options:{activationConstraint:a}}=o;if(!s)return;const c=(n=GN(t))!=null?n:Fa,u=k0(s,c);if(!r&&a){if(D7(a)){if(a.tolerance!=null&&bT(u,a.tolerance))return this.handleCancel();if(bT(u,a.distance))return this.handleStart()}if(I7(a)&&bT(u,a.tolerance))return this.handleCancel();this.handlePending(a,u);return}t.cancelable&&t.preventDefault(),i(c)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===In.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const IZe={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class cb extends UL{constructor(t){const{event:n}=t,r=ab(n.target);super(t,IZe,r)}}cb.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const TZe={move:{name:"mousemove"},end:{name:"mouseup"}};var hR;(function(e){e[e.RightClick=2]="RightClick"})(hR||(hR={}));class MZe extends UL{constructor(t){super(t,TZe,ab(t.event.target))}}MZe.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===hR.RightClick?!1:(r==null||r({event:n}),!0)}}];const xT={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class AZe extends UL{constructor(t){super(t,xT)}static setup(){return window.addEventListener(xT.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(xT.move.name,t)};function t(){}}}AZe.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:s}=n;return s.length>1?!1:(r==null||r({event:n}),!0)}}];var xy;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(xy||(xy={}));var ZN;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(ZN||(ZN={}));function RZe(e){let{acceleration:t,activator:n=xy.Pointer,canScroll:r,draggingRect:s,enabled:o,interval:i=5,order:a=ZN.TreeOrder,pointerCoordinates:c,scrollableAncestors:u,scrollableAncestorRects:d,delta:f,threshold:h}=e;const p=PZe({delta:f,disabled:!o}),[g,b]=KKe(),x=v.useRef({x:0,y:0}),y=v.useRef({x:0,y:0}),S=v.useMemo(()=>{switch(n){case xy.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case xy.DraggableRect:return s}},[n,s,c]),w=v.useRef(null),C=v.useCallback(()=>{const k=w.current;if(!k)return;const _=x.current.x*y.current.x,E=x.current.y*y.current.y;k.scrollBy(_,E)},[]),N=v.useMemo(()=>a===ZN.TreeOrder?[...u].reverse():u,[a,u]);v.useEffect(()=>{if(!o||!u.length||!S){b();return}for(const k of N){if((r==null?void 0:r(k))===!1)continue;const _=u.indexOf(k),E=d[_];if(!E)continue;const{direction:D,speed:j}=SZe(k,E,S,t,h);for(const I of["x","y"])p[I][D[I]]||(j[I]=0,D[I]=0);if(j.x>0||j.y>0){b(),w.current=k,g(C,i),x.current=j,y.current=D;return}}x.current={x:0,y:0},y.current={x:0,y:0},b()},[t,C,r,b,o,i,JSON.stringify(S),JSON.stringify(p),g,u,N,d,JSON.stringify(h)])}const FZe={x:{[ws.Backward]:!1,[ws.Forward]:!1},y:{[ws.Backward]:!1,[ws.Forward]:!1}};function PZe(e){let{delta:t,disabled:n}=e;const r=YN(t);return ew(s=>{if(n||!r||!s)return FZe;const o={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[ws.Backward]:s.x[ws.Backward]||o.x===-1,[ws.Forward]:s.x[ws.Forward]||o.x===1},y:{[ws.Backward]:s.y[ws.Backward]||o.y===-1,[ws.Forward]:s.y[ws.Forward]||o.y===1}}},[n,t,r])}function OZe(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return ew(s=>{var o;return t==null?null:(o=r??s)!=null?o:null},[r,t])}function LZe(e,t){return v.useMemo(()=>e.reduce((n,r)=>{const{sensor:s}=r,o=s.activators.map(i=>({eventName:i.eventName,handler:t(i.handler,r)}));return[...n,...o]},[]),[e,t])}var _0;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(_0||(_0={}));var pR;(function(e){e.Optimized="optimized"})(pR||(pR={}));const T7=new Map;function $Ze(e,t){let{dragging:n,dependencies:r,config:s}=t;const[o,i]=v.useState(null),{frequency:a,measure:c,strategy:u}=s,d=v.useRef(e),f=x(),h=N0(f),p=v.useCallback(function(y){y===void 0&&(y=[]),!h.current&&i(S=>S===null?y:S.concat(y.filter(w=>!S.includes(w))))},[h]),g=v.useRef(null),b=ew(y=>{if(f&&!n)return T7;if(!y||y===T7||d.current!==e||o!=null){const S=new Map;for(let w of e){if(!w)continue;if(o&&o.length>0&&!o.includes(w.id)&&w.rect.current){S.set(w.id,w.rect.current);continue}const C=w.node.current,N=C?new HL(c(C),C):null;w.rect.current=N,N&&S.set(w.id,N)}return S}return y},[e,o,n,f,c]);return v.useEffect(()=>{d.current=e},[e]),v.useEffect(()=>{f||p()},[n,f]),v.useEffect(()=>{o&&o.length>0&&i(null)},[JSON.stringify(o)]),v.useEffect(()=>{f||typeof a!="number"||g.current!==null||(g.current=setTimeout(()=>{p(),g.current=null},a))},[a,f,p,...r]),{droppableRects:b,measureDroppableContainers:p,measuringScheduled:o!=null};function x(){switch(u){case _0.Always:return!1;case _0.BeforeDragging:return n;default:return!n}}}function WL(e,t){return ew(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function zZe(e,t){return WL(e,t)}function BZe(e){let{callback:t,disabled:n}=e;const r=Dj(t),s=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(r)},[r,n]);return v.useEffect(()=>()=>s==null?void 0:s.disconnect(),[s]),s}function Aj(e){let{callback:t,disabled:n}=e;const r=Dj(t),s=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(r)},[n]);return v.useEffect(()=>()=>s==null?void 0:s.disconnect(),[s]),s}function VZe(e){return new HL(lb(e),e)}function M7(e,t,n){t===void 0&&(t=VZe);const[r,s]=v.useState(null);function o(){s(c=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=c??n)!=null?u:null}const d=t(e);return JSON.stringify(c)===JSON.stringify(d)?c:d})}const i=BZe({callback(c){if(e)for(const u of c){const{type:d,target:f}=u;if(d==="childList"&&f instanceof HTMLElement&&f.contains(e)){o();break}}}}),a=Aj({callback:o});return Ra(()=>{o(),e?(a==null||a.observe(e),i==null||i.observe(document.body,{childList:!0,subtree:!0})):(a==null||a.disconnect(),i==null||i.disconnect())},[e]),r}function HZe(e){const t=WL(e);return lae(e,t)}const A7=[];function UZe(e){const t=v.useRef(e),n=ew(r=>e?r&&r!==A7&&e&&t.current&&e.parentNode===t.current.parentNode?r:Mj(e):A7,[e]);return v.useEffect(()=>{t.current=e},[e]),n}function WZe(e){const[t,n]=v.useState(null),r=v.useRef(e),s=v.useCallback(o=>{const i=gT(o.target);i&&n(a=>a?(a.set(i,fR(i)),new Map(a)):null)},[]);return v.useEffect(()=>{const o=r.current;if(e!==o){i(o);const a=e.map(c=>{const u=gT(c);return u?(u.addEventListener("scroll",s,{passive:!0}),[u,fR(u)]):null}).filter(c=>c!=null);n(a.length?new Map(a):null),r.current=e}return()=>{i(e),i(o)};function i(a){a.forEach(c=>{const u=gT(c);u==null||u.removeEventListener("scroll",s)})}},[s,e]),v.useMemo(()=>e.length?t?Array.from(t.values()).reduce((o,i)=>mm(o,i),Fa):mae(e):Fa,[e,t])}function R7(e,t){t===void 0&&(t=[]);const n=v.useRef(null);return v.useEffect(()=>{n.current=null},t),v.useEffect(()=>{const r=e!==Fa;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?k0(e,n.current):Fa}function qZe(e){v.useEffect(()=>{if(!Ej)return;const t=e.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n==null||n()}},e.map(t=>{let{sensor:n}=t;return n}))}function YZe(e,t){return v.useMemo(()=>e.reduce((n,r)=>{let{eventName:s,handler:o}=r;return n[s]=i=>{o(i,t)},n},{}),[e,t])}function xae(e){return v.useMemo(()=>e?xZe(e):null,[e])}const F7=[];function GZe(e,t){t===void 0&&(t=lb);const[n]=e,r=xae(n?Lo(n):null),[s,o]=v.useState(F7);function i(){o(()=>e.length?e.map(c=>hae(c)?r:new HL(t(c),c)):F7)}const a=Aj({callback:i});return Ra(()=>{a==null||a.disconnect(),i(),e.forEach(c=>a==null?void 0:a.observe(c))},[e]),s}function yae(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Jv(t)?t:e}function KZe(e){let{measure:t}=e;const[n,r]=v.useState(null),s=v.useCallback(u=>{for(const{target:d}of u)if(Jv(d)){r(f=>{const h=t(d);return f?{...f,width:h.width,height:h.height}:h});break}},[t]),o=Aj({callback:s}),i=v.useCallback(u=>{const d=yae(u);o==null||o.disconnect(),d&&(o==null||o.observe(d)),r(d?t(d):null)},[t,o]),[a,c]=qN(i);return v.useMemo(()=>({nodeRef:a,rect:n,setRef:c}),[n,a,c])}const ZZe=[{sensor:cb,options:{}},{sensor:rw,options:{}}],XZe={current:{}},eC={draggable:{measure:j7},droppable:{measure:j7,strategy:_0.WhileDragging,frequency:pR.Optimized},dragOverlay:{measure:lb}};class yy extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const QZe={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new yy,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:KN},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:eC,measureDroppableContainers:KN,windowRect:null,measuringScheduled:!1},vae={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:KN,draggableNodes:new Map,over:null,measureDroppableContainers:KN},sw=v.createContext(vae),wae=v.createContext(QZe);function JZe(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new yy}}}function eXe(e,t){switch(t.type){case ps.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case ps.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case ps.DragEnd:case ps.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ps.RegisterDroppable:{const{element:n}=t,{id:r}=n,s=new yy(e.droppable.containers);return s.set(r,n),{...e,droppable:{...e.droppable,containers:s}}}case ps.SetDroppableDisabled:{const{id:n,key:r,disabled:s}=t,o=e.droppable.containers.get(n);if(!o||r!==o.key)return e;const i=new yy(e.droppable.containers);return i.set(n,{...o,disabled:s}),{...e,droppable:{...e.droppable,containers:i}}}case ps.UnregisterDroppable:{const{id:n,key:r}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const o=new yy(e.droppable.containers);return o.delete(n),{...e,droppable:{...e.droppable,containers:o}}}default:return e}}function tXe(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:s}=v.useContext(sw),o=YN(r),i=YN(n==null?void 0:n.id);return v.useEffect(()=>{if(!t&&!r&&o&&i!=null){if(!Ij(o)||document.activeElement===o.target)return;const a=s.get(i);if(!a)return;const{activatorNode:c,node:u}=a;if(!c.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[c.current,u.current]){if(!d)continue;const f=QKe(d);if(f){f.focus();break}}})}},[r,t,s,i,o]),null}function Sae(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((s,o)=>o({transform:s,...r}),n):n}function nXe(e){return v.useMemo(()=>({draggable:{...eC.draggable,...e==null?void 0:e.draggable},droppable:{...eC.droppable,...e==null?void 0:e.droppable},dragOverlay:{...eC.dragOverlay,...e==null?void 0:e.dragOverlay}}),[e==null?void 0:e.draggable,e==null?void 0:e.droppable,e==null?void 0:e.dragOverlay])}function rXe(e){let{activeNode:t,measure:n,initialRect:r,config:s=!0}=e;const o=v.useRef(!1),{x:i,y:a}=typeof s=="boolean"?{x:s,y:s}:s;Ra(()=>{if(!i&&!a||!t){o.current=!1;return}if(o.current||!r)return;const u=t==null?void 0:t.node.current;if(!u||u.isConnected===!1)return;const d=n(u),f=lae(d,r);if(i||(f.x=0),a||(f.y=0),o.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const h=uae(u);h&&h.scrollBy({top:f.y,left:f.x})}},[t,i,a,r,n])}const Rj=v.createContext({...Fa,scaleX:1,scaleY:1});var yu;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(yu||(yu={}));const ow=v.memo(function(t){var n,r,s,o;let{id:i,accessibility:a,autoScroll:c=!0,children:u,sensors:d=ZZe,collisionDetection:f=fZe,measuring:h,modifiers:p,...g}=t;const b=v.useReducer(eXe,void 0,JZe),[x,y]=b,[S,w]=sZe(),[C,N]=v.useState(yu.Uninitialized),k=C===yu.Initialized,{draggable:{active:_,nodes:E,translate:D},droppable:{containers:j}}=x,I=_!=null?E.get(_):null,T=v.useRef({initial:null,translated:null}),F=v.useMemo(()=>{var Ve;return _!=null?{id:_,data:(Ve=I==null?void 0:I.data)!=null?Ve:XZe,rect:T}:null},[_,I]),P=v.useRef(null),[R,B]=v.useState(null),[z,U]=v.useState(null),Y=N0(g,Object.values(g)),O=tw("DndDescribedBy",i),K=v.useMemo(()=>j.getEnabled(),[j]),q=nXe(h),{droppableRects:M,measureDroppableContainers:G,measuringScheduled:L}=$Ze(K,{dragging:k,dependencies:[D.x,D.y],config:q.droppable}),$=OZe(E,_),V=v.useMemo(()=>z?GN(z):null,[z]),H=Ye(),A=zZe($,q.draggable.measure);rXe({activeNode:_!=null?E.get(_):null,config:H.layoutShiftCompensation,initialRect:A,measure:q.draggable.measure});const W=M7($,q.draggable.measure,A),X=M7($?$.parentElement:null),Z=v.useRef({activatorEvent:null,active:null,activeNode:$,collisionRect:null,collisions:null,droppableRects:M,draggableNodes:E,draggingNode:null,draggingNodeRect:null,droppableContainers:j,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),J=j.getNodeFor((n=Z.current.over)==null?void 0:n.id),re=KZe({measure:q.dragOverlay.measure}),fe=(r=re.nodeRef.current)!=null?r:$,de=k?(s=re.rect)!=null?s:W:null,Se=!!(re.nodeRef.current&&re.rect),ue=HZe(Se?null:W),ve=xae(fe?Lo(fe):null),xe=UZe(k?J??$:null),ke=GZe(xe),se=Sae(p,{transform:{x:D.x-ue.x,y:D.y-ue.y,scaleX:1,scaleY:1},activatorEvent:z,active:F,activeNodeRect:W,containerNodeRect:X,draggingNodeRect:de,over:Z.current.over,overlayNodeRect:re.rect,scrollableAncestors:xe,scrollableAncestorRects:ke,windowRect:ve}),be=V?mm(V,D):null,Ce=WZe(xe),ge=R7(Ce),ee=R7(Ce,[W]),te=mm(se,ge),ce=de?mZe(de,se):null,le=F&&ce?f({active:F,collisionRect:ce,droppableRects:M,droppableContainers:K,pointerCoordinates:be}):null,Ee=aae(le,"id"),[ye,ne]=v.useState(null),je=Se?se:mm(se,ee),Ue=hZe(je,(o=ye==null?void 0:ye.rect)!=null?o:null,W),Be=v.useRef(null),rt=v.useCallback((Ve,$e)=>{let{sensor:Ae,options:Re}=$e;if(P.current==null)return;const He=E.get(P.current);if(!He)return;const Ge=Ve.nativeEvent,ht=new Ae({active:P.current,activeNode:He,event:Ge,options:Re,context:Z,onAbort(st){if(!E.get(st))return;const{onDragAbort:Ke}=Y.current,_t={id:st};Ke==null||Ke(_t),S({type:"onDragAbort",event:_t})},onPending(st,Fe,Ke,_t){if(!E.get(st))return;const{onDragPending:Ze}=Y.current,at={id:st,constraint:Fe,initialCoordinates:Ke,offset:_t};Ze==null||Ze(at),S({type:"onDragPending",event:at})},onStart(st){const Fe=P.current;if(Fe==null)return;const Ke=E.get(Fe);if(!Ke)return;const{onDragStart:_t}=Y.current,Te={activatorEvent:Ge,active:{id:Fe,data:Ke.data,rect:T}};Sr.unstable_batchedUpdates(()=>{_t==null||_t(Te),N(yu.Initializing),y({type:ps.DragStart,initialCoordinates:st,active:Fe}),S({type:"onDragStart",event:Te}),B(Be.current),U(Ge)})},onMove(st){y({type:ps.DragMove,coordinates:st})},onEnd:lt(ps.DragEnd),onCancel:lt(ps.DragCancel)});Be.current=ht;function lt(st){return async function(){const{active:Ke,collisions:_t,over:Te,scrollAdjustedTranslate:Ze}=Z.current;let at=null;if(Ke&&Ze){const{cancelDrop:bt}=Y.current;at={activatorEvent:Ge,active:Ke,collisions:_t,delta:Ze,over:Te},st===ps.DragEnd&&typeof bt=="function"&&await Promise.resolve(bt(at))&&(st=ps.DragCancel)}P.current=null,Sr.unstable_batchedUpdates(()=>{y({type:st}),N(yu.Uninitialized),ne(null),B(null),U(null),Be.current=null;const bt=st===ps.DragEnd?"onDragEnd":"onDragCancel";if(at){const ft=Y.current[bt];ft==null||ft(at),S({type:bt,event:at})}})}}},[E]),Xe=v.useCallback((Ve,$e)=>(Ae,Re)=>{const He=Ae.nativeEvent,Ge=E.get(Re);if(P.current!==null||!Ge||He.dndKit||He.defaultPrevented)return;const ht={active:Ge};Ve(Ae,$e.options,ht)===!0&&(He.dndKit={capturedBy:$e.sensor},P.current=Re,rt(Ae,$e))},[E,rt]),et=LZe(d,Xe);qZe(d),Ra(()=>{W&&C===yu.Initializing&&N(yu.Initialized)},[W,C]),v.useEffect(()=>{const{onDragMove:Ve}=Y.current,{active:$e,activatorEvent:Ae,collisions:Re,over:He}=Z.current;if(!$e||!Ae)return;const Ge={active:$e,activatorEvent:Ae,collisions:Re,delta:{x:te.x,y:te.y},over:He};Sr.unstable_batchedUpdates(()=>{Ve==null||Ve(Ge),S({type:"onDragMove",event:Ge})})},[te.x,te.y]),v.useEffect(()=>{const{active:Ve,activatorEvent:$e,collisions:Ae,droppableContainers:Re,scrollAdjustedTranslate:He}=Z.current;if(!Ve||P.current==null||!$e||!He)return;const{onDragOver:Ge}=Y.current,ht=Re.get(Ee),lt=ht&&ht.rect.current?{id:ht.id,rect:ht.rect.current,data:ht.data,disabled:ht.disabled}:null,st={active:Ve,activatorEvent:$e,collisions:Ae,delta:{x:He.x,y:He.y},over:lt};Sr.unstable_batchedUpdates(()=>{ne(lt),Ge==null||Ge(st),S({type:"onDragOver",event:st})})},[Ee]),Ra(()=>{Z.current={activatorEvent:z,active:F,activeNode:$,collisionRect:ce,collisions:le,droppableRects:M,draggableNodes:E,draggingNode:fe,draggingNodeRect:de,droppableContainers:j,over:ye,scrollableAncestors:xe,scrollAdjustedTranslate:te},T.current={initial:de,translated:ce}},[F,$,le,ce,E,fe,de,M,j,ye,xe,te]),RZe({...H,delta:D,draggingRect:ce,pointerCoordinates:be,scrollableAncestors:xe,scrollableAncestorRects:ke});const tt=v.useMemo(()=>({active:F,activeNode:$,activeNodeRect:W,activatorEvent:z,collisions:le,containerNodeRect:X,dragOverlay:re,draggableNodes:E,droppableContainers:j,droppableRects:M,over:ye,measureDroppableContainers:G,scrollableAncestors:xe,scrollableAncestorRects:ke,measuringConfiguration:q,measuringScheduled:L,windowRect:ve}),[F,$,W,z,le,X,re,E,j,M,ye,G,xe,ke,q,L,ve]),me=v.useMemo(()=>({activatorEvent:z,activators:et,active:F,activeNodeRect:W,ariaDescribedById:{draggable:O},dispatch:y,draggableNodes:E,over:ye,measureDroppableContainers:G}),[z,et,F,W,y,O,E,ye,G]);return v.createElement(sae.Provider,{value:w},v.createElement(sw.Provider,{value:me},v.createElement(wae.Provider,{value:tt},v.createElement(Rj.Provider,{value:Ue},u)),v.createElement(tXe,{disabled:(a==null?void 0:a.restoreFocus)===!1})),v.createElement(aZe,{...a,hiddenTextDescribedById:O}));function Ye(){const Ve=(R==null?void 0:R.autoScrollEnabled)===!1,$e=typeof c=="object"?c.enabled===!1:c===!1,Ae=k&&!Ve&&!$e;return typeof c=="object"?{...c,enabled:Ae}:{enabled:Ae}}}),sXe=v.createContext(null),P7="button",oXe="Draggable";function iXe(e){let{id:t,data:n,disabled:r=!1,attributes:s}=e;const o=tw(oXe),{activators:i,activatorEvent:a,active:c,activeNodeRect:u,ariaDescribedById:d,draggableNodes:f,over:h}=v.useContext(sw),{role:p=P7,roleDescription:g="draggable",tabIndex:b=0}=s??{},x=(c==null?void 0:c.id)===t,y=v.useContext(x?Rj:sXe),[S,w]=qN(),[C,N]=qN(),k=YZe(i,t),_=N0(n);Ra(()=>(f.set(t,{id:t,key:o,node:S,activatorNode:C,data:_}),()=>{const D=f.get(t);D&&D.key===o&&f.delete(t)}),[f,t]);const E=v.useMemo(()=>({role:p,tabIndex:b,"aria-disabled":r,"aria-pressed":x&&p===P7?!0:void 0,"aria-roledescription":g,"aria-describedby":d.draggable}),[r,p,b,x,g,d.draggable]);return{active:c,activatorEvent:a,activeNodeRect:u,attributes:E,isDragging:x,listeners:r?void 0:k,node:S,over:h,setNodeRef:w,setActivatorNodeRef:N,transform:y}}function Cae(){return v.useContext(wae)}const aXe="Droppable",lXe={timeout:25};function Nae(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:s}=e;const o=tw(aXe),{active:i,dispatch:a,over:c,measureDroppableContainers:u}=v.useContext(sw),d=v.useRef({disabled:n}),f=v.useRef(!1),h=v.useRef(null),p=v.useRef(null),{disabled:g,updateMeasurementsFor:b,timeout:x}={...lXe,...s},y=N0(b??r),S=v.useCallback(()=>{if(!f.current){f.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{u(Array.isArray(y.current)?y.current:[y.current]),p.current=null},x)},[x]),w=Aj({callback:S,disabled:g||!i}),C=v.useCallback((E,D)=>{w&&(D&&(w.unobserve(D),f.current=!1),E&&w.observe(E))},[w]),[N,k]=qN(C),_=N0(t);return v.useEffect(()=>{!w||!N.current||(w.disconnect(),f.current=!1,w.observe(N.current))},[N,w]),v.useEffect(()=>(a({type:ps.RegisterDroppable,element:{id:r,key:o,disabled:n,node:N,rect:h,data:_}}),()=>a({type:ps.UnregisterDroppable,key:o,id:r})),[r]),v.useEffect(()=>{n!==d.current.disabled&&(a({type:ps.SetDroppableDisabled,id:r,key:o,disabled:n}),d.current.disabled=n)},[r,o,n,a]),{active:i,rect:h,isOver:(c==null?void 0:c.id)===r,node:N,over:c,setNodeRef:k}}function cXe(e){let{animation:t,children:n}=e;const[r,s]=v.useState(null),[o,i]=v.useState(null),a=YN(n);return!n&&!r&&a&&s(a),Ra(()=>{if(!o)return;const c=r==null?void 0:r.key,u=r==null?void 0:r.props.id;if(c==null||u==null){s(null);return}Promise.resolve(t(u,o)).then(()=>{s(null)})},[t,r,o]),v.createElement(v.Fragment,null,n,r?v.cloneElement(r,{ref:i}):null)}const uXe={x:0,y:0,scaleX:1,scaleY:1};function dXe(e){let{children:t}=e;return v.createElement(sw.Provider,{value:vae},v.createElement(Rj.Provider,{value:uXe},t))}const fXe={position:"fixed",touchAction:"none"},hXe=e=>Ij(e)?"transform 250ms ease":void 0,pXe=v.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:s,children:o,className:i,rect:a,style:c,transform:u,transition:d=hXe}=e;if(!a)return null;const f=s?u:{...u,scaleX:1,scaleY:1},h={...fXe,width:a.width,height:a.height,top:a.top,left:a.left,transform:_i.Transform.toString(f),transformOrigin:s&&r?lZe(r,a):void 0,transition:typeof d=="function"?d(r):d,...c};return v.createElement(n,{className:i,style:h,ref:t},o)}),mXe=e=>t=>{let{active:n,dragOverlay:r}=t;const s={},{styles:o,className:i}=e;if(o!=null&&o.active)for(const[a,c]of Object.entries(o.active))c!==void 0&&(s[a]=n.node.style.getPropertyValue(a),n.node.style.setProperty(a,c));if(o!=null&&o.dragOverlay)for(const[a,c]of Object.entries(o.dragOverlay))c!==void 0&&r.node.style.setProperty(a,c);return i!=null&&i.active&&n.node.classList.add(i.active),i!=null&&i.dragOverlay&&r.node.classList.add(i.dragOverlay),function(){for(const[c,u]of Object.entries(s))n.node.style.setProperty(c,u);i!=null&&i.active&&n.node.classList.remove(i.active)}},gXe=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:_i.Transform.toString(t)},{transform:_i.Transform.toString(n)}]},bXe={duration:250,easing:"ease",keyframes:gXe,sideEffects:mXe({styles:{active:{opacity:"0"}}})};function xXe(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:s}=e;return Dj((o,i)=>{if(t===null)return;const a=n.get(o);if(!a)return;const c=a.node.current;if(!c)return;const u=yae(i);if(!u)return;const{transform:d}=Lo(i).getComputedStyle(i),f=cae(d);if(!f)return;const h=typeof t=="function"?t:yXe(t);return gae(c,s.draggable.measure),h({active:{id:o,data:a.data,node:c,rect:s.draggable.measure(c)},draggableNodes:n,dragOverlay:{node:i,rect:s.dragOverlay.measure(u)},droppableContainers:r,measuringConfiguration:s,transform:f})})}function yXe(e){const{duration:t,easing:n,sideEffects:r,keyframes:s}={...bXe,...e};return o=>{let{active:i,dragOverlay:a,transform:c,...u}=o;if(!t)return;const d={x:a.rect.left-i.rect.left,y:a.rect.top-i.rect.top},f={scaleX:c.scaleX!==1?i.rect.width*c.scaleX/a.rect.width:1,scaleY:c.scaleY!==1?i.rect.height*c.scaleY/a.rect.height:1},h={x:c.x-d.x,y:c.y-d.y,...f},p=s({...u,active:i,dragOverlay:a,transform:{initial:c,final:h}}),[g]=p,b=p[p.length-1];if(JSON.stringify(g)===JSON.stringify(b))return;const x=r==null?void 0:r({active:i,dragOverlay:a,...u}),y=a.node.animate(p,{duration:t,easing:n,fill:"forwards"});return new Promise(S=>{y.onfinish=()=>{x==null||x(),S()}})}}let O7=0;function vXe(e){return v.useMemo(()=>{if(e!=null)return O7++,O7},[e])}const kae=v.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:s,transition:o,modifiers:i,wrapperElement:a="div",className:c,zIndex:u=999}=e;const{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:p,draggableNodes:g,droppableContainers:b,dragOverlay:x,over:y,measuringConfiguration:S,scrollableAncestors:w,scrollableAncestorRects:C,windowRect:N}=Cae(),k=v.useContext(Rj),_=vXe(f==null?void 0:f.id),E=Sae(i,{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:p,draggingNodeRect:x.rect,over:y,overlayNodeRect:x.rect,scrollableAncestors:w,scrollableAncestorRects:C,transform:k,windowRect:N}),D=WL(h),j=xXe({config:r,draggableNodes:g,droppableContainers:b,measuringConfiguration:S}),I=D?x.setRef:void 0;return v.createElement(dXe,null,v.createElement(cXe,{animation:j},f&&_?v.createElement(pXe,{key:_,id:f.id,ref:I,as:a,activatorEvent:d,adjustScale:t,className:c,transition:o,rect:D,style:{zIndex:u,...s},transform:E},n):null))});function ub(e,t,n){const r=e.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function wXe(e,t){return e.reduce((n,r,s)=>{const o=t.get(r);return o&&(n[s]=o),n},Array(e.length))}function J1(e){return e!==null&&e>=0}function SXe(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function CXe(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const eS={scaleX:1,scaleY:1},qL=e=>{var t;let{rects:n,activeNodeRect:r,activeIndex:s,overIndex:o,index:i}=e;const a=(t=n[s])!=null?t:r;if(!a)return null;const c=NXe(n,i,s);if(i===s){const u=n[o];return u?{x:s<o?u.left+u.width-(a.left+a.width):u.left-a.left,y:0,...eS}:null}return i>s&&i<=o?{x:-a.width-c,y:0,...eS}:i<s&&i>=o?{x:a.width+c,y:0,...eS}:{x:0,y:0,...eS}};function NXe(e,t,n){const r=e[t],s=e[t-1],o=e[t+1];return!r||!s&&!o?0:n<t?s?r.left-(s.left+s.width):o.left-(r.left+r.width):o?o.left-(r.left+r.width):r.left-(s.left+s.width)}const _ae=e=>{let{rects:t,activeIndex:n,overIndex:r,index:s}=e;const o=ub(t,r,n),i=t[s],a=o[s];return!a||!i?null:{x:a.left-i.left,y:a.top-i.top,scaleX:a.width/i.width,scaleY:a.height/i.height}},tS={scaleX:1,scaleY:1},YL=e=>{var t;let{activeIndex:n,activeNodeRect:r,index:s,rects:o,overIndex:i}=e;const a=(t=o[n])!=null?t:r;if(!a)return null;if(s===n){const u=o[i];return u?{x:0,y:n<i?u.top+u.height-(a.top+a.height):u.top-a.top,...tS}:null}const c=kXe(o,s,n);return s>n&&s<=i?{x:0,y:-a.height-c,...tS}:s<n&&s>=i?{x:0,y:a.height+c,...tS}:{x:0,y:0,...tS}};function kXe(e,t,n){const r=e[t],s=e[t-1],o=e[t+1];return r?n<t?s?r.top-(s.top+s.height):o?o.top-(r.top+r.height):0:o?o.top-(r.top+r.height):s?r.top-(s.top+s.height):0:0}const jae="Sortable",Eae=v.createContext({activeIndex:-1,containerId:jae,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:_ae,disabled:{draggable:!1,droppable:!1}});function iw(e){let{children:t,id:n,items:r,strategy:s=_ae,disabled:o=!1}=e;const{active:i,dragOverlay:a,droppableRects:c,over:u,measureDroppableContainers:d}=Cae(),f=tw(jae,n),h=a.rect!==null,p=v.useMemo(()=>r.map(k=>typeof k=="object"&&"id"in k?k.id:k),[r]),g=i!=null,b=i?p.indexOf(i.id):-1,x=u?p.indexOf(u.id):-1,y=v.useRef(p),S=!SXe(p,y.current),w=x!==-1&&b===-1||S,C=CXe(o);Ra(()=>{S&&g&&d(p)},[S,p,g,d]),v.useEffect(()=>{y.current=p},[p]);const N=v.useMemo(()=>({activeIndex:b,containerId:f,disabled:C,disableTransforms:w,items:p,overIndex:x,useDragOverlay:h,sortedRects:wXe(p,c),strategy:s}),[b,f,C.draggable,C.droppable,w,p,x,c,h,s]);return v.createElement(Eae.Provider,{value:N},t)}const _Xe=e=>{let{id:t,items:n,activeIndex:r,overIndex:s}=e;return ub(n,r,s).indexOf(t)},jXe=e=>{let{containerId:t,isSorting:n,wasDragging:r,index:s,items:o,newIndex:i,previousItems:a,previousContainerId:c,transition:u}=e;return!u||!r||a!==o&&s===i?!1:n?!0:i!==s&&t===c},EXe={duration:200,easing:"ease"},Dae="transform",DXe=_i.Transition.toString({property:Dae,duration:0,easing:"linear"}),IXe={roleDescription:"sortable"};function TXe(e){let{disabled:t,index:n,node:r,rect:s}=e;const[o,i]=v.useState(null),a=v.useRef(n);return Ra(()=>{if(!t&&n!==a.current&&r.current){const c=s.current;if(c){const u=lb(r.current,{ignoreTransform:!0}),d={x:c.left-u.left,y:c.top-u.top,scaleX:c.width/u.width,scaleY:c.height/u.height};(d.x||d.y)&&i(d)}}n!==a.current&&(a.current=n)},[t,n,r,s]),v.useEffect(()=>{o&&i(null)},[o]),o}function db(e){let{animateLayoutChanges:t=jXe,attributes:n,disabled:r,data:s,getNewIndex:o=_Xe,id:i,strategy:a,resizeObserverConfig:c,transition:u=EXe}=e;const{items:d,containerId:f,activeIndex:h,disabled:p,disableTransforms:g,sortedRects:b,overIndex:x,useDragOverlay:y,strategy:S}=v.useContext(Eae),w=MXe(r,p),C=d.indexOf(i),N=v.useMemo(()=>({sortable:{containerId:f,index:C,items:d},...s}),[f,s,C,d]),k=v.useMemo(()=>d.slice(d.indexOf(i)),[d,i]),{rect:_,node:E,isOver:D,setNodeRef:j}=Nae({id:i,data:N,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:k,...c}}),{active:I,activatorEvent:T,activeNodeRect:F,attributes:P,setNodeRef:R,listeners:B,isDragging:z,over:U,setActivatorNodeRef:Y,transform:O}=iXe({id:i,data:N,attributes:{...IXe,...n},disabled:w.draggable}),K=GKe(j,R),q=!!I,M=q&&!g&&J1(h)&&J1(x),G=!y&&z,L=G&&M?O:null,V=M?L??(a??S)({rects:b,activeNodeRect:F,activeIndex:h,overIndex:x,index:C}):null,H=J1(h)&&J1(x)?o({id:i,items:d,activeIndex:h,overIndex:x}):C,A=I==null?void 0:I.id,W=v.useRef({activeId:A,items:d,newIndex:H,containerId:f}),X=d!==W.current.items,Z=t({active:I,containerId:f,isDragging:z,isSorting:q,id:i,index:C,items:d,newIndex:W.current.newIndex,previousItems:W.current.items,previousContainerId:W.current.containerId,transition:u,wasDragging:W.current.activeId!=null}),J=TXe({disabled:!Z,index:C,node:E,rect:_});return v.useEffect(()=>{q&&W.current.newIndex!==H&&(W.current.newIndex=H),f!==W.current.containerId&&(W.current.containerId=f),d!==W.current.items&&(W.current.items=d)},[q,H,f,d]),v.useEffect(()=>{if(A===W.current.activeId)return;if(A!=null&&W.current.activeId==null){W.current.activeId=A;return}const fe=setTimeout(()=>{W.current.activeId=A},50);return()=>clearTimeout(fe)},[A]),{active:I,activeIndex:h,attributes:P,data:N,rect:_,index:C,newIndex:H,items:d,isOver:D,isSorting:q,isDragging:z,listeners:B,node:E,overIndex:x,over:U,setNodeRef:K,setActivatorNodeRef:Y,setDroppableNodeRef:j,setDraggableNodeRef:R,transform:J??V,transition:re()};function re(){if(J||X&&W.current.newIndex===C)return DXe;if(!(G&&!Ij(T)||!u)&&(q||Z))return _i.Transition.toString({...u,property:Dae})}}function MXe(e,t){var n,r;return typeof e=="boolean"?{draggable:e,droppable:!1}:{draggable:(n=e==null?void 0:e.draggable)!=null?n:t.draggable,droppable:(r=e==null?void 0:e.droppable)!=null?r:t.droppable}}function XN(e){if(!e)return!1;const t=e.data.current;return!!(t&&"sortable"in t&&typeof t.sortable=="object"&&"containerId"in t.sortable&&"items"in t.sortable&&"index"in t.sortable)}const AXe=[In.Down,In.Right,In.Up,In.Left],GL=(e,t)=>{let{context:{active:n,collisionRect:r,droppableRects:s,droppableContainers:o,over:i,scrollableAncestors:a}}=t;if(AXe.includes(e.code)){if(e.preventDefault(),!n||!r)return;const c=[];o.getEnabled().forEach(f=>{if(!f||f!=null&&f.disabled)return;const h=s.get(f.id);if(h)switch(e.code){case In.Down:r.top<h.top&&c.push(f);break;case In.Up:r.top>h.top&&c.push(f);break;case In.Left:r.left>h.left&&c.push(f);break;case In.Right:r.left<h.left&&c.push(f);break}});const u=uZe({collisionRect:r,droppableRects:s,droppableContainers:c});let d=aae(u,"id");if(d===(i==null?void 0:i.id)&&u.length>1&&(d=u[1].id),d!=null){const f=o.get(n.id),h=o.get(d),p=h?s.get(h.id):null,g=h==null?void 0:h.node.current;if(g&&p&&f&&h){const x=Mj(g).some((k,_)=>a[_]!==k),y=Iae(f,h),S=RXe(f,h),w=x||!y?{x:0,y:0}:{x:S?r.width-p.width:0,y:S?r.height-p.height:0},C={x:p.left,y:p.top};return w.x&&w.y?C:k0(C,w)}}}};function Iae(e,t){return!XN(e)||!XN(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function RXe(e,t){return!XN(e)||!XN(t)||!Iae(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function FXe(e,t,n){const[r,s]=v.useState(null),[o,i]=v.useState(""),a=()=>{const g={id:`hierarchy_${Date.now()}`,label:o||"New Hierarchy",type:"static",steps:[],default:!1};t([...e,g]),i(""),s(g.id)},c=g=>{t(e.filter(b=>b.id!==g))},u=(g,b)=>{t(e.map(x=>x.id===g?{...x,...b}:x))};return{editingHierarchy:r,setEditingHierarchy:s,newHierarchyName:o,setNewHierarchyName:i,createNewHierarchy:a,deleteHierarchy:c,updateHierarchy:u,addStepToHierarchy:(g,b)=>{const x=n.find(w=>w.id===b);if(!x)return;const y={field:x,mode:"drillDown",label:`Drill to ${x.label}`,retainFilters:!0,preferredChartType:"bar"},S=e.find(w=>w.id===g);S&&u(g,{steps:[...S.steps,y]})},removeStepFromHierarchy:(g,b)=>{const x=e.find(y=>y.id===g);if(x){const y=[...x.steps];y.splice(b,1),u(g,{steps:y})}},updateStep:(g,b,x)=>{const y=e.find(S=>S.id===g);if(y){const S=y.steps.map((w,C)=>C===b?{...w,...x}:w);u(g,{steps:S})}},setDefaultHierarchy:g=>{t(e.map(b=>({...b,default:b.id===g})))}}}function PXe({step:e,hierarchyId:t,stepIndex:n,onUpdateStep:r,open:s,onOpenChange:o,trigger:i}){return l.jsxs(m.Popover,{open:s,onOpenChange:o,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:i}),l.jsx(m.PopoverContent,{className:"z-50 w-80",align:"start",children:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{children:[l.jsx(m.Label,{className:"mb-1 block text-xs font-medium",children:"Chart Type"}),l.jsxs(m.Select,{value:e.preferredChartType||"bar",onValueChange:a=>{r(t,n,{preferredChartType:a})},children:[l.jsx(m.SelectTrigger,{className:"h-8",children:l.jsx(m.SelectValue,{})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"bar",children:"Bar Chart"}),l.jsx(m.SelectItem,{value:"pie",children:"Pie Chart"}),l.jsx(m.SelectItem,{value:"line",children:"Line Chart"}),l.jsx(m.SelectItem,{value:"donut",children:"Donut Chart"}),l.jsx(m.SelectItem,{value:"table",children:"Table"}),l.jsx(m.SelectItem,{value:"metric",children:"Metric"})]})]})]}),l.jsxs("div",{children:[l.jsx(m.Label,{className:"mb-1 block text-xs font-medium",children:"Step Label"}),l.jsx(m.Input,{value:e.label||"",onChange:a=>r(t,n,{label:a.target.value}),placeholder:"Custom drill label",className:"h-8"})]}),l.jsxs("div",{children:[l.jsx(m.Label,{className:"mb-1 block text-xs font-medium",children:"Breadcrumb Label Template"}),l.jsx(m.Input,{value:e.breadcrumbLabelTemplate||"",onChange:a=>r(t,n,{breadcrumbLabelTemplate:a.target.value}),placeholder:"e.g., 'Region: {{value}}'",className:"h-8"})]}),l.jsx("div",{className:"flex items-center gap-4",children:l.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[l.jsx("input",{type:"checkbox",checked:e.retainFilters!==!1,onChange:a=>r(t,n,{retainFilters:a.target.checked}),className:"rounded"}),"Retain filters when drilling"]})}),l.jsx("div",{className:"flex justify-end",children:l.jsx(m.Button,{size:"sm",variant:"outline",onClick:()=>o(!1),children:"Done"})})]})})]})}function OXe({field:e,step:t,stepIndex:n,hierarchyId:r,onUpdateStep:s,onRemoveStep:o}){const[i,a]=v.useState(!1),{attributes:c,listeners:u,setNodeRef:d,transform:f,transition:h,isDragging:p}=db({id:`${r}-${e.id}-${n}`,disabled:!1}),g={transform:_i.Transform.toString(f),transition:h,opacity:p?.8:1,zIndex:p?1e3:1};return l.jsx("div",{ref:d,style:g,className:`relative ${i?"z-[9998]":""}`,...c,children:l.jsx(PXe,{step:t,hierarchyId:r,stepIndex:n,onUpdateStep:s,open:i,onOpenChange:a,trigger:l.jsxs("div",{className:`flex cursor-pointer items-center gap-2 rounded-lg border bg-muted px-3 py-2 transition-colors hover:bg-muted/50 ${p?"shadow-lg ring-2 ring-primary":""}`,...u,onClick:b=>{b.stopPropagation(),a(x=>!x)},children:[l.jsxs("div",{className:"pointer-events-none flex items-center gap-2",children:[l.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:e.label}),t.preferredChartType&&t.preferredChartType!=="bar"&&l.jsx("span",{className:"whitespace-nowrap rounded bg-purple-100 px-1 py-0.5 text-xs text-purple-700 dark:bg-purple-900/50 dark:text-purple-300",children:t.preferredChartType}),t.linkedInsightId&&l.jsx("span",{className:"whitespace-nowrap rounded bg-green-100 px-1 py-0.5 text-xs text-green-700 dark:bg-green-900/50 dark:text-green-300",children:"📊"})]}),l.jsx("button",{className:"pointer-events-auto ml-1 text-xs text-muted-foreground hover:text-red-800 dark:hover:text-red-400",onClick:b=>{b.stopPropagation(),o(r,n)},children:l.jsx(m.X,{className:"h-3 w-3"})})]})})})}function LXe(e){return{sensors:Tj(cg(cb,{activationConstraint:{distance:5}}),cg(rw,{coordinateGetter:GL})),handleStepDragEnd:(r,s)=>{const{active:o,over:i}=r;if(!i||o.id===i.id)return;const a=o.id.replace(`${s.id}-`,""),c=i.id.replace(`${s.id}-`,""),u=s.steps.findIndex(f=>f.field.id===a),d=s.steps.findIndex(f=>f.field.id===c);if(u!==-1&&d!==-1&&u!==d){const f=ub(s.steps,u,d);e(s.id,{steps:f})}}}}function $Xe({hierarchy:e,onUpdateStep:t,onRemoveStep:n,onUpdateHierarchy:r}){const{sensors:s}=LXe(r),[o,i]=v.useState(null),a=e.steps.filter(h=>h&&h.field&&h.field.id),u=a.map(h=>h.field).map((h,p)=>`${e.id}-${h.id}-${p}`),d=h=>{const p=h.active.id,g=Number.parseInt(p.split("-").pop()||"0"),b=a[g],x=b==null?void 0:b.field;i(x||null)},f=h=>{i(null);const{active:p,over:g}=h;if(!g||p.id===g.id)return;const b=Number.parseInt(p.id.split("-").pop()||"0"),x=Number.parseInt(g.id.split("-").pop()||"0");if(b!==x&&b<a.length&&x<a.length){const y=[...e.steps],[S]=y.splice(b,1);y.splice(x,0,S),r(e.id,{steps:y})}};return a.length===0?l.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:l.jsx("div",{className:"rounded-lg border bg-muted/50 p-2 text-sm text-muted-foreground",children:"No drill steps configured. Add steps to create a drill hierarchy."})}):l.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:l.jsxs(ow,{sensors:s,collisionDetection:nw,onDragStart:d,onDragEnd:f,children:[l.jsx(iw,{items:u,strategy:qL,children:l.jsx("div",{className:"flex flex-wrap items-center gap-2",style:{minHeight:"40px"},children:a.map((h,p)=>{if(!h||!h.field||!h.field.id)return null;const g=[];p>0&&g.push(l.jsx(Mr,{className:"pointer-events-none h-4 w-4 text-gray-400"},`arrow-${p}`));const b=p===0,x=p===a.length-1;return g.push(l.jsx(OXe,{field:h.field,step:h,stepIndex:p,hierarchyId:e.id,onUpdateStep:t,onRemoveStep:n,isFirstField:b,isLastField:x},`field-${h.field.id}-${p}`)),g})})}),typeof window<"u"&&Sr.createPortal(l.jsx(sb,{children:l.jsx(kae,{style:{zIndex:9999},children:o?l.jsx("div",{className:"flex items-center gap-2 rounded-lg border-2 border-blue-300 bg-blue-200 p-2 shadow-lg dark:border-blue-600 dark:bg-blue-900/70",children:l.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:o.label})}):null})}),document.body)]})})}var L7=1,zXe=.9,BXe=.8,VXe=.17,yT=.1,vT=.999,HXe=.9999,UXe=.99,WXe=/[\\\/_+.#"@\[\(\{&]/,qXe=/[\\\/_+.#"@\[\(\{&]/g,YXe=/[\s-]/,Tae=/[\s-]/g;function mR(e,t,n,r,s,o,i){if(o===t.length)return s===e.length?L7:UXe;var a=`${s},${o}`;if(i[a]!==void 0)return i[a];for(var c=r.charAt(o),u=n.indexOf(c,s),d=0,f,h,p,g;u>=0;)f=mR(e,t,n,r,u+1,o+1,i),f>d&&(u===s?f*=L7:WXe.test(e.charAt(u-1))?(f*=BXe,p=e.slice(s,u-1).match(qXe),p&&s>0&&(f*=Math.pow(vT,p.length))):YXe.test(e.charAt(u-1))?(f*=zXe,g=e.slice(s,u-1).match(Tae),g&&s>0&&(f*=Math.pow(vT,g.length))):(f*=VXe,s>0&&(f*=Math.pow(vT,u-s))),e.charAt(u)!==t.charAt(o)&&(f*=HXe)),(f<yT&&n.charAt(u-1)===r.charAt(o+1)||r.charAt(o+1)===r.charAt(o)&&n.charAt(u-1)!==r.charAt(o))&&(h=mR(e,t,n,r,u+1,o+2,i),h*yT>f&&(f=h*yT)),f>d&&(d=f),u=n.indexOf(c,u+1);return i[a]=d,d}function $7(e){return e.toLowerCase().replace(Tae," ")}function GXe(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,mR(e,t,$7(e),$7(t),0,0,{})}var rx='[cmdk-group=""]',wT='[cmdk-group-items=""]',KXe='[cmdk-group-heading=""]',Mae='[cmdk-item=""]',z7=`${Mae}:not([aria-disabled="true"])`,gR="cmdk-item-select",zp="data-value",ZXe=(e,t,n)=>GXe(e,t,n),Aae=Q.createContext(void 0),aw=()=>Q.useContext(Aae),Rae=Q.createContext(void 0),KL=()=>Q.useContext(Rae),Fae=Q.createContext(void 0),Pae=Q.forwardRef((e,t)=>{let n=Bp(()=>{var q,M;return{search:"",value:(M=(q=e.value)!=null?q:e.defaultValue)!=null?M:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Bp(()=>new Set),s=Bp(()=>new Map),o=Bp(()=>new Map),i=Bp(()=>new Set),a=Oae(e),{label:c,children:u,value:d,onValueChange:f,filter:h,shouldFilter:p,loop:g,disablePointerSelection:b=!1,vimBindings:x=!0,...y}=e,S=m.useId(),w=m.useId(),C=m.useId(),N=Q.useRef(null),k=aQe();Mh(()=>{if(d!==void 0){let q=d.trim();n.current.value=q,_.emit()}},[d]),Mh(()=>{k(6,F)},[]);let _=Q.useMemo(()=>({subscribe:q=>(i.current.add(q),()=>i.current.delete(q)),snapshot:()=>n.current,setState:(q,M,G)=>{var L,$,V,H;if(!Object.is(n.current[q],M)){if(n.current[q]=M,q==="search")T(),j(),k(1,I);else if(q==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let A=document.getElementById(C);A?A.focus():(L=document.getElementById(S))==null||L.focus()}if(k(7,()=>{var A;n.current.selectedItemId=(A=P())==null?void 0:A.id,_.emit()}),G||k(5,F),(($=a.current)==null?void 0:$.value)!==void 0){let A=M??"";(H=(V=a.current).onValueChange)==null||H.call(V,A);return}}_.emit()}},emit:()=>{i.current.forEach(q=>q())}}),[]),E=Q.useMemo(()=>({value:(q,M,G)=>{var L;M!==((L=o.current.get(q))==null?void 0:L.value)&&(o.current.set(q,{value:M,keywords:G}),n.current.filtered.items.set(q,D(M,G)),k(2,()=>{j(),_.emit()}))},item:(q,M)=>(r.current.add(q),M&&(s.current.has(M)?s.current.get(M).add(q):s.current.set(M,new Set([q]))),k(3,()=>{T(),j(),n.current.value||I(),_.emit()}),()=>{o.current.delete(q),r.current.delete(q),n.current.filtered.items.delete(q);let G=P();k(4,()=>{T(),(G==null?void 0:G.getAttribute("id"))===q&&I(),_.emit()})}),group:q=>(s.current.has(q)||s.current.set(q,new Set),()=>{o.current.delete(q),s.current.delete(q)}),filter:()=>a.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:S,inputId:C,labelId:w,listInnerRef:N}),[]);function D(q,M){var G,L;let $=(L=(G=a.current)==null?void 0:G.filter)!=null?L:ZXe;return q?$(q,n.current.search,M):0}function j(){if(!n.current.search||a.current.shouldFilter===!1)return;let q=n.current.filtered.items,M=[];n.current.filtered.groups.forEach(L=>{let $=s.current.get(L),V=0;$.forEach(H=>{let A=q.get(H);V=Math.max(A,V)}),M.push([L,V])});let G=N.current;R().sort((L,$)=>{var V,H;let A=L.getAttribute("id"),W=$.getAttribute("id");return((V=q.get(W))!=null?V:0)-((H=q.get(A))!=null?H:0)}).forEach(L=>{let $=L.closest(wT);$?$.appendChild(L.parentElement===$?L:L.closest(`${wT} > *`)):G.appendChild(L.parentElement===G?L:L.closest(`${wT} > *`))}),M.sort((L,$)=>$[1]-L[1]).forEach(L=>{var $;let V=($=N.current)==null?void 0:$.querySelector(`${rx}[${zp}="${encodeURIComponent(L[0])}"]`);V==null||V.parentElement.appendChild(V)})}function I(){let q=R().find(G=>G.getAttribute("aria-disabled")!=="true"),M=q==null?void 0:q.getAttribute(zp);_.setState("value",M||void 0)}function T(){var q,M,G,L;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let $=0;for(let V of r.current){let H=(M=(q=o.current.get(V))==null?void 0:q.value)!=null?M:"",A=(L=(G=o.current.get(V))==null?void 0:G.keywords)!=null?L:[],W=D(H,A);n.current.filtered.items.set(V,W),W>0&&$++}for(let[V,H]of s.current)for(let A of H)if(n.current.filtered.items.get(A)>0){n.current.filtered.groups.add(V);break}n.current.filtered.count=$}function F(){var q,M,G;let L=P();L&&(((q=L.parentElement)==null?void 0:q.firstChild)===L&&((G=(M=L.closest(rx))==null?void 0:M.querySelector(KXe))==null||G.scrollIntoView({block:"nearest"})),L.scrollIntoView({block:"nearest"}))}function P(){var q;return(q=N.current)==null?void 0:q.querySelector(`${Mae}[aria-selected="true"]`)}function R(){var q;return Array.from(((q=N.current)==null?void 0:q.querySelectorAll(z7))||[])}function B(q){let M=R()[q];M&&_.setState("value",M.getAttribute(zp))}function z(q){var M;let G=P(),L=R(),$=L.findIndex(H=>H===G),V=L[$+q];(M=a.current)!=null&&M.loop&&(V=$+q<0?L[L.length-1]:$+q===L.length?L[0]:L[$+q]),V&&_.setState("value",V.getAttribute(zp))}function U(q){let M=P(),G=M==null?void 0:M.closest(rx),L;for(;G&&!L;)G=q>0?oQe(G,rx):iQe(G,rx),L=G==null?void 0:G.querySelector(z7);L?_.setState("value",L.getAttribute(zp)):z(q)}let Y=()=>B(R().length-1),O=q=>{q.preventDefault(),q.metaKey?Y():q.altKey?U(1):z(1)},K=q=>{q.preventDefault(),q.metaKey?B(0):q.altKey?U(-1):z(-1)};return Q.createElement(m.Primitive.div,{ref:t,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:q=>{var M;(M=y.onKeyDown)==null||M.call(y,q);let G=q.nativeEvent.isComposing||q.keyCode===229;if(!(q.defaultPrevented||G))switch(q.key){case"n":case"j":{x&&q.ctrlKey&&O(q);break}case"ArrowDown":{O(q);break}case"p":case"k":{x&&q.ctrlKey&&K(q);break}case"ArrowUp":{K(q);break}case"Home":{q.preventDefault(),B(0);break}case"End":{q.preventDefault(),Y();break}case"Enter":{q.preventDefault();let L=P();if(L){let $=new Event(gR);L.dispatchEvent($)}}}}},Q.createElement("label",{"cmdk-label":"",htmlFor:E.inputId,id:E.labelId,style:cQe},c),Fj(e,q=>Q.createElement(Rae.Provider,{value:_},Q.createElement(Aae.Provider,{value:E},q))))}),XXe=Q.forwardRef((e,t)=>{var n,r;let s=m.useId(),o=Q.useRef(null),i=Q.useContext(Fae),a=aw(),c=Oae(e),u=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;Mh(()=>{if(!u)return a.item(s,i==null?void 0:i.id)},[u]);let d=Lae(s,o,[e.value,e.children,o],e.keywords),f=KL(),h=gd(k=>k.value&&k.value===d.current),p=gd(k=>u||a.filter()===!1?!0:k.search?k.filtered.items.get(s)>0:!0);Q.useEffect(()=>{let k=o.current;if(!(!k||e.disabled))return k.addEventListener(gR,g),()=>k.removeEventListener(gR,g)},[p,e.onSelect,e.disabled]);function g(){var k,_;b(),(_=(k=c.current).onSelect)==null||_.call(k,d.current)}function b(){f.setState("value",d.current,!0)}if(!p)return null;let{disabled:x,value:y,onSelect:S,forceMount:w,keywords:C,...N}=e;return Q.createElement(m.Primitive.div,{ref:m.composeRefs(o,t),...N,id:s,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!h,"data-disabled":!!x,"data-selected":!!h,onPointerMove:x||a.getDisablePointerSelection()?void 0:b,onClick:x?void 0:g},e.children)}),QXe=Q.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:s,...o}=e,i=m.useId(),a=Q.useRef(null),c=Q.useRef(null),u=m.useId(),d=aw(),f=gd(p=>s||d.filter()===!1?!0:p.search?p.filtered.groups.has(i):!0);Mh(()=>d.group(i),[]),Lae(i,a,[e.value,e.heading,c]);let h=Q.useMemo(()=>({id:i,forceMount:s}),[s]);return Q.createElement(m.Primitive.div,{ref:m.composeRefs(a,t),...o,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&Q.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:u},n),Fj(e,p=>Q.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?u:void 0},Q.createElement(Fae.Provider,{value:h},p))))}),JXe=Q.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,s=Q.useRef(null),o=gd(i=>!i.search);return!n&&!o?null:Q.createElement(m.Primitive.div,{ref:m.composeRefs(s,t),...r,"cmdk-separator":"",role:"separator"})}),eQe=Q.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,s=e.value!=null,o=KL(),i=gd(u=>u.search),a=gd(u=>u.selectedItemId),c=aw();return Q.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),Q.createElement(m.Primitive.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":a,id:c.inputId,type:"text",value:s?e.value:i,onChange:u=>{s||o.setState("search",u.target.value),n==null||n(u.target.value)}})}),tQe=Q.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...s}=e,o=Q.useRef(null),i=Q.useRef(null),a=gd(u=>u.selectedItemId),c=aw();return Q.useEffect(()=>{if(i.current&&o.current){let u=i.current,d=o.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let p=u.offsetHeight;d.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return h.observe(u),()=>{cancelAnimationFrame(f),h.unobserve(u)}}},[]),Q.createElement(m.Primitive.div,{ref:m.composeRefs(o,t),...s,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:c.listId},Fj(e,u=>Q.createElement("div",{ref:m.composeRefs(i,c.listInnerRef),"cmdk-list-sizer":""},u)))}),nQe=Q.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:s,contentClassName:o,container:i,...a}=e;return Q.createElement(Pk,{open:n,onOpenChange:r},Q.createElement(Ok,{container:i},Q.createElement(yg,{"cmdk-overlay":"",className:s}),Q.createElement(vg,{"aria-label":e.label,"cmdk-dialog":"",className:o},Q.createElement(Pae,{ref:t,...a}))))}),rQe=Q.forwardRef((e,t)=>gd(n=>n.filtered.count===0)?Q.createElement(m.Primitive.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),sQe=Q.forwardRef((e,t)=>{let{progress:n,children:r,label:s="Loading...",...o}=e;return Q.createElement(m.Primitive.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":s},Fj(e,i=>Q.createElement("div",{"aria-hidden":!0},i)))}),bo=Object.assign(Pae,{List:tQe,Item:XXe,Input:eQe,Group:QXe,Separator:JXe,Dialog:nQe,Empty:rQe,Loading:sQe});function oQe(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function iQe(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Oae(e){let t=Q.useRef(e);return Mh(()=>{t.current=e}),t}var Mh=typeof window>"u"?Q.useEffect:Q.useLayoutEffect;function Bp(e){let t=Q.useRef();return t.current===void 0&&(t.current=e()),t}function gd(e){let t=KL(),n=()=>e(t.snapshot());return Q.useSyncExternalStore(t.subscribe,n,n)}function Lae(e,t,n,r=[]){let s=Q.useRef(),o=aw();return Mh(()=>{var i;let a=(()=>{var u;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(u=d.current.textContent)==null?void 0:u.trim():s.current}})(),c=r.map(u=>u.trim());o.value(e,a,c),(i=t.current)==null||i.setAttribute(zp,a),s.current=a}),s}var aQe=()=>{let[e,t]=Q.useState(),n=Bp(()=>new Map);return Mh(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,s)=>{n.current.set(r,s),t({})}};function lQe(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Fj({asChild:e,children:t},n){return e&&Q.isValidElement(t)?Q.cloneElement(lQe(t),{ref:t.ref},n(t.props.children)):n(t)}var cQe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Pj=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo,{ref:n,className:m.cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));Pj.displayName=bo.displayName;const ZL=Q.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[l.jsx(Ws,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(bo.Input,{ref:n,className:m.cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));ZL.displayName=bo.Input.displayName;const Oj=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo.List,{ref:n,className:m.cn("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));Oj.displayName=bo.List.displayName;const Lj=Q.forwardRef((e,t)=>l.jsx(bo.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));Lj.displayName=bo.Empty.displayName;const $j=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo.Group,{ref:n,className:m.cn("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));$j.displayName=bo.Group.displayName;const $ae=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo.Separator,{ref:n,className:m.cn("-mx-1 h-px bg-border",e),...t}));$ae.displayName=bo.Separator.displayName;const zj=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo.Item,{ref:n,className:m.cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",e),...t}));zj.displayName=bo.Item.displayName;function uQe({hierarchy:e,sampleFieldReferences:t,onUpdateHierarchy:n,onDeleteHierarchy:r,onUpdateStep:s,onRemoveStep:o,onAddStep:i}){const[a,c]=v.useState(!1),{attributes:u,listeners:d,setNodeRef:f,transform:h,transition:p}=db({id:e.id,disabled:!1}),g={transform:_i.Transform.toString(h),transition:p},b=e.steps.filter(x=>x.field).map(x=>x.field.id);return l.jsxs("div",{ref:f,style:g,className:"hierarchy-container relative rounded-lg border bg-background p-3 transition-shadow hover:shadow-md",children:[l.jsxs("div",{className:"mb-3 flex cursor-move items-center justify-between",...u,...d,children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("div",{onPointerDown:x=>x.stopPropagation(),onClick:x=>x.stopPropagation(),onKeyDown:x=>x.stopPropagation(),children:l.jsx(Zi,{value:e.label||"",onSave:x=>{n(e.id,{label:x})},placeholder:"Hierarchy Name",displayClassName:"font-medium",inputClassName:"font-medium"})})}),l.jsx("div",{className:"flex items-center gap-1",children:l.jsx(m.Button,{size:"sm",variant:"ghost",onClick:x=>{x.stopPropagation(),r(e.id)},onPointerDown:x=>x.stopPropagation(),children:l.jsx(yl,{className:"h-3 w-3"})})})]}),l.jsx($Xe,{hierarchy:e,onUpdateStep:s,onRemoveStep:o,onUpdateHierarchy:n}),l.jsx("div",{className:"mt-3 border-t pt-3","data-hierarchy-editing":!0,children:a?l.jsxs(Pj,{className:"rounded-lg border",children:[l.jsx(ZL,{placeholder:"Search fields..."}),l.jsxs(Oj,{children:[l.jsx(Lj,{children:"No field found."}),l.jsx($j,{children:t.filter(x=>!b.includes(x.id)).map(x=>l.jsx(zj,{value:x.label,onSelect:()=>{i(e.id,x.id),c(!1)},children:x.label},x.id))})]})]}):l.jsxs(m.Button,{type:"button",variant:"outline",size:"sm",onClick:x=>{x.preventDefault(),x.stopPropagation(),c(!0)},children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Add Step"]})})]})}function dQe({open:e,onOpenChange:t,drillHierarchies:n,onUpdateHierarchies:r,availableFields:s}){const[o,i]=v.useState(n);v.useEffect(()=>{e&&i(n)},[e,n]);const a=v.useMemo(()=>s.filter(S=>m.getDataType(S.dataType)==="string"),[s]),c=Tj(cg(cb),cg(rw,{coordinateGetter:GL})),{createNewHierarchy:u,deleteHierarchy:d,updateHierarchy:f,addStepToHierarchy:h,removeStepFromHierarchy:p,updateStep:g,setDefaultHierarchy:b}=FXe(o,i,a),x=S=>{const{active:w,over:C}=S;if(w.id!==(C==null?void 0:C.id)){const N=o.findIndex(_=>_.id===w.id),k=o.findIndex(_=>_.id===(C==null?void 0:C.id));i(ub(o,N,k))}},y=S=>{S||r(o),t(S)};return l.jsx(Oo,{modal:!0,open:e,onOpenChange:y,children:l.jsx(mo,{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden p-0",onInteractOutside:S=>S.preventDefault(),onEscapeKeyDown:S=>S.preventDefault(),children:l.jsx(m.FocusScope,{trapped:!1,children:l.jsxs("div",{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden",children:[l.jsxs(na,{className:"border-b px-6 pb-4 pt-6",children:[l.jsx(go,{children:"Manage Drill Hierarchies"}),l.jsx(si,{children:"Create multiple drill paths for different analysis scenarios. Define step-by-step navigation through your dimensions."})]}),l.jsx(m.ScrollArea,{className:"flex-1 px-6",children:l.jsxs("div",{className:"space-y-4 py-4",children:[o.length>0&&l.jsx("div",{className:"flex justify-end",children:l.jsxs(m.Button,{type:"button",size:"sm",onClick:S=>{S.preventDefault(),S.stopPropagation(),u()},children:[l.jsx(dr,{className:"mr-1 h-4 w-4"}),"Add Hierarchy"]})}),o.length>0?l.jsx(ow,{sensors:c,collisionDetection:nw,onDragEnd:x,children:l.jsx(iw,{items:o.map(S=>S.id),strategy:YL,children:l.jsx("div",{className:"space-y-4",children:o.map(S=>l.jsx(uQe,{hierarchy:S,sampleFieldReferences:a,onUpdateHierarchy:f,onDeleteHierarchy:d,onSetDefaultHierarchy:b,onUpdateStep:g,onRemoveStep:p,onAddStep:h},S.id))})})}):l.jsxs("div",{className:"rounded-lg border border-dashed p-8 text-center",children:[l.jsx("p",{className:"mb-2 text-sm text-muted-foreground",children:"No hierarchies configured yet"}),l.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:"Create your first hierarchy to enable drill-down interactions"}),l.jsxs(m.Button,{type:"button",size:"sm",variant:"outline",onClick:S=>{S.preventDefault(),S.stopPropagation(),u()},children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Create First Hierarchy"]})]})]})}),l.jsx("div",{className:"flex justify-end gap-2 border-t px-6 py-4",children:l.jsx(m.Button,{variant:"outline",onClick:()=>y(!1),children:"Done"})})]})})})})}function j0(e){switch(e){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];case"hour":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:00 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:00 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"minute":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:00 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"second":return[{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}}function fQe({interaction:e,onUpdate:t,card:n,availableFields:r,onUpdateHierarchies:s,onManageHierarchies:o}){var I;const[i,a]=v.useState(!1),[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,p]=v.useState(!1),[g,b]=v.useState({}),x=v.useMemo(()=>{var T;return((T=n.interactionConfig)==null?void 0:T.drillHierarchies)||[]},[(I=n.interactionConfig)==null?void 0:I.drillHierarchies]),y=v.useMemo(()=>{var R,B;const T=[],F=e.trigger;if(!F)return T;let P;if(F.type==="attribute"){const z=r.find(Y=>Y.id===F.field.id);z&&(z.dataType==="date"||z.dataType==="timestamp")&&(P=z)}else if(F.type==="metric"){const z=(B=(R=n.config)==null?void 0:R.groupByColumns)==null?void 0:B.find(U=>U.dataType==="date"||U.dataType==="timestamp");z&&(P=z)}if(P&&m.shouldAutoGenerateDateHierarchy(P,x)){const z=m.generateDateHierarchy(P);T.push(z)}return T},[r,x,e.trigger,n.config]),S=v.useMemo(()=>[...x,...y],[x,y]),w=S.find(T=>T.id===e.hierarchyId);Q.useEffect(()=>{i&&w&&w.type==="date"?f(w.id):i||f(null)},[i,w]);const C=T=>{if(y.some(P=>P.id===T)&&s){const P=y.find(R=>R.id===T);P&&s([...x,P])}t({...e,hierarchyId:T}),a(!1)},N=()=>{a(!1),u(!0),o&&o()},k=T=>{s&&s(T)},_=T=>T.steps.map(P=>P.field.label||P.field.name).join(" → "),E=T=>T&&T.charAt(0).toUpperCase()+T.slice(1),D=(T,F,P)=>{const R=[...T.steps];R[F]={...R[F],field:{...R[F].field,dateFormat:P,customFormat:P==="custom"?g[F]||"":void 0}};const B={...T,steps:R};if(s){const z=x.findIndex(U=>U.id===T.id);if(z>=0){const U=[...x];U[z]=B,s(U)}else s([...x,B])}},j=(T,F,P)=>{b(z=>({...z,[F]:P}));const R=[...T.steps];R[F]={...R[F],field:{...R[F].field,dateFormat:"custom",customFormat:P}};const B={...T,steps:R};if(s){const z=x.findIndex(U=>U.id===T.id);if(z>=0){const U=[...x];U[z]=B,s(U)}else s([...x,B])}};return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Choose hierarchy"}),l.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Select which hierarchy to drill through when this interaction triggers"}),S.length>0?l.jsxs(l.Fragment,{children:[l.jsxs(m.Popover,{open:i,onOpenChange:a,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsxs(m.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[l.jsx("div",{className:"flex flex-1 flex-col items-start text-left",children:w?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{className:"font-medium",children:w.label||"Unnamed Hierarchy"})}),l.jsx("span",{className:"text-xs text-muted-foreground",children:_(w)})]}):l.jsx("span",{className:"text-muted-foreground",children:"Select hierarchy..."})}),l.jsxs("div",{className:"flex items-center gap-2",children:[w&&w.type==="date"&&l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:T=>{T.stopPropagation(),p(!h)},children:l.jsx(xF,{className:"h-3 w-3"})}),l.jsx(Mr,{className:"h-4 w-4 shrink-0 opacity-50"})]})]})}),l.jsxs(m.PopoverContent,{className:"w-[500px] p-0",align:"start",children:[l.jsxs("div",{className:"flex items-center justify-between border-b p-3",children:[l.jsx("span",{className:"text-sm font-medium",children:"Select Hierarchy"}),l.jsxs(m.Button,{variant:"ghost",size:"sm",onClick:N,children:[l.jsx(dr,{className:"mr-1.5 h-3.5 w-3.5"}),"Create new"]})]}),l.jsxs("div",{className:"p-2",children:[y.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-3 py-2",children:l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"AUTO-GENERATED"})}),y.map(T=>l.jsx("div",{className:`cursor-pointer rounded-md p-3 hover:bg-muted ${e.hierarchyId===T.id?"bg-muted":""}`,onClick:()=>C(T.id),children:l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{className:"text-sm font-medium",children:T.label||"Unnamed Hierarchy"})}),l.jsx("div",{className:"text-xs text-muted-foreground",children:_(T)})]})},T.id))]}),x.length>0&&l.jsxs(l.Fragment,{children:[y.length>0&&l.jsx("div",{className:"my-2 border-t"}),x.map(T=>l.jsx("div",{className:`cursor-pointer rounded-md p-3 hover:bg-muted ${e.hierarchyId===T.id?"bg-muted":""}`,onClick:()=>C(T.id),children:l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{className:"text-sm font-medium",children:T.label||"Unnamed Hierarchy"})}),l.jsx("div",{className:"text-xs text-muted-foreground",children:_(T)})]})},T.id))]})]})]})]}),w&&w.type==="date"&&h&&l.jsxs("div",{className:"mt-3 space-y-3 rounded-md border border-border p-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Customize Date Formats"}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 text-xs",onClick:()=>p(!1),children:"Close"})]}),w.steps.map((T,F)=>{var z;const P=T.field.granularity;if(!P)return null;const R=j0(P),B=T.field.dateFormat||((z=R[0])==null?void 0:z.value);return l.jsxs("div",{className:"space-y-1",children:[l.jsx(m.Label,{className:"text-xs font-medium text-muted-foreground",children:T.field.label||E(P)}),l.jsxs(m.Select,{value:B,onValueChange:U=>{D(w,F,U)},children:[l.jsx(m.SelectTrigger,{className:"h-8 text-xs",children:l.jsx(m.SelectValue,{})}),l.jsx(m.SelectContent,{children:R.map(U=>l.jsx(m.SelectItem,{value:U.value,className:"text-xs",children:U.label},U.value))})]}),B==="custom"&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx(m.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD)",value:T.field.customFormat||g[F]||"",onChange:U=>{j(w,F,U.target.value)},className:"h-8 text-xs"}),l.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Common tokens: YYYY (year), MM (month), DD (day), HH (hour), mm (minute)"})]})]},F)})]})]}):l.jsxs("div",{className:"rounded-md border border-dashed p-6 text-center",children:[l.jsx("p",{className:"mb-2 text-sm text-muted-foreground",children:"No hierarchies configured"}),l.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:"Create a hierarchy to define your drill path"}),l.jsxs(m.Button,{variant:"outline",size:"sm",onClick:N,children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Create hierarchy"]})]})]}),l.jsx(dQe,{open:c,onOpenChange:u,drillHierarchies:x,onUpdateHierarchies:k,availableFields:r})]})}function hQe({fields:e,selectedFieldIds:t,onSelectionChange:n,searchPlaceholder:r="Search fields...",className:s=""}){const[o,i]=v.useState(""),a=e.filter(d=>d.label.toLowerCase().includes(o.toLowerCase())||d.qualifiedEntityName&&d.qualifiedEntityName.toLowerCase().includes(o.toLowerCase())),c=()=>{const d=[...new Set([...t,...a.map(f=>f.id)])];n(d)},u=()=>{const d=a.map(f=>f.id);n(t.filter(f=>!d.includes(f)))};return l.jsxs("div",{className:`space-y-2 ${s}`,children:[l.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[l.jsx(m.Input,{placeholder:r,value:o,onChange:d=>i(d.target.value),className:"flex-1"}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[a.length," fields"]})]}),l.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[l.jsx(m.Button,{size:"sm",variant:"outline",onClick:c,children:"Select All"}),l.jsx(m.Button,{size:"sm",variant:"outline",onClick:u,children:"Deselect All"}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," selected"]})]}),l.jsx("div",{className:"grid max-h-32 grid-cols-2 gap-2 overflow-y-auto rounded border p-2",children:a.map(d=>l.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded p-2 text-xs hover:bg-muted/50",children:[l.jsx(Ln,{checked:t.includes(d.id),onCheckedChange:f=>{n(f?[...t,d.id]:t.filter(h=>h!==d.id))}}),l.jsx("span",{className:"font-medium",children:d.label})]},d.id))}),o&&a.length===0&&l.jsxs("div",{className:"py-4 text-center text-sm text-muted-foreground",children:['No fields found matching "',o,'"']})]})}const pQe=e=>["string","boolean"].includes(m.getDataType(e.dataType));function mQe({interaction:e,availableFields:t,onUpdate:n}){var i;const r=t.filter(pQe),s=((i=e.availableFields)==null?void 0:i.map(a=>a.id))||[],o=a=>{const c=r.filter(u=>a.includes(u.id));n({...e,availableFields:c})};return l.jsx("div",{className:"space-y-4",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{children:"Available dimensions"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose which fields users can explore dynamically"}),l.jsx(hQe,{fields:r,selectedFieldIds:s,onSelectionChange:o,searchPlaceholder:"Search fields..."}),s.length===0&&l.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ Please select at least one field"})]})})}function gQe({value:e,onChange:t}){const[n,r]=v.useState(!1),[s,o]=v.useState(""),[i,a]=v.useState("all"),{currentUser:c}=ta(),{data:u,isLoading:d}=MF(Xr.DASHBOARD,s),f=(u==null?void 0:u.dashboards)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(c==null?void 0:c.id):!0),p=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),o("")};return l.jsxs(m.Popover,{open:n,onOpenChange:r,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsx(m.Button,{variant:"outline",className:m.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:p?l.jsx("span",{className:"truncate",children:p.title}):"Choose dashboard..."})}),l.jsx(m.PopoverContent,{className:"w-[500px] p-0",align:"start",children:l.jsxs(m.Tabs,{value:i,onValueChange:b=>a(b),children:[l.jsx("div",{className:"p-3 border-b",children:l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),l.jsx(m.Input,{placeholder:"Search all dashboards...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]})}),l.jsxs(m.TabsList,{className:"w-full justify-start rounded-none border-b bg-transparent p-0",children:[l.jsx(m.TabsTrigger,{value:"me",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"created by me"}),l.jsx(m.TabsTrigger,{value:"all",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"all"})]}),l.jsx(m.TabsContent,{value:i,className:"mt-0",children:l.jsx(m.ScrollArea,{className:"h-[300px]",children:d?l.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading dashboards..."}):h.length===0?l.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:s?`No dashboards found matching "${s}"`:i==="me"?"No dashboards created by you":"No dashboards available"}):l.jsx("div",{className:"p-2",children:h.map(b=>l.jsxs("button",{onClick:()=>g(b),className:m.cn("w-full flex items-start gap-3 p-3 rounded-md hover:bg-muted/50 transition-colors text-left",e===b.id&&"bg-muted"),children:[l.jsx(Rm,{className:"h-5 w-5 mt-0.5 text-muted-foreground flex-shrink-0"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"font-medium text-sm truncate",children:b.title}),l.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:bQe(b.createdAt)})]})]},b.id))})})})]})})]})}function bQe(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear()){const i=t.getHours(),a=t.getMinutes(),c=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${c}`}const s=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),o=t.getDate();return`${s} ${o}`}function xQe({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Target dashboard"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select which dashboard to navigate to when this interaction triggers"}),l.jsx(gQe,{value:e.targetDashboardId,onChange:(n,r)=>{const s={...e,targetDashboardId:n};!e.label&&r&&(s.label=r),t(s)}})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Propagate Filters"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose what filters to pass to the target dashboard"}),l.jsxs(m.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsxs(m.SelectValue,{placeholder:"Choose context mode...",children:[e.contextMode==="interactionFilters"&&"Interaction Filters",(e.contextMode==="full"||!e.contextMode)&&"All Filters",e.contextMode==="none"&&"None"]})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"interactionFilters",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"Interaction Filters"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass only the clicked element as a filter"})]})}),l.jsx(m.SelectItem,{value:"full",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"All Filters"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass current dashboard filters + clicked element"})]})}),l.jsx(m.SelectItem,{value:"none",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"None"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Navigate without passing any filters"})]})})]})]})]}),!e.targetDashboardId&&l.jsx("div",{className:"rounded-md bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3",children:l.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"⚠ Please select a target dashboard to complete this configuration"})}),e.targetDashboardId&&l.jsx("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:l.jsx("p",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Dashboard drill-through configured successfully"})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(m.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:tp(e.mode)}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function yQe({value:e,onChange:t}){const[n,r]=v.useState(!1),[s,o]=v.useState(""),[i,a]=v.useState("all"),{currentUser:c}=ta(),{data:u,isLoading:d}=MF(Xr.VISUAL,s),f=(u==null?void 0:u.visuals)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(c==null?void 0:c.id):!0),p=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),o("")};return l.jsxs(m.Popover,{open:n,onOpenChange:r,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsx(m.Button,{variant:"outline",className:m.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:p?l.jsx("span",{className:"truncate",children:p.title}):"Choose insight..."})}),l.jsx(m.PopoverContent,{className:"w-[500px] p-0",align:"start",children:l.jsxs(m.Tabs,{value:i,onValueChange:b=>a(b),children:[l.jsx("div",{className:"p-3 border-b",children:l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),l.jsx(m.Input,{placeholder:"Search all insights...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]})}),l.jsxs(m.TabsList,{className:"w-full justify-start rounded-none border-b bg-transparent p-0",children:[l.jsx(m.TabsTrigger,{value:"me",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"created by me"}),l.jsx(m.TabsTrigger,{value:"all",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"all"})]}),l.jsx(m.TabsContent,{value:i,className:"mt-0",children:l.jsx(m.ScrollArea,{className:"h-[300px]",children:d?l.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading insights..."}):h.length===0?l.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:s?`No insights found matching "${s}"`:i==="me"?"No insights created by you":"No insights available"}):l.jsx("div",{className:"p-2",children:h.map(b=>l.jsxs("button",{onClick:()=>g(b),className:m.cn("w-full flex items-start gap-3 p-3 rounded-md hover:bg-muted/50 transition-colors text-left",e===b.id&&"bg-muted"),children:[l.jsx(m.ChartColumn,{className:"h-5 w-5 mt-0.5 text-muted-foreground flex-shrink-0"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"font-medium text-sm truncate",children:b.title}),l.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:vQe(b.createdAt)})]})]},b.id))})})})]})})]})}function vQe(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear()){const i=t.getHours(),a=t.getMinutes(),c=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${c}`}const s=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),o=t.getDate();return`${s} ${o}`}function wQe({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Target insight"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select the saved insight to navigate to"}),l.jsx(yQe,{value:e.targetInsightId,onChange:(n,r)=>{const s={...e,targetInsightId:n};!e.label&&r&&(s.label=r),t(s)}})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Propagate Filters"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose what filters to pass to the insight"}),l.jsxs(m.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsxs(m.SelectValue,{placeholder:"Choose context mode...",children:[e.contextMode==="interactionFilters"&&"Interaction Filters",(e.contextMode==="full"||!e.contextMode)&&"All Filters",e.contextMode==="none"&&"None"]})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"interactionFilters",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"Interaction Filters"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass only the clicked element as a filter"})]})}),l.jsx(m.SelectItem,{value:"full",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"All Filters"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass all current filters and selections"})]})}),l.jsx(m.SelectItem,{value:"none",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"None"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Open insight without any filters"})]})})]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Display mode"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose how the insight should be displayed"}),l.jsxs(m.Select,{value:e.displayMode||"modal",onValueChange:n=>t({...e,displayMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsx(m.SelectValue,{placeholder:"Choose display mode..."})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"modal",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"Open in modal"})})}),l.jsx(m.SelectItem,{value:"replace-card",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"Replace the card"})})})]})]})]}),!e.targetInsightId&&l.jsx("div",{className:"rounded-md bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3",children:l.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"⚠ Please enter a target insight ID to complete this configuration"})}),e.targetInsightId&&l.jsx("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:l.jsx("p",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Insight drill-through configured successfully"})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(m.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:tp(e.mode)}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function SQe(e){return e.filter(t=>t.role==="groupby"||t.role==="pivotby").map(t=>({id:t.name,label:t.label||t.name,category:"attribute",field:t}))}function CQe(){return[{id:"card_id",label:"Card ID",category:"identifier"},{id:"frame_id",label:"Frame ID",category:"identifier"},{id:"sheet_id",label:"Sheet ID",category:"identifier"}]}function NQe(e,t){const n=`{{${t}}}`;return e.includes(n)}function kQe(e,t){return t.filter(n=>NQe(e,n.id))}function _Qe(e,t,n){const r=`{{${t}}}`,s=e.slice(0,n)+r+e.slice(n),o=n+r.length;return{newTemplate:s,newCursorPosition:o}}function jQe(e,t){let n=e;return t.forEach(r=>{const s=`{{${r.id}}}`;let o;if(r.category==="identifier")o=`${r.id.toUpperCase()}-abc123`;else{const i=r.label.toLowerCase();i.includes("name")?o="Example Name":i.includes("region")||i.includes("location")?o="California":i.includes("id")?o="ID-12345":i.includes("category")?o="Category A":o="Sample Value"}n=n.replace(new RegExp(s,"g"),o)}),n}function EQe({open:e,onOpenChange:t,interaction:n,availableFields:r,onSave:s}){const[o,i]=v.useState(n.urlTemplate||""),[a,c]=v.useState(0),[u,d]=v.useState(n.encodeParameters!==!1),[f,h]=v.useState(n.label||""),p=v.useRef(null);v.useEffect(()=>{e&&(i(n.urlTemplate||""),d(n.encodeParameters!==!1),h(n.label||""),c(0))},[e,n.urlTemplate,n.encodeParameters,n.label]);const g=SQe(r),b=CQe(),x=[...g,...b],y=kQe(o,x),S=m.validateURLTemplate(o),w=o&&S.valid?jQe(o,y):"",C=j=>{i(j.target.value),c(j.target.selectionStart)},N=j=>{const I=j.target;c(I.selectionStart)},k=j=>{const I=j.target;c(I.selectionStart)},_=j=>{const{newTemplate:I,newCursorPosition:T}=_Qe(o,j.id,a);i(I),c(T),p.current&&(p.current.focus(),setTimeout(()=>{p.current&&p.current.setSelectionRange(T,T)},0))},E=()=>{S.valid&&(s({...n,urlTemplate:o,parameters:y,encodeParameters:u,label:f}),t(!1))},D=()=>{t(!1)};return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{className:"max-h-[90vh] max-w-5xl overflow-y-auto",onOpenAutoFocus:j=>{j.preventDefault(),setTimeout(()=>{var I;(I=p.current)==null||I.focus()},0)},children:[l.jsxs(na,{children:[l.jsx(go,{children:"Configure Drill to URL"}),l.jsx(si,{children:"Build a custom URL with dynamic parameters that will open when users click on chart elements."})]}),l.jsxs("div",{className:"flex flex-col gap-6 py-4",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[l.jsxs("div",{className:"flex flex-col gap-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(m.Label,{htmlFor:"url-template",children:"URL"}),l.jsx(m.TooltipProvider,{children:l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Info,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(m.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-xs",children:"Enter your URL and click parameters from the right panel to insert them. Parameters will be replaced with actual values when the URL is opened."})})]})})]}),l.jsx(Bh,{ref:p,id:"url-template",value:o,onChange:C,onClick:N,onKeyUp:k,placeholder:"https://example.com/product/{{product_id}}?region={{region}}",className:"min-h-[200px] font-mono text-sm"}),!S.valid&&o&&l.jsx("div",{className:"rounded-lg border border-destructive bg-destructive/10 p-3",children:l.jsx("div",{className:"text-sm text-destructive",children:S.errors.map((j,I)=>l.jsx("div",{children:j},I))})}),w&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-xs text-muted-foreground",children:"Preview:"}),l.jsx("div",{className:"rounded-md bg-muted p-3",children:l.jsx("p",{className:"break-all font-mono text-xs",children:w})})]})]}),l.jsxs("div",{className:"flex flex-col gap-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(m.Label,{children:"Parameters"}),l.jsx(m.TooltipProvider,{children:l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Info,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(m.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-xs",children:"Click any parameter to insert it into your URL at the cursor position. Attributes come from your chart data, Identifiers are system values."})})]})})]}),l.jsxs("div",{className:"flex flex-col gap-6 rounded-lg border p-4",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Attributes"}),l.jsxs("div",{className:"space-y-1",children:[g.map(j=>l.jsx(B7,{parameter:j,isUsed:y.some(I=>I.id===j.id),onClick:()=>_(j)},j.id)),g.length===0&&l.jsx("p",{className:"text-sm text-muted-foreground",children:"No attributes available"})]})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Identifiers"}),l.jsx("div",{className:"space-y-1",children:b.map(j=>l.jsx(B7,{parameter:j,isUsed:y.some(I=>I.id===j.id),onClick:()=>_(j)},j.id))})]})]})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ln,{id:"encode-params",checked:u,onCheckedChange:j=>d(j===!0)}),l.jsx(m.Label,{htmlFor:"encode-params",className:"cursor-pointer text-sm font-normal",children:"URL encode parameters"}),l.jsx(m.TooltipProvider,{children:l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Info,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(m.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-xs",children:"Recommended. Encodes special characters in parameter values to ensure valid URLs (e.g., spaces become %20)."})})]})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(m.TooltipProvider,{children:l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Info,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(m.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-xs",children:"How this interaction appears when multiple actions are available"})})]})})]}),l.jsx(m.Input,{value:f,onChange:j=>h(j.target.value),placeholder:tp("drillToURL")})]}),l.jsxs("div",{className:"flex items-start gap-2 rounded-lg border bg-muted/50 p-3",children:[l.jsx(m.Info,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"URLs will always open in a new browser tab when clicked."})]})]}),l.jsxs(Gc,{children:[l.jsx(m.Button,{variant:"outline",onClick:D,children:"Cancel"}),l.jsx(m.Button,{onClick:E,disabled:!S.valid,children:"Save"})]})]})})}function B7({parameter:e,isUsed:t,onClick:n}){var o,i;const r=e.category==="attribute"?"🏷️":"#",s=((o=e.field)==null?void 0:o.qualifiedFieldName)||((i=e.field)==null?void 0:i.name);return l.jsxs(m.Button,{type:"button",variant:"ghost",className:"h-auto w-full justify-start gap-2 px-3 py-2 font-normal hover:bg-accent",onClick:n,children:[l.jsx("span",{className:"text-base",children:r}),l.jsxs("div",{className:"flex flex-1 flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-sm",children:e.label}),s&&l.jsx("span",{className:"text-xs text-muted-foreground",children:s})]}),t&&l.jsx(Yr,{variant:"secondary",className:"ml-auto gap-1",children:l.jsx(m.Check,{className:"h-3 w-3"})})]})}function DQe({interaction:e,availableFields:t,onUpdate:n}){const[r,s]=v.useState(!1),o=!!e.urlTemplate;return l.jsxs("div",{className:"flex flex-col gap-4",children:[o?l.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border p-4",children:[l.jsxs("div",{className:"flex items-start justify-between gap-4",children:[l.jsxs("div",{className:"flex-1 space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Am,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"text-sm font-medium",children:"URL Template"})]}),l.jsx("div",{className:"rounded-md bg-muted p-3",children:l.jsx("p",{className:"break-all font-mono text-xs",children:e.urlTemplate})})]}),l.jsxs(m.Button,{variant:"outline",size:"sm",onClick:()=>s(!0),children:[l.jsx(jk,{className:"mr-2 h-4 w-4"}),"Edit"]})]}),e.parameters&&e.parameters.length>0&&l.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.parameters.length," parameter",e.parameters.length!==1?"s":""," configured"]}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["URL encoding:"," ",e.encodeParameters!==!1?"enabled":"disabled"]})]}):l.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border border-dashed p-8",children:[l.jsx(Am,{className:"h-8 w-8 text-muted-foreground"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"No URL configured"}),l.jsx(m.Button,{variant:"outline",size:"sm",onClick:()=>s(!0),children:"Add Custom URL"})]}),l.jsx(EQe,{open:r,onOpenChange:s,interaction:e,availableFields:t,onSave:n})]})}function IQe({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Fetch mode"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose when to load the detailed data"}),l.jsxs(m.Select,{value:e.fetchMode||"lazy",onValueChange:n=>t({...e,fetchMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsx(m.SelectValue,{placeholder:"Choose fetch mode..."})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"lazy",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"Lazy loading"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Fetch data only when user clicks"})]})}),l.jsx(m.SelectItem,{value:"preloaded",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"Preloaded"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Fetch all data when dashboard loads"})]})})]})]}),l.jsxs("div",{className:"rounded-md bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 p-3 flex gap-2",children:[l.jsx(m.Info,{className:"h-4 w-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0"}),l.jsx("div",{className:"text-xs text-blue-800 dark:text-blue-200",children:e.fetchMode==="lazy"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"font-medium",children:"Lazy loading"}),l.jsx("div",{className:"mt-1",children:"Data is fetched on-demand when the user clicks. Best for large datasets or when detailed data isn't always needed."})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"font-medium",children:"Preloaded"}),l.jsx("div",{className:"mt-1",children:"Data is fetched when the dashboard loads. Best for small datasets or when instant drill-down is required."})]})})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Record limit"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Maximum number of detailed records to show (0 for unlimited)"}),l.jsx(m.Input,{type:"number",min:"0",placeholder:"100",value:e.inlineLimit??100,onChange:n=>{const r=parseInt(n.target.value)||0;t({...e,inlineLimit:r})}})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Display mode"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"How to display the detailed records"}),l.jsxs(m.Select,{value:e.displayMode||"table",onValueChange:n=>t({...e,displayMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsx(m.SelectValue,{placeholder:"Choose display mode..."})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"table",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"Table view"})})}),l.jsx(m.SelectItem,{value:"list",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"List view"})})}),l.jsx(m.SelectItem,{value:"cards",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"Card view"})})})]})]})]}),l.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 bg-background",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Show in modal"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Display detailed records in a modal overlay"})]}),l.jsx(m.Switch,{checked:e.showInModal??!1,onCheckedChange:n=>t({...e,showInModal:n})})]}),l.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 bg-background",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Allow export"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Enable users to export the detailed records"})]}),l.jsx(m.Switch,{checked:e.allowExport??!0,onCheckedChange:n=>t({...e,allowExport:n})})]}),l.jsxs("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:[l.jsx("div",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Inline drill configured successfully"}),l.jsxs("div",{className:"mt-2 space-y-1 text-xs text-green-700 dark:text-green-300",children:[l.jsxs("div",{children:["Mode: ",e.fetchMode==="lazy"?"Lazy loading":"Preloaded"]}),l.jsxs("div",{children:["Limit: ",e.inlineLimit===0?"Unlimited":`${e.inlineLimit} records`]}),l.jsxs("div",{children:["Display: ",e.displayMode==="table"?"Table view":e.displayMode==="list"?"List view":"Card view"]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(m.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:tp(e.mode)}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function TQe({interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i,onRemove:a}){const c=e.trigger!==void 0,u=e.mode!==void 0,d=c&&u,[f,h]=v.useState(!d),p=()=>{var y;if(!c)return"Configure interaction";const b=`When ${((y=e.trigger)==null?void 0:y.field.label)||"..."}`;if(!u)return`${b} → Choose action`;const x=e.label||tp(e.mode);return`${b} → ${x}`},g=u?UN(e.mode):null;return l.jsxs(Tm,{className:"relative p-0",children:[l.jsx(m.Button,{variant:"ghost",size:"sm",className:"absolute right-2 top-2 z-10 h-8 w-8 p-0",onClick:a,"aria-label":"Remove interaction",children:l.jsx(m.X,{className:"h-3 w-3"})}),l.jsxs(Vc,{open:f,onOpenChange:h,children:[l.jsx(Hc,{asChild:!0,children:l.jsxs(m.Button,{variant:"ghost",className:"h-auto w-full justify-between p-4 pr-12 hover:bg-muted/50",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[g&&l.jsx(g,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"text-left text-sm font-medium",children:p()})]}),f?l.jsx(pF,{className:"h-3 w-3 flex-shrink-0"}):l.jsx(_k,{className:"h-3 w-3 flex-shrink-0"})]})}),l.jsx(Uc,{children:l.jsxs("div",{className:"space-y-6 border-t p-6",children:[l.jsx("div",{className:"space-y-3",children:c?l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"text-sm font-medium",children:["When I click on"," ",l.jsx("span",{className:"text-muted-foreground",children:"(value of)"})]}),e.trigger&&l.jsxs("div",{className:"inline-flex cursor-pointer items-center gap-2 rounded-md border bg-background px-3 py-2 hover:bg-muted/50",onClick:()=>{i({...e,trigger:void 0})},children:[WN(e.trigger.field.dataType),l.jsx("span",{className:"text-sm font-medium",children:e.trigger.field.label})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"text-sm font-medium",children:"When I click on"}),l.jsx(WKe,{value:e.trigger,onChange:b=>{i({...e,trigger:b})},metrics:t,attributes:n})]})}),c&&l.jsx(l.Fragment,{children:l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"text-sm font-medium",children:"I want to"}),l.jsx(qKe,{value:e.mode,onChange:b=>{if(!e.trigger){console.error("Trigger must be defined before selecting action");return}const x={mode:b,trigger:e.trigger};switch(b){case"clickFilter":i({...x,mode:"clickFilter",filterFields:[]});break;case"drillDown":i({...x,mode:"drillDown",filterFields:[]});break;case"dynamicDrill":i({...x,mode:"dynamicDrill",availableFields:[]});break;case"drillThrough":i({...x,mode:"drillThrough",filterFields:[],targetDashboardId:""});break;case"drillToDetail":i({...x,mode:"drillToDetail",filterFields:[]});break;case"drillToURL":i({...x,mode:"drillToURL",filterFields:[],urlTemplate:"",parameters:[],encodeParameters:!0});break;case"inlineDrill":i({...x,mode:"inlineDrill",filterFields:[]});break}}})]})}),c&&u&&l.jsxs(l.Fragment,{children:[l.jsx(m.Separator,{}),l.jsx(MQe,{interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i})]})]})})]})]})}function MQe({interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i}){switch(e.mode){case"clickFilter":return l.jsx(YKe,{interaction:e,onUpdate:a=>i(a)});case"drillDown":return l.jsx(fQe,{interaction:e,onUpdate:a=>i(a),card:s,availableFields:r,onUpdateHierarchies:o});case"dynamicDrill":return l.jsx(mQe,{interaction:e,onUpdate:a=>i(a),availableFields:r});case"drillThrough":return l.jsx(xQe,{interaction:e,onUpdate:a=>i(a)});case"drillToDetail":return l.jsx(wQe,{interaction:e,onUpdate:a=>i(a)});case"drillToURL":return l.jsx(DQe,{interaction:e,availableFields:[...t,...n],onUpdate:a=>i(a)});case"inlineDrill":return l.jsx(IQe,{interaction:e,onUpdate:a=>i(a)});default:return l.jsx("div",{className:"text-sm text-muted-foreground",children:"Unknown interaction type"})}}function AQe({interactions:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onChange:i}){const[a,c]=v.useState(null),u=()=>{const h=OGe().id,p={id:h};i([...e,p]),c(h)},d=(h,p)=>{const g=e[h],b={...p,id:p.id||(g==null?void 0:g.id)},x=[...e];x[h]=b,i(x)},f=h=>{var g;const p=e.filter((b,x)=>x!==h);i(p),a===((g=e[h])==null?void 0:g.id)&&c(null)};return l.jsxs("div",{className:"space-y-4",children:[e.length>0?l.jsx("div",{className:"space-y-3",children:e.map((h,p)=>l.jsx(TQe,{interaction:h,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:g=>d(p,g),onRemove:()=>f(p)},h.id||p))}):l.jsx("div",{className:"border rounded-lg p-8 text-center bg-muted/30",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"No interactions configured"}),l.jsx("div",{className:"text-xs text-muted-foreground",children:'Click "Add Interaction" to create your first interaction'}),l.jsx("div",{className:"pt-2",children:l.jsxs(m.Button,{onClick:u,size:"sm",variant:"outline",children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Add First Interaction"]})})]})}),e.length>0&&l.jsx("div",{className:"flex justify-start pt-2",children:l.jsxs(m.Button,{onClick:u,size:"sm",variant:"outline",children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Add Interaction"]})})]})}const RQe=[],FQe=[],PQe=[];function ST(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function OQe(e){return e.flatMap(t=>t.columns.map(n=>({...n,id:n.id||`${t.entityId}-${n.name}`,name:n.name,qualifiedFieldName:n.qualifiedFieldName||n.name,dataType:n.dataType,qualifiedEntityName:n.qualifiedEntityName||t.qualifiedEntityName,label:n.label||m.toTitleCase(n.name),description:n.description,entityId:n.entityId||t.entityId,entityName:n.entityName||t.entityName,entityType:n.entityType||t.entityType})))}function XL(e){var C;const{tokenProps:t}=Ct(),n=m.useDashboardStore(N=>N.authToken)||e,{selectedConnection:r,hasSchemaSupport:s}=FZ(e),o=m.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.connectionId}),i=m.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.semanticDomainId}),a=m.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.selectedEntities}),c=v.useMemo(()=>(a==null?void 0:a.filter(N=>N.type==="model"))||RQe,[a]),u=v.useMemo(()=>(a==null?void 0:a.filter(N=>m.DATABASE_ENTITY_TYPES.includes(N.type)))||FQe,[a]),d=v.useMemo(()=>(a==null?void 0:a.filter(N=>N.type==="dataset"))||PQe,[a]);function f(N){var k;if(N.type==="dataset")return!!o&&!!N.domainId&&!!N.name;if(N.type==="model")return!!o&&!!N.id;if(m.DATABASE_ENTITY_TYPES.includes(N.type)){const _=((k=r==null?void 0:r.capabilities)==null?void 0:k.path)||[],E=_.includes("database"),D=_.includes("schema")||s;return!(!o||!N.name||E&&!N.database||D&&!N.schema)}return!1}const h=[...c,...u,...d],p=hg({queries:h.map(N=>{let k={};return N.type==="model"?k=ST({connection_id:o,datamodel_id:N.id,database_name:"",schema_name:"",table_name:""}):N.type==="dataset"?k=ST({connection_id:N.connectionId,domain_id:N.domainId,dataset_name:N.name,database_name:N.database,schema_name:N.schema,table_name:N.table}):k=ST({connection_id:o,datamodel_id:"",database_name:N.database,schema_name:N.schema,table_name:N.name}),{queryKey:["columns",o,N,i||null],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",k),enabled:!!o&&f(N)}})}),g=p.some(N=>N.isPending&&N.fetchStatus==="fetching"),b=p.some(N=>N.isError),x=(C=p.find(N=>N.isError))==null?void 0:C.error,y=p.map((N,k)=>{var T,F;const _=h[k],E=((T=N.data)==null?void 0:T.columns)||[],D=_.type==="dataset"?(F=E.find(P=>P.entityName))==null?void 0:F.entityName:void 0,j=D||_.name,I=m.getQualifiedEntityName(_.type==="dataset"&&D?{..._,name:D}:_);return{entityId:_.id||_.name,entityType:_.type,entityName:j,label:_.label,description:_.description,qualifiedEntityName:I,columns:E.map(P=>{const R=_.type==="dataset"?P.entityName||j:_.name,B=P.qualifiedEntityName||(_.type==="dataset"&&R?m.getQualifiedEntityName({..._,name:R}):I);return{id:`${R}-${P.column_name}`,name:P.column_name,qualifiedFieldName:P.qualifiedFieldName||P.column_name,dataType:P.data_type,label:P.label||m.toLabel(P.column_name),description:P.description||"",qualifiedEntityName:B,entityId:P.entityId||_.id||_.id||R,entityName:R,entityType:P.entityType||_.type,role:P.role,expression:P.expression,calculatedFormula:P.calculatedFormula,format:m.fromSemanticFormat(P.format)}})}}).filter(N=>{var k;return((k=N==null?void 0:N.columns)==null?void 0:k.length)>0})||[],S=p.flatMap(N=>{var k;return((k=N.data)==null?void 0:k.calculatedFields)||[]}).map(N=>({...N,id:m.getStableDomainCalculatedFieldId({...N}),fieldScope:"domain"}));if(S.length>0){const N=new Map;S.forEach(k=>{const _=m.getStableDomainCalculatedFieldId(k);N.has(_)||N.set(_,k)}),y.unshift({entityId:m.CALCULATED_FIELDS_GROUP_ID,entityType:"dataset",entityName:m.CALCULATED_FIELDS_GROUP_NAME,label:"Calculated Fields",description:"Domain-level calculated metrics and dimensions",qualifiedEntityName:m.CALCULATED_FIELDS_GROUP_NAME,columns:Array.from(N.values())})}const w=OQe(y);return{columnGroups:y,columns:w,isLoading:g,hasError:b,error:x,refetch:async()=>{await Promise.all(p.map(N=>N.refetch()))}}}function LQe(e){const t=n=>{if(!n||typeof n!="object")return!1;const r=n;return Array.isArray(r.cards)};if(!e)return null;if(typeof e=="string")try{const n=JSON.parse(e);return t(n)?n:null}catch{return null}return t(e)?e:null}function QN(e){return Array.isArray(e)?e.map(t=>QN(t)):e&&typeof e=="object"?Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).reduce((t,[n,r])=>(t[n]=QN(r),t),{}):e}function CT(e,t){return JSON.stringify(QN(e))===JSON.stringify(QN(t))}function $Qe(){var V,H,A,W,X,Z,J,re,fe;const{open:e,frameId:t,cardId:n,closePopover:r,anchorPosition:s}=TP(),{authToken:o,tokenProps:i}=Ct(),a=ns(),{updateCurrentDashboardCard:c,updateFrameCard:u}=m.useDashboardActions(),{setCard:d}=m.useEditorActions(),f=m.useDashboardStore(de=>de.dashboard),h=((V=f==null?void 0:f.sheets)==null?void 0:V.flatMap(de=>de.frames||[]).find(de=>(de==null?void 0:de.id)===t))||null,p=h&&n?h.cards.find(de=>de.id===n):null,g=!!(h!=null&&h.visualId&&p),b=Ak((h==null?void 0:h.visualId)||"",{enabled:e&&g&&!!(o!=null&&o.accessToken)&&!!(i!=null&&i.apiServiceUrl)}),x=((H=b.data)==null?void 0:H.frameObject)||((W=(A=b.data)==null?void 0:A.visual)==null?void 0:W.frameObject),y=v.useMemo(()=>LQe(x),[x]),S=((X=b.data)==null?void 0:X.lastModified)||((J=(Z=b.data)==null?void 0:Z.visual)==null?void 0:J.lastModified),w=v.useMemo(()=>{if(!p||!h||!y)return null;const de=p.linkedSourceCardId&&y.cards.find(ue=>ue.id===p.linkedSourceCardId);if(de)return de;const Se=h.cards.findIndex(ue=>ue.id===p.id);return Se>=0&&y.cards[Se]||null},[p,h,y]),C=v.useMemo(()=>{const de=new Map;return!h||!y||h.cards.forEach((Se,ue)=>{var xe;const ve=Se.linkedSourceCardId||((xe=y.cards[ue])==null?void 0:xe.id);ve&&de.set(ve,Se.id)}),de},[h,y]),N=v.useMemo(()=>{var Se;if(!w)return[];const de=of((Se=w.interactionConfig)==null?void 0:Se.interactions);return JS(de,C)},[w,C]),k=v.useMemo(()=>p?fT(N,p.linkedInteractionTargetOverrides):[],[p,N]),_=g?w:p,E=g&&!!x&&!y&&!b.isFetching;v.useEffect(()=>{if(!e)return;const de=g&&w||p;de&&d(de)},[e,g,w,p,d]);const{columns:D}=XL(),j=_==null?void 0:_.config,I=D,T=(j==null?void 0:j.metricColumns)||[],F=[...(j==null?void 0:j.groupByColumns)||[],...(j==null?void 0:j.pivotByColumns)||[]],[P,R]=v.useState(((re=_==null?void 0:_.interactionConfig)==null?void 0:re.drillHierarchies)||[]),[B,z]=v.useState(((fe=_==null?void 0:_.interactionConfig)==null?void 0:fe.allowedDrillTargets)||[]),[U,Y]=v.useState([]),[O,K]=v.useState(!1),q=v.useRef(null),M=v.useMemo(()=>`${e}-${t}-${n}-${g?(w==null?void 0:w.id)||"loading":(p==null?void 0:p.id)||"none"}`,[e,t,n,g,w==null?void 0:w.id,p==null?void 0:p.id]);v.useEffect(()=>{e||(q.current=null)},[e]),v.useEffect(()=>{var de,Se,ue;!e||!_||g&&!w||q.current!==M&&(R(((de=_.interactionConfig)==null?void 0:de.drillHierarchies)||[]),z(((Se=_.interactionConfig)==null?void 0:Se.allowedDrillTargets)||[]),Y(g?k:of((ue=_.interactionConfig)==null?void 0:ue.interactions)),q.current=M)},[e,_,M,g,w,k]);const G=async()=>{var de,Se,ue,ve,xe;if(p){K(!0);try{const ke=of(m.normalizeInteractionsForSave(U));if(!g||!(h!=null&&h.visualId)||!y||!w){const Xe={...p,interactionConfig:{...p.interactionConfig,drillHierarchies:P,allowedDrillTargets:B,interactions:ke}},et=(Se=(de=f==null?void 0:f.sheets)==null?void 0:de.find(tt=>(tt.frames||[]).some(me=>me.id===(h==null?void 0:h.id))))==null?void 0:Se.id;et&&(h!=null&&h.id)&&u?u(et,h.id,Xe):c(Xe),d(Xe),r();return}const se=of((ue=w.interactionConfig)==null?void 0:ue.interactions),be=FGe(ke,se),Ce=((ve=w.interactionConfig)==null?void 0:ve.drillHierarchies)||[],ge=((xe=w.interactionConfig)==null?void 0:xe.allowedDrillTargets)||[],ee=!CT(P,Ce)||!CT(B,ge)||!CT(be,se),te={...w,interactionConfig:{...w.interactionConfig,drillHierarchies:P,allowedDrillTargets:B,interactions:be}},ce={...y,cards:y.cards.map(Xe=>Xe.id===w.id?te:Xe)};if(ee){if(!(i!=null&&i.apiServiceUrl)||!(o!=null&&o.accessToken))throw new Error("Missing authentication context for visual update");const Xe=await fetch(`${i.apiServiceUrl}/management/v1/visuals/${h.visualId}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(o==null?void 0:o.accessToken)||""}`},body:JSON.stringify({frameObject:ce,expectedLastModified:S})});if(!Xe.ok){const tt=await Xe.json().catch(()=>({})),me=new Error((tt==null?void 0:tt.error)||"Failed to update visual");throw me.status=Xe.status,me}const et=await Xe.json();a.setQueryData(["resource-by-id","visual",h.visualId],et)}const le=JS(of(be),C),Ee=le.filter(Xe=>Xe.id).map(Xe=>Xe.id),ye=g7(PGe(ke,le),Ee),ne=fT(le,ye),je={...p,linkedSourceCardId:p.linkedSourceCardId||w.id,linkedInteractionTargetOverrides:ye,interactionConfig:{...p.interactionConfig,drillHierarchies:P,allowedDrillTargets:B,interactions:ne}},Ue=Xe=>{const et=new Map;return Xe.cards.forEach((tt,me)=>{var Ve;const Ye=tt.linkedSourceCardId||((Ve=y.cards[me])==null?void 0:Ve.id);Ye&&et.set(Ye,tt.id)}),et},Be=Xe=>{const et=Xe.cards.find(me=>me.linkedSourceCardId===w.id);if(et)return et;const tt=y.cards.findIndex(me=>me.id===w.id);return tt>=0&&Xe.cards[tt]||null},rt=[];if((f.sheets||[]).forEach(Xe=>{(Xe.frames||[]).forEach(et=>{if(et.visualId!==h.visualId)return;const tt=Be(et);if(!tt)return;const me=Ue(et),Ye=JS(of(be),me),Ve=Ye.filter(He=>He.id).map(He=>He.id),$e=et.id===h.id&&tt.id===p.id?ye:tt.linkedInteractionTargetOverrides,Ae=g7($e,Ve),Re=fT(Ye,Ae);rt.push({sheetId:Xe.id,frameId:et.id,isCurrentCard:et.id===h.id&&tt.id===p.id,card:{...tt,linkedSourceCardId:tt.linkedSourceCardId||w.id,linkedInteractionTargetOverrides:Ae,interactionConfig:{...tt.interactionConfig,drillHierarchies:P,allowedDrillTargets:B,interactions:Re}}})})}),rt.length>0&&u){rt.forEach(et=>{u(et.sheetId,et.frameId,et.card)});const Xe=rt.find(et=>et.isCurrentCard);Xe||c(je),d((Xe==null?void 0:Xe.card)||je)}else c(je),d(je);r()}catch(ke){ke.status===409?(ut.error("This saved visual was updated by another editor. Refresh and retry."),q.current=null,await b.refetch()):ut.error(ke.message||"Failed to save interactions")}finally{K(!1)}}},L=()=>{q.current=null,r()};if(!e||!t||!n||!p||!s)return null;const $={position:"fixed",left:`${s.left}px`,top:`${s.top}px`,width:`${s.width}px`,height:`${s.height}px`};return l.jsxs(m.Popover,{modal:!1,open:e,onOpenChange:de=>!de&&r(),children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsx("div",{style:$,className:"pointer-events-none invisible","aria-hidden":"true"})}),l.jsxs(m.PopoverContent,{onEscapeKeyDown:de=>de.preventDefault(),className:"mt-5 flex max-h-[70vh] w-[600px] max-w-4xl flex-col overflow-hidden p-0",align:"start",side:"right",sideOffset:20,children:[l.jsx(m.Arrow2,{className:"fill-border",width:12,height:8}),l.jsxs("div",{className:"flex flex-col border-b px-6 py-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h2",{className:"text-lg font-semibold",children:"Configure Interactions"}),U.length>0&&l.jsx(Yr,{variant:"default",className:"h-5 min-w-5 rounded-full px-1.5 text-xs",children:U.length})]}),l.jsxs("p",{className:"text-sm text-muted-foreground",children:["Set up drill behaviors for"," ",(p==null?void 0:p.title)||"this chart"]}),g&&l.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Logic is owned by the saved visual. Filter target routing is saved per dashboard instance."})]}),l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:l.jsx("div",{className:"space-y-6 p-6",children:g&&!w?l.jsx("p",{className:"text-sm text-muted-foreground",children:b.isFetching?"Loading saved visual interaction config...":E?"Unable to load interaction settings for this saved visual. Please refresh or relink the visual.":"Unable to map this dashboard card to its source card in the saved visual. Re-link the visual to continue."}):l.jsx("div",{children:l.jsx("div",{className:"grid grid-cols-1 gap-4",children:l.jsx(AQe,{interactions:U,metrics:T,attributes:F,availableFields:I,card:{..._||p,interactionConfig:{...(_==null?void 0:_.interactionConfig)||p.interactionConfig,drillHierarchies:P}},onUpdateHierarchies:R,onChange:de=>Y(de)})})})})}),l.jsxs("div",{className:"flex justify-end gap-2 border-t px-6 py-4",children:[l.jsx(m.Button,{variant:"outline",onClick:L,children:"Cancel"}),l.jsx(m.Button,{onClick:G,disabled:O||g&&!w,children:O?"Saving...":g?"Save to Library":"Accept"})]})]})]})}function bR(e,t){return Mo.serializeLayoutsForDirtyCheck(e)!==Mo.serializeLayoutsForDirtyCheck(t)}function zQe(e,t){return t&&bR(e,t)?t:null}function BQe(e){return!!e.expression}function VQe(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function HQe(e){const t=VQe(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function zae(e){return e.fieldScope==="domain"&&e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===m.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===m.CALCULATED_FIELDS_GROUP_NAME}function UQe(e){return zae(e)}function WQe(e){return e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||(e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card")&&HQe(e.id)&&!e.entityName}function bd(e){return BQe(e)?UQe(e)?"domain_calculated":WQe(e)?"user_calculated":"inline_expression":"none"}function fb(e){return bd(e)!=="none"}function ka(e){if(!fb(e))return!1;const t=bd(e);return t==="domain_calculated"||t==="user_calculated"?!0:e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card"}function Bae(e){return ka(e)&&e.fieldScope!=="card"}function Vae(e,t,n){return fb(e)?t==="editor"?!0:t==="filter"?ka(e)&&e.fieldScope!=="card":ka(e)&&(n==null?void 0:n.isValuePickSafe)!==!1:!1}function NT(e,t){return e.map(n=>({...n,fieldScope:t}))}function Hae(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=XL(),i=m.useEditorStore(_=>_.frame.calculatedFields),a=m.useEditorStore(_=>_.card.calculatedFields),c=m.useEditorStore(_=>_.card.config),u=m.useDashboardStore(_=>_.dashboard),d=m.useDashboardStore(_=>_.visualEditPendingDashboardCalculatedFields),f=m.useDashboardStore(_=>_.selectedSheetId),h=m.useDashboardStore(_=>_.selectedFrameId),p=m.useDashboardStore(_=>_.isVisualEditing),g=v.useMemo(()=>e.filter(_=>bd(_)==="domain_calculated"),[e]),b=v.useMemo(()=>e.filter(_=>bd(_)!=="domain_calculated"),[e]),x=v.useMemo(()=>{var E;if(p)return i||[];const _=(E=u==null?void 0:u.sheets)==null?void 0:E.find(D=>D.id===f);return m.getSheetCalculatedFields(_)},[u==null?void 0:u.sheets,i,p,h,f]),y=v.useMemo(()=>{const _=d??(u==null?void 0:u.calculatedFields)??[];return _.length?NT(_,"dashboard"):[]},[u==null?void 0:u.calculatedFields,d]),S=v.useMemo(()=>x.length?NT(x,"sheet"):[],[x]),w=v.useMemo(()=>m.buildCalculatedFieldComparableKeySet([...y,...S]),[y,S]),C=v.useMemo(()=>{const _=(a||[]).filter(T=>ka(T)&&T.fieldScope!=="domain"),E=((c==null?void 0:c.metricColumns)||[]).filter(T=>ka(T)&&T.fieldScope!=="domain"),D=((c==null?void 0:c.groupByColumns)||[]).filter(T=>ka(T)&&T.fieldScope!=="domain"),I=m.dedupeCalculatedFields([..._,...E,...D]).filter(T=>!w.has(m.getCalculatedFieldComparableKey(T)));return NT(I,"card").map(T=>({...T,id:`card-source-${T.id}`}))},[a,c==null?void 0:c.groupByColumns,c==null?void 0:c.metricColumns,w]),N=v.useMemo(()=>[...g,...y,...S,...C,...b],[C,b,y,g,S]),k=v.useMemo(()=>t.filter(_=>_.entityId!==m.CALCULATED_FIELDS_GROUP_ID),[t]);return{columns:e,columnGroups:k,rawColumnGroups:t,columnFields:b,domainCalculatedFields:g,dashboardCalculatedFields:y,sheetCalculatedFields:S,cardCalculatedFields:C,scopedFields:N,isLoading:n,hasError:r,error:s,refetch:o}}function qQe(e){const t="expression"in e&&e.expression||"",n=e.qualifiedEntityName||e.entityName||"",r=e.fieldScope||"unscoped",s=e.qualifiedFieldName||e.name;return t?["calculated",r,e.role||"field",n,s,t].join("::"):["calculated",r,e.role||"field",n,m.normalizeCalculatedFieldId(e.id)||s].join("::")}function YQe(e){return["physical",e.fieldScope||"physical",e.role||"field",e.qualifiedEntityName||"",e.qualifiedFieldName||e.name,e.name].join("::")}function Vp(e){const t=new Map;return e.forEach(n=>{const r=fb(n)?qQe(n):YQe(n);t.has(r)||t.set(r,n)}),Array.from(t.values())}function QL(e){return!Cr.isCalculatedMetric(e)}function kT(e,t){return Vp(e.filter(n=>Vae(n,t,{isValuePickSafe:QL(n)})))}function GQe(e){return!fb(e)||Vae(e,"inline-filter",{isValuePickSafe:QL(e)})}function KQe(e){return!fb(e)||Bae(e)}function Uae(){const e=Hae(),t=v.useMemo(()=>Vp(e.scopedFields),[e.scopedFields]),n=v.useMemo(()=>Vp([...e.columns,...e.dashboardCalculatedFields,...e.sheetCalculatedFields]),[e.columns,e.dashboardCalculatedFields,e.sheetCalculatedFields]),r=v.useMemo(()=>Vp(n.filter(KQe)),[n]),s=v.useMemo(()=>kT(t,"editor"),[t]),o=v.useMemo(()=>kT(n.filter(Bae),"filter"),[n]),i=v.useMemo(()=>Vp(t.filter(QL)),[t]),a=v.useMemo(()=>Vp(i.filter(GQe)),[i]),c=v.useMemo(()=>kT(a,"inline-filter"),[a]);return{...e,filterableFields:t,sharedFilterableFields:n,dashboardFilterableFields:r,inlineFilterableFields:a,scopedCalculatedFields:s,sharedCalculatedFields:o,inlineCalculatedFields:c,valuePickFilterableFields:i}}const Wae=Q.forwardRef(function({icon:t,label:n,asButton:r,disabled:s,labelWrapper:o,inQuery:i,trailing:a,kebab:c,showKebab:u,onKebabClick:d,selected:f,dragging:h,disableHover:p,className:g,...b},x){const y=l.jsx("span",{className:"block min-w-0 flex-1 truncate text-[13px] text-foreground/90",children:n}),S=m.cn("group/field-row relative flex h-7 items-center gap-2 px-4 transition-colors",h&&"opacity-40",f?"bg-muted":i?"bg-foreground/[0.06] hover:bg-foreground/[0.09]":!p&&"hover:bg-muted/60",r&&"w-full text-left disabled:cursor-not-allowed",g),w=l.jsxs(l.Fragment,{children:[t,o?o(y):y,i&&l.jsx("span",{className:"sr-only",children:"In query"}),a,(c||u)&&l.jsx("button",{type:"button","aria-label":"Field actions",onClick:C=>{C.stopPropagation(),d==null||d(C)},onPointerDown:C=>C.stopPropagation(),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:opacity-100 group-focus-within/field-row:opacity-100 [@media(hover:none)]:opacity-100",children:c??l.jsx(ja,{className:"h-3 w-3"})})]});return r?l.jsx("button",{ref:x,type:"button",disabled:s,"data-selected":f?"true":void 0,className:S,...b,children:w}):l.jsx("div",{ref:x,"data-selected":f?"true":void 0,className:S,...b,children:w})});function JL(e){const{tokenProps:t,authToken:n}=Ct(),r=t==null?void 0:t.apiServiceUrl;return On({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return m.getRequest(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function qae(e,t,n){if(t==="source")return{isValid:!0};const r=m.getDataType(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function Yae(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function ZQe(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const XQe=new Set(["COUNT","DISTINCT"]),QQe=new Set(["running_total","moving_average","previous_period_delta"]);function JQe(e){return m.getDataType(e.dataType||"")==="number"?!0:e.aggregate?XQe.has(e.aggregate.toUpperCase()):!1}function eJe(e,t){var r,s;return!!((s=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:s.function)}function e3(e,t){var n,r;return e==="aggregateTable"&&((((n=t.rowAggregates)==null?void 0:n.length)??0)>0||(((r=t.columnAggregates)==null?void 0:r.length)??0)>0)}function Gae({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,c;if(e==="detailTable"||e==="kpi")return{supported:!1,reason:"Metric transforms are not supported for this card type."};if((((i=t.groupByColumns)==null?void 0:i.length)??0)===0)return{supported:!1,reason:"Metric transforms require at least one grouped dimension."};if(!JQe(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const s=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,o=e==="pivotTable"||e3(e,t);return s&&!o?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:QQe.has(r)&&(((c=t.groupByColumns)==null?void 0:c.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function tJe(e){return e.find(t=>m.getDataType(t.dataType||"")==="date")}function nJe(e){return e}function vy({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(o=>o.id&&o.id!==n).map(o=>o.id),s=[];if(e==="pivotTable"||e3(e,t))for(const o of t.pivotByColumns||[])o.id&&s.push(o.id);return Array.from(new Set([...r,...s]))}function rJe({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const s=r||((i=tJe(n.groupByColumns||[]))==null?void 0:i.id),o=vy({cardType:t,cardConfig:n,orderByFieldId:s});return e==="moving_average"?{function:"moving_average",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,frame:"unbounded_preceding"}}const sJe=new Set(["table","aggregateTable","pivotTable","detailTable"]);function oJe(e){return e.alias||e.label||e.name}function Kae(e,t,n){var a,c,u;if(!e)return null;const r=m.fromSemanticFormat(t.format);if(!r)return null;const s=n||{};let o=s,i=!1;if(sJe.has(e.type)){const d=m.toColumnNumberFormat(r),f=oJe(t);if(d&&!((c=(a=s.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:c[f])){const p=so();o={...o,tablePrefs:{...o.tablePrefs||{},columnSettingsMap:{...((u=o.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...p,type:"number",textAlign:"right",numberFormat:{...p.numberFormat,...d}}}}},i=!0}if(!s.formatNumber){const h=m.toLegacyFormatNumber(r);h&&(o={...o,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?o:null}const Zae=e=>{var L;const t=(L=e==null?void 0:e.dataSource)==null?void 0:L.semanticDomainId,{data:n}=JL(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=m.useEditorActions(),p=m.useEditorStore($=>$.card.type),g=e==null?void 0:e.id,b=($,V)=>{if($.id)return $.id;const H=$.qualifiedEntityName||$.entityName||V;return`${V}-${H}-${$.name}`},x=v.useCallback($=>{if(!(e!=null&&e.config))return[];switch($){case"groupBy":return(e.config.groupByColumns||[]).map(V=>({...V,id:b(V,"groupBy"),label:V.label!==void 0?V.label:V.name}));case"metrics":return(e.config.metricColumns||[]).map(V=>({...V,id:b(V,"metrics"),label:V.label!==void 0?V.label:V.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map(V=>({id:b(V,"pivotBy"),name:V.name,dataType:V.dataType,label:V.label!==void 0?V.label:V.name,qualifiedEntityName:V.qualifiedEntityName,entityId:V.entityId,entityName:V.entityName,entityType:V.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(V=>({id:b(V,"sortBy"),name:V.name,dataType:V.dataType,label:V.label!==void 0?V.label:V.name,qualifiedEntityName:V.qualifiedEntityName,entityId:V.entityId,entityName:V.entityName,entityType:V.entityType,direction:V.direction}));case"detailColumns":return ZQe(e.config.detailColumns,V=>b(V,"detailColumns"));case"source":return[];default:return[]}},[e]),y=v.useCallback(($,V)=>{if(g)switch($){case"groupBy":{r(g,{groupByColumns:V});break}case"metrics":{r(g,{metricColumns:V});break}case"pivotBy":{r(g,{pivotByColumns:V});break}case"sortBy":{r(g,{sortByColumns:V});break}case"detailColumns":{r(g,{detailColumns:V});break}}},[g,r]),S=v.useCallback(($,V,H)=>{if(!g)return;const A=x($),W=A[V];if(W)switch($){case"groupBy":s(g,W.id,{label:H});break;case"metrics":o(g,W.id,{label:H});break;case"pivotBy":i(g,W.id,{label:H});break;case"sortBy":a(g,W.id,{label:H});break;case"detailColumns":{const X=A.map((Z,J)=>J===V?{...Z,label:H}:Z);r(g,{detailColumns:X});break}}},[g,x,s,o,i,a,r]),w=v.useCallback(($,V)=>{if(!g)return;const A=x("metrics")[$];A&&o(g,A.id,{aggregate:V,label:oee(A.name,V)})},[g,x,o]),C=v.useCallback(($,V,H,A="groupBy")=>{if(!g)return;const W=x(A),X=W[$];if(!X)return;const Z={dateFormat:V,customFormat:V==="custom"&&H?H:void 0};if(A==="detailColumns"){const J=W.map((re,fe)=>fe===$?{...re,...Z}:re);r(g,{detailColumns:J});return}s(g,X.id,Z)},[g,x,r,s]),N=v.useCallback(($,V)=>{if(!g)return;const A=x("groupBy")[$];A&&s(g,A.id,{granularity:V})},[g,x,s]),k=v.useCallback(($,V)=>{if(!g)return;const A=x("metrics")[$];A&&o(g,A.id,{aliasTemplate:V})},[g,x,o]),_=v.useCallback(($,V)=>{if(console.log("handleValueAliasesChange",$,V),!g)return;console.log("handleValueAliasesChange",$,V);const A=x("metrics")[$];A&&(console.log("handleValueAliasesChange",V),o(g,A.id,{valueAliases:V}))},[g,x,o]),E=v.useCallback(($,V)=>{var W,X;if(!g)return;const A=x("metrics")[$];A&&(o(g,A.id,{format:V}),p==="kpi"&&((X=(W=e==null?void 0:e.preferences)==null?void 0:W.kpiVisualOptions)!=null&&X.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,g,p,x,h,o]),D=v.useCallback(($,V)=>{var X;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=V!=="none"&&((X=A.parameters)==null?void 0:X.windowTransform);o(g,A.id,{comparisonType:V,...V!=="target"?{targetValue:void 0}:{},...W?{parameters:{...A.parameters||{},windowTransform:void 0}}:{}})},[g,x,o]),j=v.useCallback(($,V)=>{var fe,de,Se;if(!g||!(e!=null&&e.config))return;const A=x("metrics")[$];if(!A)return;if(V==="none"){o(g,A.id,{parameters:{...A.parameters||{},windowTransform:void 0}});return}const W=Gae({cardType:p,cardConfig:e.config,metric:A,transformMode:V});if(!W.supported){ut.error(W.reason||"Metric transform is not supported here.");return}const X=new Set((e.config.groupByColumns||[]).map(ue=>ue.id)),Z=(Se=(de=(fe=A.parameters)==null?void 0:fe.windowTransform)==null?void 0:de.orderBy)==null?void 0:Se.fieldId,J=Z&&X.has(Z)?Z:void 0,re=rJe({transformMode:V,cardType:p,cardConfig:e.config,fallbackOrderByFieldId:J});o(g,A.id,{comparisonType:"none",targetValue:void 0,parameters:{...A.parameters||{},windowTransform:re}})},[e,g,p,x,o]),I=v.useCallback(($,V)=>{var re,fe;if(!g||!(e!=null&&e.config))return;const A=x("metrics")[$];if(!A)return;const W=(re=A.parameters)==null?void 0:re.windowTransform;if(!W||!["running_total","moving_average","previous_period_delta"].includes(W.function))return;const X=vy({cardType:p,cardConfig:e.config,orderByFieldId:V}),J=(W.partitionByFieldIds||X).filter(de=>de!==V);o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,orderBy:{fieldId:V,direction:((fe=W.orderBy)==null?void 0:fe.direction)||"asc"},partitionByFieldIds:J}}})},[e,g,p,x,o]),T=v.useCallback(($,V)=>{var X;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(X=A.parameters)==null?void 0:X.windowTransform;!W||!["running_total","moving_average","previous_period_delta"].includes(W.function)||o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,orderBy:W.orderBy?{...W.orderBy,direction:V}:W.orderBy}}})},[g,x,o]),F=v.useCallback(($,V)=>{var J,re;if(!g||!(e!=null&&e.config))return;const A=x("metrics")[$];if(!A)return;const W=(J=A.parameters)==null?void 0:J.windowTransform;if(!W)return;const X=vy({cardType:p,cardConfig:e.config,orderByFieldId:(re=W.orderBy)==null?void 0:re.fieldId}),Z=new Set(W.partitionByFieldIds||X);Z.has(V)?Z.delete(V):Z.add(V),o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,partitionByFieldIds:Array.from(Z)}}})},[e,g,p,x,o]),P=v.useCallback(($,V)=>{var re,fe;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(re=A.parameters)==null?void 0:re.windowTransform;if(!W||W.function!=="moving_average")return;const X=Math.max(1,Math.floor(V||1)),Z=((fe=W.movingAverage)==null?void 0:fe.minPeriods)||1,J=Math.min(Z,X);o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,movingAverage:{windowSize:X,minPeriods:J}}}})},[g,x,o]),R=v.useCallback(($,V)=>{var J,re;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(J=A.parameters)==null?void 0:J.windowTransform;if(!W||W.function!=="moving_average")return;const X=((re=W.movingAverage)==null?void 0:re.windowSize)||7,Z=Math.max(1,Math.min(Math.floor(V||1),X));o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,movingAverage:{windowSize:X,minPeriods:Z}}}})},[g,x,o]),B=v.useCallback(($,V)=>{var X;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(X=A.parameters)==null?void 0:X.windowTransform;!W||W.function!=="previous_period_delta"||o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,previousPeriodDelta:{mode:V}}}})},[g,x,o]),z=v.useCallback(($,V)=>{var Z;if(!g||!(e!=null&&e.config))return;const A=x("metrics")[$];if(!A)return;const W=(Z=A.parameters)==null?void 0:Z.windowTransform;if(!W||W.function!=="percent_of_total")return;const X=V==="grand_total"?[]:(W.partitionByFieldIds||[]).length>0?W.partitionByFieldIds||[]:vy({cardType:p,cardConfig:e.config,orderByFieldId:void 0});o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,partitionByFieldIds:X,percentOfTotal:{...W.percentOfTotal||{},scope:V}}}})},[e,g,p,x,o]),U=v.useCallback(($,V)=>{var X;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(X=A.parameters)==null?void 0:X.windowTransform;!W||W.function!=="percent_of_total"||o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,percentOfTotal:{...W.percentOfTotal||{},output:V}}}})},[g,x,o]),Y=v.useCallback($=>{g&&r(g,{showTrendline:$})},[g,r]),O=v.useCallback($=>{g&&r(g,{trendlineWindow:$})},[g,r]),K=v.useCallback($=>{g&&r(g,{trendlineGranularity:$})},[g,r]),q=v.useCallback(($,V)=>{if(!g)return;const A=x("metrics")[$];A&&o(g,A.id,{targetValue:V})},[g,x,o]),M=v.useCallback(async $=>{var re;if(!g)return;const V=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy"),...x("detailColumns")],H=$,A=FFe(H,V,{joinPlan:(re=e==null?void 0:e.config)==null?void 0:re.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t,datasetAliases:n==null?void 0:n.datasets});if(!A.isValid){A.showError&&eee();return}const W=qFe(H,V,p);if(!W){ut.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const X=qae(H,W,p);if(!X.isValid){ut.error("Invalid Field Type",{description:X.reason,position:"top-center",duration:3e3});return}const Z=x(W);if(tee(H,Z))return;const J=iee(H,W,Z);if(J){const fe=[...Z,J];if(y(W,fe),W==="metrics"){const de=Kae(e,J,e==null?void 0:e.preferences);de&&h(de),Yae(p,e==null?void 0:e.config,r,g,fe)}}},[g,e,x,y,t,n,p,r,h]),G=v.useCallback(($,V)=>{if(!g)return;const A=x($)[V];if(A){if($!=="sortBy"){const W=x("sortBy"),X=W.filter(Z=>!(Z.name===A.name&&Z.qualifiedEntityName===A.qualifiedEntityName));X.length!==W.length&&r(g,{sortByColumns:X})}switch($){case"groupBy":c(g,A.id);break;case"metrics":u(g,A.id);break;case"pivotBy":d(g,A.id);break;case"sortBy":f(g,A.id);break;case"detailColumns":{r(g,{detailColumns:(x("detailColumns")||[]).filter((W,X)=>X!==V)});break}}}},[g,x,c,u,d,f,r]);return{getFieldsForContainer:x,setFieldsForContainer:y,updateLabel:S,handleAggregationChange:w,handleDateFormatChange:C,handleGranularityChange:N,handleAliasTemplateChange:k,handleValueAliasesChange:_,handleMetricFormatChange:E,removeField:G,handleFieldClick:M,handleMetricComparisonChange:D,handleMetricWindowTransformChange:j,handleMetricWindowOrderByChange:I,handleMetricWindowDirectionChange:T,handleMetricWindowPartitionToggle:F,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:R,handleMetricPreviousPeriodDeltaModeChange:B,handleMetricPercentOfTotalScopeChange:z,handleMetricPercentOfTotalOutputChange:U,handleKpiShowTrendlineChange:Y,handleKpiTrendlineWindowChange:O,handleKpiTrendlineGranularityChange:K,handleMetricTargetValueChange:q,cardType:p}};function Xae(e){var y;const{tokenProps:t}=Ct(),n=m.useDashboardStore(S=>S.authToken)||e,r=m.useEditorStore(S=>S.selectedConnectionId),s=m.useEditorStore(S=>S.selectedDatabaseName),o=m.useEditorStore(S=>S.selectedDatamodelId),i=m.useEditorStore(S=>S.selectedSchemaName),a=m.useEditorStore(S=>S.selectedTableName),{selectedConnection:c}=Xc(),u=c==null?void 0:c.type,{data:d,isLoading:f,isFetching:h,isError:p,refetch:g}=On({queryKey:["columns",r,s,o,i,a],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",{connection_id:r,datamodel_id:o||"",database_name:s,schema_name:i,table_name:a}),enabled:b(u)});function b(S){var _;if(!(n!=null&&n.accessToken))return!1;if(o&&o)return!0;if(!r||!S)return!1;const w=((_=c==null?void 0:c.capabilities)==null?void 0:_.path)||[],C=w.includes("database"),N=w.includes("schema"),k=w.includes("table");return!(C&&(!s||s==="NA")||N&&!i||k&&!a)}return{columns:(y=d==null?void 0:d.columns)==null?void 0:y.map(S=>({...S,data_type:S.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:p,refetchColumns:g}}function iJe(e){const t=m.useDashboardStore(g=>g.selectedLensId),n=m.useDashboardStore(g=>g.dashboard.filters),r=m.useFinalFilterGroupKey(e)||"",{cardFilterValues:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:c,queryRelevantConfig:u}=PO(e),d=c_([e],{authority:"editor",queryRelevantConfigsByCardId:{[e.id]:u}}).payload,f=hv({card:e,cardConfig:u,semanticExecutionPayload:d}),h=(e==null?void 0:e.sql)||"",{queryKey:p}=CP(e,{finalFiltersKey:r,selectedLensId:t,cardFilterValues:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:c,queryRelevantConfig:u,filters:n,resolvedPrimaryDateField:f});return{queryKey:p,sql:h,cardFilterValues:s,controlValues:o}}function Bj(e,t){var ne,je,Ue,Be,rt,Xe,et,tt;const{tokenProps:n}=Ct(),r=ns(),s=Ct().authToken||e,o=m.useEditorStore(me=>me.selectedConnectionId),i=m.useEditorStore(me=>me.card),{queryKey:a}=iJe(i),c=m.useEditorStore(me=>me.selectedDatamodelId),u=m.useEditorStore(me=>me.isDevMode),d=m.useEditorStore(me=>me.selectedDatabaseName),f=m.useEditorStore(me=>me.selectedSchemaName),h=m.useEditorStore(me=>me.selectedTableName),p=m.useEditorStore(me=>me.actions.setSelectedConnectionId),g=m.useEditorStore(me=>me.actions.setSelectedDatamodelId),b=m.useEditorStore(me=>me.actions.setSelectedDatabaseName),x=m.useEditorStore(me=>me.actions.setSelectedSchemaName),y=m.useEditorStore(me=>me.actions.setSelectedTableName);m.useEditorStore(me=>me.actions.setCardSql);const{setQueryConfig:S}=m.useEditorActions();function w(me){var Re;if(!o||!me)return!1;const Ye=((Re=D==null?void 0:D.capabilities)==null?void 0:Re.path)||[],Ve=Ye.includes("database"),$e=Ye.includes("schema");return!(!Ye.includes("table")||Ve&&(!d||d==="NA")||$e&&!f)}function C(me){var Ye;return!o||!me?!1:!!((Ye=D==null?void 0:D.capabilities)!=null&&Ye.path.includes("database"))}const{refetchConnections:N,connectionsData:k,isConnectionsLoading:_,isConnectionsError:E,selectedConnection:D}=Xc(e),{refetch:j,data:I,isLoading:T,isError:F}=On({queryKey:["models",o],queryFn:()=>m.getRequest(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),P=D==null?void 0:D.type,R=((ne=D==null?void 0:D.capabilities)==null?void 0:ne.path.includes("schema"))??!1,B=((je=D==null?void 0:D.capabilities)==null?void 0:je.path.length)===1&&((Ue=D==null?void 0:D.capabilities)==null?void 0:Ue.path[0])==="table",z=B,{data:U,isLoading:Y,isFetching:O,isError:K,refetch:q}=On({queryKey:["databases",o],queryFn:()=>m.getRequest(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:C(P)}),{data:M,isLoading:G,isFetching:L,isError:$,refetch:V}=On({queryKey:["schemas",o,d],queryFn:()=>m.getRequest(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&R&&d!=="NA"}),{data:H,isLoading:A,isFetching:W,isError:X,refetch:Z}=On({queryKey:["tables",o,d,f],queryFn:()=>m.getRequest(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:w(P)}),{columns:J,isColumnsLoading:re,isColumnsFetching:fe,isColumnsError:de,refetchColumns:Se}=Xae(e);v.useEffect(()=>{B&&(b(""),x(""),g(""),P==="API"&&y("api"))},[P,y,b,x,g,B]);const ue=(D==null?void 0:D.type)==="API"?(Be=D==null?void 0:D.type)==null?void 0:Be.toLowerCase():h||"",ve=R&&f||"";function xe(me){y(me),S(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ke(me){x(me),y("")}function se(me){b(me==="none"?"":me),x(""),y(""),me!=="none"&&me!==""&&g("")}function be(me){p(me)}function Ce(me){g(me==="none"?"":me),me!=="none"&&me!==""&&b("")}U&&((rt=U==null?void 0:U.databases)==null?void 0:rt.length)>0,M&&((Xe=M==null?void 0:M.schemas)==null?void 0:Xe.length)>0;const ge=k==null?void 0:k.connections.map(me=>({id:me.id,name:me.name,type:me.type})),ee=(et=I==null?void 0:I.datamodels)==null?void 0:et.map(me=>({id:me.id,name:me.name})),te=U==null?void 0:U.databases.map(me=>({id:me.database_name,name:me.database_name})),ce=M==null?void 0:M.schemas.map(me=>({id:me.schema_name,name:me.schema_name})),le=H==null?void 0:H.tables.map(me=>({id:me.table_name,name:me.table_name})),Ee=(tt=I==null?void 0:I.datamodels.find(me=>me.id===c))==null?void 0:tt.name,ye=D!=null&&D.capabilities?m.getFormattedTableNameForQuery({schemaName:ve,tableName:ue,modelName:Ee,databaseName:d||"",capabilities:D.capabilities}):ue;return{connectionItems:ge,selectedConnectionId:o,selectedConnection:D,isConnectionsLoading:_,isConnectionsError:E,modelItems:ee,selectedDatamodelId:c,selectedDatamodelName:Ee,isModelsLoading:T,isModelsError:F,selectedDatabaseName:d,databaseItems:te,isDatabasesLoadingOrFetching:Y||O,isDatabaseError:K,schemaItems:ce,selectedSchemaName:f,isSchemaLoadingOrFetching:G||L,isSchemaError:$,tableItems:le,selectedTableName:h,isTableLoadingOrFetching:A||W,isTableError:X,columns:J,isColumnsLoadingOrFetching:re||fe,isColumnsError:de,isNonDbConnection:z,connectionType:P,tableName:ue,formattedTableName:ye,schemaName:ve,refetchConnections:N,refetchModels:j,refetchDatabases:q,refetchSchemas:V,refetchTables:Z,refetchColumns:Se,handleConnectionChange:be,handleDatamodelChange:Ce,handleDatabaseChange:se,handleSchemaChange:ke,handleTableChange:xe}}function nS(e){return`${e}-${m.v4()}`}function V7(e,t){const n=m.toTitleCase(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function aJe(e,t){const n=m.toTitleCase(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function t3(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function Qae(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Jae(){const e=m.useEditorStore(_=>_.sqlGen),t=m.useEditorStore(_=>_.isDevMode),n=m.useEditorStore(_=>_.card.dataSource),r=m.useEditorStore(_=>{var E,D;return(D=(E=_.card)==null?void 0:E.queryConfig)==null?void 0:D.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=t3(n),a=Qae(n),c=m.useEditorStore(_=>_.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:g}=m.useEditorActions(),{modelItems:b,selectedDatamodelName:x}=Bj(),{selectedConnection:y}=Xc(),S=y==null?void 0:y.capabilities,w=_=>({column_name:_.name,data_type:_.dataType,label:_.label,description:_.description});return{handleDevModeFieldClick:_=>{var D;if(!t)return;const E=w(_);if(t&&a&&s&&S){const j=m.createSqlGenConfig(E,e);p(j);const I=(D=b==null?void 0:b.find(F=>F.id===c))==null?void 0:D.name,T=m.getSql(j,o||"",s,I||"",i||"",S,_.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(m.isTextDataType(E.data_type))if(r&&r.length>0){const j={...E,role:"groupby",id:nS(E.column_name),name:E.column_name,type:E.data_type};d(j)}else{const j={...E,role:"metric",id:nS(E.column_name),name:E.column_name,label:V7(E.column_name,"COUNT"),type:E.data_type,aggregate:"COUNT"};u(j)}if(m.isDateDataType(E.data_type)){const j={...E,role:"groupby",id:nS(E.column_name),name:E.column_name,type:E.data_type,label:aJe(E.column_name,"month"),granularity:"month"};d(j)}if(m.isNumberDataType(E.data_type)){const j={...E,role:"metric",id:nS(E.column_name),name:E.column_name,label:V7(E.column_name,"SUM"),type:E.data_type,aggregate:"SUM"};u(j)}}},handleShowSample:()=>{if(!a||!s||!S){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=m.getFormattedTableNameForQuery({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:S});g(!1);const D=(y==null?void 0:y.type)==="MSSQL"?`SELECT top 10 * FROM ${_}`:`SELECT * FROM ${_} LIMIT 10`;f(D),h(!0)},handleShowCount:()=>{if(!a||!s||!S){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=m.getFormattedTableNameForQuery({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:S});f(`SELECT COUNT(*) as count FROM ${_}`),h(!0)},isNumberField:_=>m.isNumberDataType(_.dataType)}}function ele(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>m.fmt(o)).join("."),s=m.fmt(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function n3(e){const t=e;return{id:e.id,name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,fieldScope:e.fieldScope,expression:t.expression,calculatedFormula:t.calculatedFormula}}function r3(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function E0(e){var t,n;return e?!!(e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function H7(e){return e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e}function ug(e,t){var b,x,y,S,w,C,N;if(!e.fieldMeta)return e.column===t.qualifiedFieldName||e.column===t.name;const n=H7((b=e.fieldMeta)==null?void 0:b.id),r=H7(t.id),s=((x=e.fieldMeta)==null?void 0:x.qualifiedFieldName)||e.column,o=s===t.qualifiedFieldName||s===t.name,i=(y=e.fieldMeta)==null?void 0:y.qualifiedEntityName,a=!i||!t.qualifiedEntityName||i===t.qualifiedEntityName,c=(S=e.fieldMeta)==null?void 0:S.entityId,u=!c||!t.entityId||c===t.entityId,d=(w=e.fieldMeta)==null?void 0:w.fieldScope;if(d&&t.fieldScope&&d!==t.fieldScope)return!1;const f=(C=e.fieldMeta)==null?void 0:C.role;if(f&&t.role&&f!==t.role)return!1;const h=E0(e.fieldMeta)||E0(t);if(h&&n&&r&&n===r)return!0;if(!h&&(!a||!u))return!1;const p=(N=e.fieldMeta)==null?void 0:N.expression,g=t.expression;return p||g?o&&a&&u&&p===g:o&&a&&u}function lJe(){const e=m.useDashboardStore(c=>c.dashboard.filters)||[],t=m.useDashboardStore(c=>c.selectedSheetId),n=m.useDashboardStore(c=>c.actions.addFilter),r=m.useDashboardStore(c=>c.actions.removeFilter),{removeFilterValues:s}=m.useDashboardActions(),o=m.useEditorStore(c=>c.card.dataSource),{selectedConnection:i}=Xc();function a(c,u="sheet"){var g;const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=ele(c);let p;if(u==="sheet"&&t){const b=Nd(e,t);p=b.find(x=>x.fieldMeta&&ug(x,c))||xke(b.filter(x=>!x.fieldMeta),d,f,t)}else p=e==null?void 0:e.find(b=>ug(b,c)||!b.fieldMeta&&Vm(b.column)===Vm(d));if(p)s(p.id),r(p.id);else{const b=m.v4(),x=n3(c),y=r3(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),S=E0(x),w=!!((o==null?void 0:o.mode)==="semanticDomain"&&((g=y==null?void 0:y.selectedEntities)!=null&&g.length||y!=null&&y.semanticDomainId)),C=u==="sheet"&&t?[t]:void 0,N=m.getDataType(c.dataType)==="date"?"between":"in";return n({id:b,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:N,applyToSheetIds:C,sql:S||w?"":tL(c.dataType,f,h),fieldMeta:x,semanticContext:y}),b}}return{assignFilter:a}}function cJe({column:e}){const[t,n]=v.useState(!1),r=m.useEditorStore(w=>w.isDevMode),s=m.useEditorStore(w=>w.card.dataSource),{tableName:o,schemaName:i,databaseName:a}=t3(s),c=m.useEditorStore(w=>w.selectedDatamodelId),u=m.useEditorStore(w=>w.sqlGen),{modelItems:d,selectedConnection:f}=Bj(),h=f==null?void 0:f.capabilities,p=m.useEditorStore(w=>w.actions.setSqlGen),g=m.useEditorStore(w=>w.actions.setCardSql),b=m.useEditorStore(w=>w.actions.setRunSql),x=Qae(s);function y(w,C){var D,j;if(!x||!o){console.warn("Cannot generate SQL: missing table metadata");return}const N=m.createSqlGenConfig(w,u,C),k=(D=d==null?void 0:d.find(I=>I.id===c))==null?void 0:D.name;if(p(N),!h){console.warn("Cannot generate SQL: missing connection capabilities");return}const _=(j=w.qualifiedFieldName)==null?void 0:j.split(".").slice(0,-1).join("."),E=m.getSql(N,i||"",o,k||"",a||"",h,_);E&&(g(E),b(!0)),n(!1)}function S(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>y(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>y(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>y(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>y(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>y(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return!r||!x?null:l.jsxs(Pg,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Og,{asChild:!0,children:l.jsx(Lh,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(cd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:S()})]})}const U7="bg-emerald-500/90 text-white",uJe="bg-blue-500/90 text-white";function s3(e){const t=bd(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:U7}:{label:"fx",badgeClassName:e.role==="metric"?U7:uJe}}function dJe(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),e.prefix&&t.push({label:"Prefix",value:e.prefix}),e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const s=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:s})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function fJe(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,s)=>{const o=t[Number(s)];return o?`{${o.name||o.label}}`:r}):e.expression}function hJe({field:e,fieldState:t}){const n=fJe(e),r=dJe(e.format),s=!!s3(e);return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-start gap-1.5 px-3 pt-2.5",children:[l.jsx("span",{className:"flex h-[18px] shrink-0 items-center",children:l.jsx(Qv,{dataType:e.dataType,calculated:s})}),l.jsx("p",{className:"min-w-0 flex-1 break-words text-[13px] font-semibold leading-[18px] text-foreground",children:e.label||e.name})]}),l.jsx("div",{className:"px-3 pb-2 pt-0.5",children:l.jsx("code",{className:"font-mono text-[11px] text-muted-foreground",children:e.dataType})}),e.description&&l.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[12px] leading-[1.55] text-muted-foreground",children:e.description}),n&&l.jsxs("div",{className:"border-t border-border/60 bg-muted/40 px-3 py-2",children:[l.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Expression"}),l.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-[11px] leading-[1.55] text-foreground/90",children:n})]}),r.length>0&&l.jsxs("div",{className:"border-t border-border/60 px-3 py-2",children:[l.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Format"}),l.jsx("dl",{className:"grid grid-cols-[64px_1fr] gap-x-3 gap-y-1 text-[11px]",children:r.map(o=>l.jsxs("div",{className:"contents",children:[l.jsx("dt",{className:"font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o.label}),l.jsx("dd",{className:"truncate font-mono tabular-nums text-foreground/90",children:o.value})]},`${o.label}-${o.value}`))})]}),t&&t.tooltip&&l.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[11px] text-muted-foreground",children:t.tooltip}),l.jsx("div",{className:"border-t border-border/60 px-3 py-2",children:l.jsx("code",{className:"block break-all font-mono text-[11px] leading-[1.45] text-muted-foreground",children:e.name})})]})}function W7({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o,onHover:i}){const a=m.useEditorStore(W=>W.isDevMode),c=t==="inline-filter"||t==="document-filter",u=t==="filter"||c,d=a||u||(n==null?void 0:n.state)==="unreachable"&&!u,f=m.useDashboardStore(W=>W.dashboard.filters),h=m.useDashboardStore(W=>W.selectedSheetId),p=m.useDashboardStore(W=>W.actions.removeFilter),{removeFilterValues:g}=m.useDashboardActions(),{assignFilter:b}=lJe(),x=t==="filter"?Nd(f,h):f,y=t==="filter"?x==null?void 0:x.find(W=>{if(ug(W,e))return!0;if(W.fieldMeta)return!1;const X=Vm(W.column||""),Z=Vm(e.name);return X.endsWith(`.${Z}`)||X===Z}):void 0,S=!!y,w=c&&(s==null?void 0:s.some(W=>ug(W,e))),C=S||w,N=y&&u?f==null?void 0:f.find(W=>W.id===y.id):void 0,k=N&&(N.applyToSheetIds&&N.applyToSheetIds.length>1||N.excludeSheetIds&&N.excludeSheetIds.length>0||!N.applyToSheetIds&&!N.excludeSheetIds&&!N.sheetId),[_,E]=v.useState(!1),[,D]=v.useState(null),{attributes:j,listeners:I,setNodeRef:T,transform:F,transition:P,isDragging:R}=db({id:e.id,disabled:d}),B=m.useEditorStore(W=>W.card),{handleFieldClick:z}=Zae(B),{handleDevModeFieldClick:U,isNumberField:Y}=Jae(),O=()=>{N&&(console.log("[SourceField] Removing multi-sheet filter:",N.id),g(N.id),p(N.id)),D(null),E(!1)},K=()=>{if(c&&r){r(e);return}t==="filter"?C&&k?(D(e),E(!0)):b(e,"sheet"):a?U(e):z(e)},q={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},M={transform:_i.Transform.toString(F),transition:P};function G(W){return W==="domain"?{label:"Semantic domain",Icon:kme}:W==="sheet"?{label:"Sheet",Icon:Rm}:W==="dashboard"?{label:"Dashboard",Icon:Rm}:{label:"Card",Icon:Eq}}const L=s3(e),$=e.fieldScope,V=$&&!L?G($):null,H=(n==null?void 0:n.state)==="unreachable",A=(n==null?void 0:n.state)==="indirect";return l.jsxs(l.Fragment,{children:[l.jsx(Wae,{ref:T,style:M,...d?{}:j,...d?{}:I,onClick:K,onMouseEnter:W=>i==null?void 0:i(!0,W.currentTarget),onMouseLeave:()=>i==null?void 0:i(!1),title:n==null?void 0:n.tooltip,selected:S,dragging:R,disableHover:H,inQuery:!u&&!!(n!=null&&n.isSelected),icon:l.jsx(Qv,{dataType:e.dataType,calculated:!!L}),label:e.label||e.name,trailing:l.jsxs(l.Fragment,{children:[a&&!u&&Y(e)&&l.jsx("span",{onClick:W=>W.stopPropagation(),onPointerDown:W=>W.stopPropagation(),children:l.jsx(cJe,{column:q})}),o?l.jsx("span",{className:"pointer-events-none inline-flex items-center opacity-0 transition-opacity group-hover/field-row:pointer-events-auto group-hover/field-row:opacity-100 group-focus-within/field-row:pointer-events-auto group-focus-within/field-row:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",onClick:W=>W.stopPropagation(),onPointerDown:W=>W.stopPropagation(),children:o}):t==="editor"?l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Field actions",onClick:W=>W.stopPropagation(),onPointerDown:W=>W.stopPropagation(),className:"pointer-events-none inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:pointer-events-auto group-hover/field-row:opacity-100 group-focus-within/field-row:pointer-events-auto group-focus-within/field-row:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",children:l.jsx(ja,{className:"h-3 w-3"})})}),l.jsx(fo,{align:"end",className:"w-44",children:l.jsx(jn,{onClick:W=>{W.stopPropagation(),navigator.clipboard.writeText(e.name).then(()=>{ut.success(`Copied "${e.name}"`)}).catch(()=>{ut.error("Could not copy field name")})},children:"Copy field name"})})]}):null,t==="editor"&&V&&l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx("span",{"aria-label":`${V.label} calculated field`,className:"inline-flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",onClick:W=>W.stopPropagation(),onPointerDown:W=>W.stopPropagation(),children:l.jsx(V.Icon,{className:"h-3 w-3"})})}),l.jsxs(m.TooltipContent,{side:"top",align:"end",children:[V.label," calculated field"]})]})]}),className:m.cn((a||u)&&"cursor-pointer",!d&&!a&&!u&&"cursor-grab active:cursor-grabbing",H&&"cursor-not-allowed opacity-50",A&&"text-muted-foreground/80",w&&"bg-primary/10 hover:bg-primary/15")}),l.jsx(Lc,{open:_,onOpenChange:E,children:l.jsxs(vl,{children:[l.jsxs(wl,{children:[l.jsx(Cl,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Nl,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Sl,{children:[l.jsx(_l,{children:"Cancel"}),l.jsx(kl,{onClick:O,children:"Remove Filter"})]})]})})]})}var za="Accordion",pJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[o3,mJe,gJe]=m.createCollection(za),[Vj]=m.createContextScope(za,[gJe,mie]),i3=mie(),tle=v.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return l.jsx(o3.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?l.jsx(vJe,{...o,ref:t}):l.jsx(yJe,{...s,ref:t})})});tle.displayName=za;var[nle,bJe]=Vj(za),[rle,xJe]=Vj(za,{collapsible:!1}),yJe=v.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,c]=m.useControllableState({prop:n,defaultProp:r??"",onChange:s,caller:za});return l.jsx(nle,{scope:e.__scopeAccordion,value:v.useMemo(()=>a?[a]:[],[a]),onItemOpen:c,onItemClose:v.useCallback(()=>o&&c(""),[o,c]),children:l.jsx(rle,{scope:e.__scopeAccordion,collapsible:o,children:l.jsx(sle,{...i,ref:t})})})}),vJe=v.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=m.useControllableState({prop:n,defaultProp:r??[],onChange:s,caller:za}),c=v.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=v.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return l.jsx(nle,{scope:e.__scopeAccordion,value:i,onItemOpen:c,onItemClose:u,children:l.jsx(rle,{scope:e.__scopeAccordion,collapsible:!0,children:l.jsx(sle,{...o,ref:t})})})}),[wJe,Hj]=Vj(za),sle=v.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=v.useRef(null),c=m.useComposedRefs(a,t),u=mJe(n),f=m.useDirection(s)==="ltr",h=m.composeEventHandlers(e.onKeyDown,p=>{var E;if(!pJe.includes(p.key))return;const g=p.target,b=u().filter(D=>{var j;return!((j=D.ref.current)!=null&&j.disabled)}),x=b.findIndex(D=>D.ref.current===g),y=b.length;if(x===-1)return;p.preventDefault();let S=x;const w=0,C=y-1,N=()=>{S=x+1,S>C&&(S=w)},k=()=>{S=x-1,S<w&&(S=C)};switch(p.key){case"Home":S=w;break;case"End":S=C;break;case"ArrowRight":o==="horizontal"&&(f?N():k());break;case"ArrowDown":o==="vertical"&&N();break;case"ArrowLeft":o==="horizontal"&&(f?k():N());break;case"ArrowUp":o==="vertical"&&k();break}const _=S%y;(E=b[_].ref.current)==null||E.focus()});return l.jsx(wJe,{scope:n,disabled:r,direction:s,orientation:o,children:l.jsx(o3.Slot,{scope:n,children:l.jsx(m.Primitive.div,{...i,"data-orientation":o,ref:c,onKeyDown:r?void 0:h})})})}),JN="AccordionItem",[SJe,a3]=Vj(JN),ole=v.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=Hj(JN,n),i=bJe(JN,n),a=i3(n),c=m.useId(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return l.jsx(SJe,{scope:n,open:u,disabled:d,triggerId:c,children:l.jsx(xie,{"data-orientation":o.orientation,"data-state":dle(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});ole.displayName=JN;var ile="AccordionHeader",ale=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Hj(za,n),o=a3(ile,n);return l.jsx(m.Primitive.h3,{"data-orientation":s.orientation,"data-state":dle(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});ale.displayName=ile;var xR="AccordionTrigger",lle=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Hj(za,n),o=a3(xR,n),i=xJe(xR,n),a=i3(n);return l.jsx(o3.ItemSlot,{scope:n,children:l.jsx(PYe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});lle.displayName=xR;var cle="AccordionContent",ule=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Hj(za,n),o=a3(cle,n),i=i3(n);return l.jsx(OYe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});ule.displayName=cle;function dle(e){return e?"open":"closed"}var CJe=tle,NJe=ole,kJe=ale,fle=lle,hle=ule;const l3=CJe,D0=Q.forwardRef(({className:e,...t},n)=>l.jsx(NJe,{ref:n,className:m.cn("border-b",e),...t}));D0.displayName="AccordionItem";const I0=Q.forwardRef(({className:e,children:t,...n},r)=>l.jsx(kJe,{className:"flex",children:l.jsxs(fle,{ref:r,className:m.cn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,l.jsx(m.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));I0.displayName=fle.displayName;const T0=Q.forwardRef(({className:e,children:t,...n},r)=>l.jsx(hle,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:l.jsx("div",{className:m.cn("pb-4 pt-0",e),children:t})}));T0.displayName=hle.displayName;let ple=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const Uj=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",insertTemplate:()=>"({a} + {b})",insertHint:"A + B",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",insertTemplate:()=>"({a} - {b})",insertHint:"A − B",requiresTwoInputs:!0},{id:"product",label:"Product",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",insertTemplate:()=>"({a} * {b})",insertHint:"A × B",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",insertTemplate:()=>"({a} / NULLIF({b}, 0))",insertHint:"A ÷ B (null-safe)",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",insertTemplate:()=>"(({b} - {a}) / NULLIF({a}, 0))",insertHint:"% change A → B",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",insertTemplate:()=>"(({a} / NULLIF({b}, 0)) * 100)",insertHint:"(A ÷ B) × 100",requiresTwoInputs:!0},{id:"scale",label:"Scale",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",insertTemplate:()=>"({a} * 1.0)",insertHint:"A × constant",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],_Je=Uj.filter(e=>e.id!=="custom"&&!!e.insertTemplate),c3=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),ek=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function mle(e,t){e.forEach(n=>{var i;const r=n.id||n.qualifiedFieldName||n.name;if(r&&t.visited.has(r))return;if(r&&t.visited.add(r),zae(n)){t.disqualified=!0;return}const s=(i=n.calculatedFormula)==null?void 0:i.inputFields;if(s!=null&&s.length){mle(s,t);return}if(n.expression&&!(bd(n)==="inline_expression"&&ka(n)&&n.fieldScope==="domain")){t.disqualified=!0;return}if(!n.entityName||!n.entityId){t.disqualified=!0;return}const o=n.qualifiedEntityName||n.entityId||n.entityName;t.entities.has(o)||t.entities.set(o,{entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName})})}function u3(e){const t={entities:new Map,disqualified:!1,visited:new Set};if(mle(e,t),t.disqualified||t.entities.size!==1)return{kind:"multi-entity"};const[n]=Array.from(t.entities.values());return!(n!=null&&n.entityName)||!n.entityId?{kind:"multi-entity"}:{kind:"inline",entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName}}const q7="calculated_fields";function jJe(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function EJe(e){return e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===q7||e.qualifiedEntityName===q7||jJe(e.id)}function DJe(e){return e.aggregate?e.aggregate:AO(e.dataType)}function IJe(e,t){const n=DJe(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function TJe(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const s=Number(r),o=t[s];return!o||EJe(o)||typeof o.expression=="string"&&nee(o.expression)?n:IJe(n,o)})}function MJe(e,t,n,r,s,o,i,a,c,u){if(!Uj.find(S=>S.id===t))throw new Error(`Unknown operation: ${t}`);let f,h=[],p;{if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}const g={operation:t,inputFields:h,...p!==void 0},b=c3(e),x=u3(h);return{id:i||`calc_${ple(10)}`,name:b,label:e,alias:b,qualifiedFieldName:b,dataType:"number",role:"metric",expression:f,calculatedFormula:g,entityId:x.kind==="inline"?x.entityId:o,entityName:x.kind==="inline"?x.entityName:Cr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:x.kind==="inline"?x.qualifiedEntityName:void 0,entityType:x.kind==="inline"?"dataset":"table",description:`Calculated field: ${e}`}}function AJe(e){var r,s;const t=Uj.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function RJe(e,t,n,r,s,o){const i=c3(e),a=u3(n);return ree({id:o||`calc_dim_${ple(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(c=>c.role==="metric"?{...c,role:"metric"}:{...c,role:"groupby"})},entityId:a.kind==="inline"?a.entityId:s,entityName:a.kind==="inline"?a.entityName:Cr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:a.kind==="inline"?a.qualifiedEntityName:void 0,entityType:a.kind==="inline"?"dataset":"table",description:`Calculated field: ${e.trim()}`})}function gle(e){return e==="metric"?"Calculated Metric":"Calculated Column"}function FJe(e){return e==="inline"?"Single dataset":"Cross-entity"}function $x(e){switch(e){case"card":return"This card";case"sheet":return"This sheet";case"dashboard":return"This dashboard";case"domain":return"Semantic domain"}}function Y7(e){return e.replace(/\s+/g,"")}function PJe(e){var s;const t=e.calculatedFormula;if(!t||t.operation==="custom")return;const n=Uj.find(o=>o.id===t.operation),r=(s=n==null?void 0:n.template)==null?void 0:s.call(n);if(r)return t.operation!=="scale"?r:r.replace("{constant}",String(t.constant??1))}function OJe(e){var r;const t=e.expression||"",n=PJe(e);return!n||Y7(t)!==Y7(n)?t:TJe(t,((r=e.calculatedFormula)==null?void 0:r.inputFields)||[])}function LJe(e){const t=new Set,n=/\{field_(\d+)\}/g;let r=n.exec(e);for(;r;)t.add(Number(r[1])),r=n.exec(e);return[...t].sort((s,o)=>s-o)}function $Je(e){var o;const t=e.expression||"",n=LJe(t);if(n.length===0)return{readOnly:!1};const r=((o=e.calculatedFormula)==null?void 0:o.inputFields)||[];return n[n.length-1]<r.length?{readOnly:!1}:{readOnly:!0,reason:"This legacy metric uses saved field tokens but is missing the input metadata needed to reopen it safely. It can be viewed, but editing is disabled to avoid changing query semantics."}}function zJe(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function BJe(e){var r;const t=new Map;return(((r=e==null?void 0:e.calculatedFormula)==null?void 0:r.inputFields)||[]).forEach(s=>{const o=ek(s.id);o&&t.set(o,s),s.qualifiedFieldName&&t.set(s.qualifiedFieldName,s),s.name&&t.set(s.name,s)}),t}function VJe(e,t){const n=ek(e.id);return n&&t.get(n)||e.qualifiedFieldName&&t.get(e.qualifiedFieldName)||t.get(e.name)}function HJe(e){const t=AO(e.dataType);if(e.role==="metric"){const n=e;return n.aggregate||n.expression||n.calculatedFormula?n:{...n,aggregate:t}}return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}}function UJe(e,t){const n=BJe(t);return e.map(r=>{const s=VJe(r,n);return(s==null?void 0:s.role)==="metric"?s:HJe(r)})}function WJe({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:s,targetQualifiedEntityName:o}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=bd(i);if(r==="inline"){const c=m.getCalculatedFieldNamespace(i),u=o||s;return a==="inline_expression"&&!!u&&c===u}return a==="domain_calculated"})}function qJe({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(c=>s.includes(c)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return l.jsx(m.Tabs,{value:a,onValueChange:c=>t(c),className:"w-fit shrink-0",children:l.jsx(m.TabsList,{size:"xs",children:o.map(c=>l.jsx(m.TabsTrigger,{value:c,disabled:i,children:gle(c)},c))})})}const d3=Q.forwardRef(({className:e,sideOffset:t=8,...n},r)=>l.jsx(m.Portal$2,{children:l.jsx(sb,{children:l.jsx(m.Content2$1,{ref:r,sideOffset:t,className:m.cn("z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})})}));d3.displayName="ValidationTooltipContent";const ble=m.Arrow2$1;function _T(e,t){return`${e} ${t}${e===1?"":"s"}`}function YJe({result:e}){const t=e.errors.length>0,n=_T(e.tokens.length,"token"),r=e.errors.length>0?_T(e.errors.length,"error"):null,s=e.warnings.length>0?_T(e.warnings.length,"warning"):null,o=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
1300
+ `},iZe={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function aZe(e){let{announcements:t=iZe,container:n,hiddenTextDescribedById:r,screenReaderInstructions:s=oZe}=e;const{announce:o,announcement:i}=nZe(),a=tw("DndLiveRegion"),[c,u]=v.useState(!1);if(v.useEffect(()=>{u(!0)},[]),rZe(v.useMemo(()=>({onDragStart(f){let{active:h}=f;o(t.onDragStart({active:h}))},onDragMove(f){let{active:h,over:p}=f;t.onDragMove&&o(t.onDragMove({active:h,over:p}))},onDragOver(f){let{active:h,over:p}=f;o(t.onDragOver({active:h,over:p}))},onDragEnd(f){let{active:h,over:p}=f;o(t.onDragEnd({active:h,over:p}))},onDragCancel(f){let{active:h,over:p}=f;o(t.onDragCancel({active:h,over:p}))}}),[o,t])),!c)return null;const d=v.createElement(v.Fragment,null,v.createElement(eZe,{id:r,value:s.draggable}),v.createElement(tZe,{id:a,announcement:i}));return n?Sr.createPortal(d,n):d}var ps;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(ps||(ps={}));function KN(){}function cg(e,t){return v.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function Tj(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return v.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const Fa=Object.freeze({x:0,y:0});function oae(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function lZe(e,t){const n=GN(e);if(!n)return"0 0";const r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+"% "+r.y+"%"}function iae(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function cZe(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function k7(e){let{left:t,top:n,height:r,width:s}=e;return[{x:t,y:n},{x:t+s,y:n},{x:t,y:n+r},{x:t+s,y:n+r}]}function aae(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function _7(e,t,n){return t===void 0&&(t=e.left),n===void 0&&(n=e.top),{x:t+e.width*.5,y:n+e.height*.5}}const nw=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=_7(t,t.left,t.top),o=[];for(const i of r){const{id:a}=i,c=n.get(a);if(c){const u=oae(_7(c),s);o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort(iae)},uZe=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=k7(t),o=[];for(const i of r){const{id:a}=i,c=n.get(a);if(c){const u=k7(c),d=s.reduce((h,p,g)=>h+oae(u[g],p),0),f=Number((d/4).toFixed(4));o.push({id:a,data:{droppableContainer:i,value:f}})}}return o.sort(iae)};function dZe(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),s=Math.min(t.left+t.width,e.left+e.width),o=Math.min(t.top+t.height,e.top+e.height),i=s-r,a=o-n;if(r<s&&n<o){const c=t.width*t.height,u=e.width*e.height,d=i*a,f=d/(c+u-d);return Number(f.toFixed(4))}return 0}const fZe=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=[];for(const o of r){const{id:i}=o,a=n.get(i);if(a){const c=dZe(a,t);c>0&&s.push({id:i,data:{droppableContainer:o,value:c}})}}return s.sort(cZe)};function hZe(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function lae(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Fa}function pZe(e){return function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s.reduce((i,a)=>({...i,top:i.top+e*a.y,bottom:i.bottom+e*a.y,left:i.left+e*a.x,right:i.right+e*a.x}),{...n})}}const mZe=pZe(1);function cae(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function gZe(e,t,n){const r=cae(t);if(!r)return e;const{scaleX:s,scaleY:o,x:i,y:a}=r,c=e.left-i-(1-s)*parseFloat(n),u=e.top-a-(1-o)*parseFloat(n.slice(n.indexOf(" ")+1)),d=s?e.width/s:e.width,f=o?e.height/o:e.height;return{width:d,height:f,top:u,right:c+d,bottom:u+f,left:c}}const bZe={ignoreTransform:!1};function lb(e,t){t===void 0&&(t=bZe);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:d}=Lo(e).getComputedStyle(e);u&&(n=gZe(n,u,d))}const{top:r,left:s,width:o,height:i,bottom:a,right:c}=n;return{top:r,left:s,width:o,height:i,bottom:a,right:c}}function j7(e){return lb(e,{ignoreTransform:!0})}function xZe(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function yZe(e,t){return t===void 0&&(t=Lo(e).getComputedStyle(e)),t.position==="fixed"}function vZe(e,t){t===void 0&&(t=Lo(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(s=>{const o=t[s];return typeof o=="string"?n.test(o):!1})}function Mj(e,t){const n=[];function r(s){if(t!=null&&n.length>=t||!s)return n;if(VL(s)&&s.scrollingElement!=null&&!n.includes(s.scrollingElement))return n.push(s.scrollingElement),n;if(!Jv(s)||nae(s)||n.includes(s))return n;const o=Lo(e).getComputedStyle(s);return s!==e&&vZe(s,o)&&n.push(s),yZe(s,o)?n:r(s.parentNode)}return e?r(e):n}function uae(e){const[t]=Mj(e,1);return t??null}function gT(e){return!Ej||!e?null:ib(e)?e:BL(e)?VL(e)||e===ab(e).scrollingElement?window:Jv(e)?e:null:null}function dae(e){return ib(e)?e.scrollX:e.scrollLeft}function fae(e){return ib(e)?e.scrollY:e.scrollTop}function fR(e){return{x:dae(e),y:fae(e)}}var ws;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(ws||(ws={}));function hae(e){return!Ej||!e?!1:e===document.scrollingElement}function pae(e){const t={x:0,y:0},n=hae(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},s=e.scrollTop<=t.y,o=e.scrollLeft<=t.x,i=e.scrollTop>=r.y,a=e.scrollLeft>=r.x;return{isTop:s,isLeft:o,isBottom:i,isRight:a,maxScroll:r,minScroll:t}}const wZe={x:.2,y:.2};function SZe(e,t,n,r,s){let{top:o,left:i,right:a,bottom:c}=n;r===void 0&&(r=10),s===void 0&&(s=wZe);const{isTop:u,isBottom:d,isLeft:f,isRight:h}=pae(e),p={x:0,y:0},g={x:0,y:0},b={height:t.height*s.y,width:t.width*s.x};return!u&&o<=t.top+b.height?(p.y=ws.Backward,g.y=r*Math.abs((t.top+b.height-o)/b.height)):!d&&c>=t.bottom-b.height&&(p.y=ws.Forward,g.y=r*Math.abs((t.bottom-b.height-c)/b.height)),!h&&a>=t.right-b.width?(p.x=ws.Forward,g.x=r*Math.abs((t.right-b.width-a)/b.width)):!f&&i<=t.left+b.width&&(p.x=ws.Backward,g.x=r*Math.abs((t.left+b.width-i)/b.width)),{direction:p,speed:g}}function CZe(e){if(e===document.scrollingElement){const{innerWidth:o,innerHeight:i}=window;return{top:0,left:0,right:o,bottom:i,width:o,height:i}}const{top:t,left:n,right:r,bottom:s}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:s,width:e.clientWidth,height:e.clientHeight}}function mae(e){return e.reduce((t,n)=>mm(t,fR(n)),Fa)}function NZe(e){return e.reduce((t,n)=>t+dae(n),0)}function kZe(e){return e.reduce((t,n)=>t+fae(n),0)}function gae(e,t){if(t===void 0&&(t=lb),!e)return;const{top:n,left:r,bottom:s,right:o}=t(e);uae(e)&&(s<=0||o<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const _Ze=[["x",["left","right"],NZe],["y",["top","bottom"],kZe]];class HL{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=Mj(n),s=mae(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,i,a]of _Ze)for(const c of i)Object.defineProperty(this,c,{get:()=>{const u=a(r),d=s[o]-u;return this.rect[c]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class by{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var s;(s=this.target)==null||s.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function jZe(e){const{EventTarget:t}=Lo(e);return e instanceof t?e:ab(e)}function bT(e,t){const n=Math.abs(e.x),r=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var Li;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Li||(Li={}));function E7(e){e.preventDefault()}function EZe(e){e.stopPropagation()}var In;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(In||(In={}));const bae={start:[In.Space,In.Enter],cancel:[In.Esc],end:[In.Space,In.Enter,In.Tab]},DZe=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case In.Right:return{...n,x:n.x+25};case In.Left:return{...n,x:n.x-25};case In.Down:return{...n,y:n.y+25};case In.Up:return{...n,y:n.y-25}}};class rw{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new by(ab(n)),this.windowListeners=new by(Lo(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Li.Resize,this.handleCancel),this.windowListeners.add(Li.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Li.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&gae(r),n(Fa)}handleKeyDown(t){if(Ij(t)){const{active:n,context:r,options:s}=this.props,{keyboardCodes:o=bae,coordinateGetter:i=DZe,scrollBehavior:a="smooth"}=s,{code:c}=t;if(o.end.includes(c)){this.handleEnd(t);return}if(o.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:Fa;this.referenceCoordinates||(this.referenceCoordinates=d);const f=i(t,{active:n,context:r.current,currentCoordinates:d});if(f){const h=k0(f,d),p={x:0,y:0},{scrollableAncestors:g}=r.current;for(const b of g){const x=t.code,{isTop:y,isRight:S,isLeft:w,isBottom:C,maxScroll:N,minScroll:k}=pae(b),_=CZe(b),E={x:Math.min(x===In.Right?_.right-_.width/2:_.right,Math.max(x===In.Right?_.left:_.left+_.width/2,f.x)),y:Math.min(x===In.Down?_.bottom-_.height/2:_.bottom,Math.max(x===In.Down?_.top:_.top+_.height/2,f.y))},D=x===In.Right&&!S||x===In.Left&&!w,j=x===In.Down&&!C||x===In.Up&&!y;if(D&&E.x!==f.x){const I=b.scrollLeft+h.x,T=x===In.Right&&I<=N.x||x===In.Left&&I>=k.x;if(T&&!h.y){b.scrollTo({left:I,behavior:a});return}T?p.x=b.scrollLeft-I:p.x=x===In.Right?b.scrollLeft-N.x:b.scrollLeft-k.x,p.x&&b.scrollBy({left:-p.x,behavior:a});break}else if(j&&E.y!==f.y){const I=b.scrollTop+h.y,T=x===In.Down&&I<=N.y||x===In.Up&&I>=k.y;if(T&&!h.x){b.scrollTo({top:I,behavior:a});return}T?p.y=b.scrollTop-I:p.y=x===In.Down?b.scrollTop-N.y:b.scrollTop-k.y,p.y&&b.scrollBy({top:-p.y,behavior:a});break}}this.handleMove(t,mm(k0(f,this.referenceCoordinates),p))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}rw.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=bae,onActivation:s}=t,{active:o}=n;const{code:i}=e.nativeEvent;if(r.start.includes(i)){const a=o.activatorNode.current;return a&&e.target!==a?!1:(e.preventDefault(),s==null||s({event:e.nativeEvent}),!0)}return!1}}];function D7(e){return!!(e&&"distance"in e)}function I7(e){return!!(e&&"delay"in e)}class UL{constructor(t,n,r){var s;r===void 0&&(r=jZe(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:o}=t,{target:i}=o;this.props=t,this.events=n,this.document=ab(i),this.documentListeners=new by(this.document),this.listeners=new by(r),this.windowListeners=new by(Lo(i)),this.initialCoordinates=(s=GN(o))!=null?s:Fa,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(Li.Resize,this.handleCancel),this.windowListeners.add(Li.DragStart,E7),this.windowListeners.add(Li.VisibilityChange,this.handleCancel),this.windowListeners.add(Li.ContextMenu,E7),this.documentListeners.add(Li.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(I7(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(D7(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:s}=this.props;s(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(Li.Click,EZe,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Li.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:s,props:o}=this,{onMove:i,options:{activationConstraint:a}}=o;if(!s)return;const c=(n=GN(t))!=null?n:Fa,u=k0(s,c);if(!r&&a){if(D7(a)){if(a.tolerance!=null&&bT(u,a.tolerance))return this.handleCancel();if(bT(u,a.distance))return this.handleStart()}if(I7(a)&&bT(u,a.tolerance))return this.handleCancel();this.handlePending(a,u);return}t.cancelable&&t.preventDefault(),i(c)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===In.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const IZe={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class cb extends UL{constructor(t){const{event:n}=t,r=ab(n.target);super(t,IZe,r)}}cb.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const TZe={move:{name:"mousemove"},end:{name:"mouseup"}};var hR;(function(e){e[e.RightClick=2]="RightClick"})(hR||(hR={}));class MZe extends UL{constructor(t){super(t,TZe,ab(t.event.target))}}MZe.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===hR.RightClick?!1:(r==null||r({event:n}),!0)}}];const xT={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class AZe extends UL{constructor(t){super(t,xT)}static setup(){return window.addEventListener(xT.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(xT.move.name,t)};function t(){}}}AZe.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:s}=n;return s.length>1?!1:(r==null||r({event:n}),!0)}}];var xy;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(xy||(xy={}));var ZN;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(ZN||(ZN={}));function RZe(e){let{acceleration:t,activator:n=xy.Pointer,canScroll:r,draggingRect:s,enabled:o,interval:i=5,order:a=ZN.TreeOrder,pointerCoordinates:c,scrollableAncestors:u,scrollableAncestorRects:d,delta:f,threshold:h}=e;const p=PZe({delta:f,disabled:!o}),[g,b]=KKe(),x=v.useRef({x:0,y:0}),y=v.useRef({x:0,y:0}),S=v.useMemo(()=>{switch(n){case xy.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case xy.DraggableRect:return s}},[n,s,c]),w=v.useRef(null),C=v.useCallback(()=>{const k=w.current;if(!k)return;const _=x.current.x*y.current.x,E=x.current.y*y.current.y;k.scrollBy(_,E)},[]),N=v.useMemo(()=>a===ZN.TreeOrder?[...u].reverse():u,[a,u]);v.useEffect(()=>{if(!o||!u.length||!S){b();return}for(const k of N){if((r==null?void 0:r(k))===!1)continue;const _=u.indexOf(k),E=d[_];if(!E)continue;const{direction:D,speed:j}=SZe(k,E,S,t,h);for(const I of["x","y"])p[I][D[I]]||(j[I]=0,D[I]=0);if(j.x>0||j.y>0){b(),w.current=k,g(C,i),x.current=j,y.current=D;return}}x.current={x:0,y:0},y.current={x:0,y:0},b()},[t,C,r,b,o,i,JSON.stringify(S),JSON.stringify(p),g,u,N,d,JSON.stringify(h)])}const FZe={x:{[ws.Backward]:!1,[ws.Forward]:!1},y:{[ws.Backward]:!1,[ws.Forward]:!1}};function PZe(e){let{delta:t,disabled:n}=e;const r=YN(t);return ew(s=>{if(n||!r||!s)return FZe;const o={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[ws.Backward]:s.x[ws.Backward]||o.x===-1,[ws.Forward]:s.x[ws.Forward]||o.x===1},y:{[ws.Backward]:s.y[ws.Backward]||o.y===-1,[ws.Forward]:s.y[ws.Forward]||o.y===1}}},[n,t,r])}function OZe(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return ew(s=>{var o;return t==null?null:(o=r??s)!=null?o:null},[r,t])}function LZe(e,t){return v.useMemo(()=>e.reduce((n,r)=>{const{sensor:s}=r,o=s.activators.map(i=>({eventName:i.eventName,handler:t(i.handler,r)}));return[...n,...o]},[]),[e,t])}var _0;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(_0||(_0={}));var pR;(function(e){e.Optimized="optimized"})(pR||(pR={}));const T7=new Map;function $Ze(e,t){let{dragging:n,dependencies:r,config:s}=t;const[o,i]=v.useState(null),{frequency:a,measure:c,strategy:u}=s,d=v.useRef(e),f=x(),h=N0(f),p=v.useCallback(function(y){y===void 0&&(y=[]),!h.current&&i(S=>S===null?y:S.concat(y.filter(w=>!S.includes(w))))},[h]),g=v.useRef(null),b=ew(y=>{if(f&&!n)return T7;if(!y||y===T7||d.current!==e||o!=null){const S=new Map;for(let w of e){if(!w)continue;if(o&&o.length>0&&!o.includes(w.id)&&w.rect.current){S.set(w.id,w.rect.current);continue}const C=w.node.current,N=C?new HL(c(C),C):null;w.rect.current=N,N&&S.set(w.id,N)}return S}return y},[e,o,n,f,c]);return v.useEffect(()=>{d.current=e},[e]),v.useEffect(()=>{f||p()},[n,f]),v.useEffect(()=>{o&&o.length>0&&i(null)},[JSON.stringify(o)]),v.useEffect(()=>{f||typeof a!="number"||g.current!==null||(g.current=setTimeout(()=>{p(),g.current=null},a))},[a,f,p,...r]),{droppableRects:b,measureDroppableContainers:p,measuringScheduled:o!=null};function x(){switch(u){case _0.Always:return!1;case _0.BeforeDragging:return n;default:return!n}}}function WL(e,t){return ew(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function zZe(e,t){return WL(e,t)}function BZe(e){let{callback:t,disabled:n}=e;const r=Dj(t),s=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(r)},[r,n]);return v.useEffect(()=>()=>s==null?void 0:s.disconnect(),[s]),s}function Aj(e){let{callback:t,disabled:n}=e;const r=Dj(t),s=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(r)},[n]);return v.useEffect(()=>()=>s==null?void 0:s.disconnect(),[s]),s}function VZe(e){return new HL(lb(e),e)}function M7(e,t,n){t===void 0&&(t=VZe);const[r,s]=v.useState(null);function o(){s(c=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=c??n)!=null?u:null}const d=t(e);return JSON.stringify(c)===JSON.stringify(d)?c:d})}const i=BZe({callback(c){if(e)for(const u of c){const{type:d,target:f}=u;if(d==="childList"&&f instanceof HTMLElement&&f.contains(e)){o();break}}}}),a=Aj({callback:o});return Ra(()=>{o(),e?(a==null||a.observe(e),i==null||i.observe(document.body,{childList:!0,subtree:!0})):(a==null||a.disconnect(),i==null||i.disconnect())},[e]),r}function HZe(e){const t=WL(e);return lae(e,t)}const A7=[];function UZe(e){const t=v.useRef(e),n=ew(r=>e?r&&r!==A7&&e&&t.current&&e.parentNode===t.current.parentNode?r:Mj(e):A7,[e]);return v.useEffect(()=>{t.current=e},[e]),n}function WZe(e){const[t,n]=v.useState(null),r=v.useRef(e),s=v.useCallback(o=>{const i=gT(o.target);i&&n(a=>a?(a.set(i,fR(i)),new Map(a)):null)},[]);return v.useEffect(()=>{const o=r.current;if(e!==o){i(o);const a=e.map(c=>{const u=gT(c);return u?(u.addEventListener("scroll",s,{passive:!0}),[u,fR(u)]):null}).filter(c=>c!=null);n(a.length?new Map(a):null),r.current=e}return()=>{i(e),i(o)};function i(a){a.forEach(c=>{const u=gT(c);u==null||u.removeEventListener("scroll",s)})}},[s,e]),v.useMemo(()=>e.length?t?Array.from(t.values()).reduce((o,i)=>mm(o,i),Fa):mae(e):Fa,[e,t])}function R7(e,t){t===void 0&&(t=[]);const n=v.useRef(null);return v.useEffect(()=>{n.current=null},t),v.useEffect(()=>{const r=e!==Fa;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?k0(e,n.current):Fa}function qZe(e){v.useEffect(()=>{if(!Ej)return;const t=e.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n==null||n()}},e.map(t=>{let{sensor:n}=t;return n}))}function YZe(e,t){return v.useMemo(()=>e.reduce((n,r)=>{let{eventName:s,handler:o}=r;return n[s]=i=>{o(i,t)},n},{}),[e,t])}function xae(e){return v.useMemo(()=>e?xZe(e):null,[e])}const F7=[];function GZe(e,t){t===void 0&&(t=lb);const[n]=e,r=xae(n?Lo(n):null),[s,o]=v.useState(F7);function i(){o(()=>e.length?e.map(c=>hae(c)?r:new HL(t(c),c)):F7)}const a=Aj({callback:i});return Ra(()=>{a==null||a.disconnect(),i(),e.forEach(c=>a==null?void 0:a.observe(c))},[e]),s}function yae(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Jv(t)?t:e}function KZe(e){let{measure:t}=e;const[n,r]=v.useState(null),s=v.useCallback(u=>{for(const{target:d}of u)if(Jv(d)){r(f=>{const h=t(d);return f?{...f,width:h.width,height:h.height}:h});break}},[t]),o=Aj({callback:s}),i=v.useCallback(u=>{const d=yae(u);o==null||o.disconnect(),d&&(o==null||o.observe(d)),r(d?t(d):null)},[t,o]),[a,c]=qN(i);return v.useMemo(()=>({nodeRef:a,rect:n,setRef:c}),[n,a,c])}const ZZe=[{sensor:cb,options:{}},{sensor:rw,options:{}}],XZe={current:{}},eC={draggable:{measure:j7},droppable:{measure:j7,strategy:_0.WhileDragging,frequency:pR.Optimized},dragOverlay:{measure:lb}};class yy extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const QZe={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new yy,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:KN},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:eC,measureDroppableContainers:KN,windowRect:null,measuringScheduled:!1},vae={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:KN,draggableNodes:new Map,over:null,measureDroppableContainers:KN},sw=v.createContext(vae),wae=v.createContext(QZe);function JZe(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new yy}}}function eXe(e,t){switch(t.type){case ps.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case ps.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case ps.DragEnd:case ps.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ps.RegisterDroppable:{const{element:n}=t,{id:r}=n,s=new yy(e.droppable.containers);return s.set(r,n),{...e,droppable:{...e.droppable,containers:s}}}case ps.SetDroppableDisabled:{const{id:n,key:r,disabled:s}=t,o=e.droppable.containers.get(n);if(!o||r!==o.key)return e;const i=new yy(e.droppable.containers);return i.set(n,{...o,disabled:s}),{...e,droppable:{...e.droppable,containers:i}}}case ps.UnregisterDroppable:{const{id:n,key:r}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const o=new yy(e.droppable.containers);return o.delete(n),{...e,droppable:{...e.droppable,containers:o}}}default:return e}}function tXe(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:s}=v.useContext(sw),o=YN(r),i=YN(n==null?void 0:n.id);return v.useEffect(()=>{if(!t&&!r&&o&&i!=null){if(!Ij(o)||document.activeElement===o.target)return;const a=s.get(i);if(!a)return;const{activatorNode:c,node:u}=a;if(!c.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[c.current,u.current]){if(!d)continue;const f=QKe(d);if(f){f.focus();break}}})}},[r,t,s,i,o]),null}function Sae(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((s,o)=>o({transform:s,...r}),n):n}function nXe(e){return v.useMemo(()=>({draggable:{...eC.draggable,...e==null?void 0:e.draggable},droppable:{...eC.droppable,...e==null?void 0:e.droppable},dragOverlay:{...eC.dragOverlay,...e==null?void 0:e.dragOverlay}}),[e==null?void 0:e.draggable,e==null?void 0:e.droppable,e==null?void 0:e.dragOverlay])}function rXe(e){let{activeNode:t,measure:n,initialRect:r,config:s=!0}=e;const o=v.useRef(!1),{x:i,y:a}=typeof s=="boolean"?{x:s,y:s}:s;Ra(()=>{if(!i&&!a||!t){o.current=!1;return}if(o.current||!r)return;const u=t==null?void 0:t.node.current;if(!u||u.isConnected===!1)return;const d=n(u),f=lae(d,r);if(i||(f.x=0),a||(f.y=0),o.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const h=uae(u);h&&h.scrollBy({top:f.y,left:f.x})}},[t,i,a,r,n])}const Rj=v.createContext({...Fa,scaleX:1,scaleY:1});var yu;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(yu||(yu={}));const ow=v.memo(function(t){var n,r,s,o;let{id:i,accessibility:a,autoScroll:c=!0,children:u,sensors:d=ZZe,collisionDetection:f=fZe,measuring:h,modifiers:p,...g}=t;const b=v.useReducer(eXe,void 0,JZe),[x,y]=b,[S,w]=sZe(),[C,N]=v.useState(yu.Uninitialized),k=C===yu.Initialized,{draggable:{active:_,nodes:E,translate:D},droppable:{containers:j}}=x,I=_!=null?E.get(_):null,T=v.useRef({initial:null,translated:null}),F=v.useMemo(()=>{var Ve;return _!=null?{id:_,data:(Ve=I==null?void 0:I.data)!=null?Ve:XZe,rect:T}:null},[_,I]),P=v.useRef(null),[R,B]=v.useState(null),[z,U]=v.useState(null),Y=N0(g,Object.values(g)),O=tw("DndDescribedBy",i),K=v.useMemo(()=>j.getEnabled(),[j]),q=nXe(h),{droppableRects:M,measureDroppableContainers:G,measuringScheduled:L}=$Ze(K,{dragging:k,dependencies:[D.x,D.y],config:q.droppable}),$=OZe(E,_),V=v.useMemo(()=>z?GN(z):null,[z]),H=Ye(),A=zZe($,q.draggable.measure);rXe({activeNode:_!=null?E.get(_):null,config:H.layoutShiftCompensation,initialRect:A,measure:q.draggable.measure});const W=M7($,q.draggable.measure,A),X=M7($?$.parentElement:null),Z=v.useRef({activatorEvent:null,active:null,activeNode:$,collisionRect:null,collisions:null,droppableRects:M,draggableNodes:E,draggingNode:null,draggingNodeRect:null,droppableContainers:j,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),J=j.getNodeFor((n=Z.current.over)==null?void 0:n.id),re=KZe({measure:q.dragOverlay.measure}),fe=(r=re.nodeRef.current)!=null?r:$,de=k?(s=re.rect)!=null?s:W:null,Se=!!(re.nodeRef.current&&re.rect),ue=HZe(Se?null:W),ve=xae(fe?Lo(fe):null),xe=UZe(k?J??$:null),ke=GZe(xe),se=Sae(p,{transform:{x:D.x-ue.x,y:D.y-ue.y,scaleX:1,scaleY:1},activatorEvent:z,active:F,activeNodeRect:W,containerNodeRect:X,draggingNodeRect:de,over:Z.current.over,overlayNodeRect:re.rect,scrollableAncestors:xe,scrollableAncestorRects:ke,windowRect:ve}),be=V?mm(V,D):null,Ce=WZe(xe),ge=R7(Ce),ee=R7(Ce,[W]),te=mm(se,ge),ce=de?mZe(de,se):null,le=F&&ce?f({active:F,collisionRect:ce,droppableRects:M,droppableContainers:K,pointerCoordinates:be}):null,Ee=aae(le,"id"),[ye,ne]=v.useState(null),je=Se?se:mm(se,ee),Ue=hZe(je,(o=ye==null?void 0:ye.rect)!=null?o:null,W),Be=v.useRef(null),rt=v.useCallback((Ve,$e)=>{let{sensor:Ae,options:Re}=$e;if(P.current==null)return;const He=E.get(P.current);if(!He)return;const Ge=Ve.nativeEvent,ht=new Ae({active:P.current,activeNode:He,event:Ge,options:Re,context:Z,onAbort(st){if(!E.get(st))return;const{onDragAbort:Ke}=Y.current,_t={id:st};Ke==null||Ke(_t),S({type:"onDragAbort",event:_t})},onPending(st,Fe,Ke,_t){if(!E.get(st))return;const{onDragPending:Ze}=Y.current,at={id:st,constraint:Fe,initialCoordinates:Ke,offset:_t};Ze==null||Ze(at),S({type:"onDragPending",event:at})},onStart(st){const Fe=P.current;if(Fe==null)return;const Ke=E.get(Fe);if(!Ke)return;const{onDragStart:_t}=Y.current,Te={activatorEvent:Ge,active:{id:Fe,data:Ke.data,rect:T}};Sr.unstable_batchedUpdates(()=>{_t==null||_t(Te),N(yu.Initializing),y({type:ps.DragStart,initialCoordinates:st,active:Fe}),S({type:"onDragStart",event:Te}),B(Be.current),U(Ge)})},onMove(st){y({type:ps.DragMove,coordinates:st})},onEnd:lt(ps.DragEnd),onCancel:lt(ps.DragCancel)});Be.current=ht;function lt(st){return async function(){const{active:Ke,collisions:_t,over:Te,scrollAdjustedTranslate:Ze}=Z.current;let at=null;if(Ke&&Ze){const{cancelDrop:bt}=Y.current;at={activatorEvent:Ge,active:Ke,collisions:_t,delta:Ze,over:Te},st===ps.DragEnd&&typeof bt=="function"&&await Promise.resolve(bt(at))&&(st=ps.DragCancel)}P.current=null,Sr.unstable_batchedUpdates(()=>{y({type:st}),N(yu.Uninitialized),ne(null),B(null),U(null),Be.current=null;const bt=st===ps.DragEnd?"onDragEnd":"onDragCancel";if(at){const ft=Y.current[bt];ft==null||ft(at),S({type:bt,event:at})}})}}},[E]),Xe=v.useCallback((Ve,$e)=>(Ae,Re)=>{const He=Ae.nativeEvent,Ge=E.get(Re);if(P.current!==null||!Ge||He.dndKit||He.defaultPrevented)return;const ht={active:Ge};Ve(Ae,$e.options,ht)===!0&&(He.dndKit={capturedBy:$e.sensor},P.current=Re,rt(Ae,$e))},[E,rt]),et=LZe(d,Xe);qZe(d),Ra(()=>{W&&C===yu.Initializing&&N(yu.Initialized)},[W,C]),v.useEffect(()=>{const{onDragMove:Ve}=Y.current,{active:$e,activatorEvent:Ae,collisions:Re,over:He}=Z.current;if(!$e||!Ae)return;const Ge={active:$e,activatorEvent:Ae,collisions:Re,delta:{x:te.x,y:te.y},over:He};Sr.unstable_batchedUpdates(()=>{Ve==null||Ve(Ge),S({type:"onDragMove",event:Ge})})},[te.x,te.y]),v.useEffect(()=>{const{active:Ve,activatorEvent:$e,collisions:Ae,droppableContainers:Re,scrollAdjustedTranslate:He}=Z.current;if(!Ve||P.current==null||!$e||!He)return;const{onDragOver:Ge}=Y.current,ht=Re.get(Ee),lt=ht&&ht.rect.current?{id:ht.id,rect:ht.rect.current,data:ht.data,disabled:ht.disabled}:null,st={active:Ve,activatorEvent:$e,collisions:Ae,delta:{x:He.x,y:He.y},over:lt};Sr.unstable_batchedUpdates(()=>{ne(lt),Ge==null||Ge(st),S({type:"onDragOver",event:st})})},[Ee]),Ra(()=>{Z.current={activatorEvent:z,active:F,activeNode:$,collisionRect:ce,collisions:le,droppableRects:M,draggableNodes:E,draggingNode:fe,draggingNodeRect:de,droppableContainers:j,over:ye,scrollableAncestors:xe,scrollAdjustedTranslate:te},T.current={initial:de,translated:ce}},[F,$,le,ce,E,fe,de,M,j,ye,xe,te]),RZe({...H,delta:D,draggingRect:ce,pointerCoordinates:be,scrollableAncestors:xe,scrollableAncestorRects:ke});const tt=v.useMemo(()=>({active:F,activeNode:$,activeNodeRect:W,activatorEvent:z,collisions:le,containerNodeRect:X,dragOverlay:re,draggableNodes:E,droppableContainers:j,droppableRects:M,over:ye,measureDroppableContainers:G,scrollableAncestors:xe,scrollableAncestorRects:ke,measuringConfiguration:q,measuringScheduled:L,windowRect:ve}),[F,$,W,z,le,X,re,E,j,M,ye,G,xe,ke,q,L,ve]),me=v.useMemo(()=>({activatorEvent:z,activators:et,active:F,activeNodeRect:W,ariaDescribedById:{draggable:O},dispatch:y,draggableNodes:E,over:ye,measureDroppableContainers:G}),[z,et,F,W,y,O,E,ye,G]);return v.createElement(sae.Provider,{value:w},v.createElement(sw.Provider,{value:me},v.createElement(wae.Provider,{value:tt},v.createElement(Rj.Provider,{value:Ue},u)),v.createElement(tXe,{disabled:(a==null?void 0:a.restoreFocus)===!1})),v.createElement(aZe,{...a,hiddenTextDescribedById:O}));function Ye(){const Ve=(R==null?void 0:R.autoScrollEnabled)===!1,$e=typeof c=="object"?c.enabled===!1:c===!1,Ae=k&&!Ve&&!$e;return typeof c=="object"?{...c,enabled:Ae}:{enabled:Ae}}}),sXe=v.createContext(null),P7="button",oXe="Draggable";function iXe(e){let{id:t,data:n,disabled:r=!1,attributes:s}=e;const o=tw(oXe),{activators:i,activatorEvent:a,active:c,activeNodeRect:u,ariaDescribedById:d,draggableNodes:f,over:h}=v.useContext(sw),{role:p=P7,roleDescription:g="draggable",tabIndex:b=0}=s??{},x=(c==null?void 0:c.id)===t,y=v.useContext(x?Rj:sXe),[S,w]=qN(),[C,N]=qN(),k=YZe(i,t),_=N0(n);Ra(()=>(f.set(t,{id:t,key:o,node:S,activatorNode:C,data:_}),()=>{const D=f.get(t);D&&D.key===o&&f.delete(t)}),[f,t]);const E=v.useMemo(()=>({role:p,tabIndex:b,"aria-disabled":r,"aria-pressed":x&&p===P7?!0:void 0,"aria-roledescription":g,"aria-describedby":d.draggable}),[r,p,b,x,g,d.draggable]);return{active:c,activatorEvent:a,activeNodeRect:u,attributes:E,isDragging:x,listeners:r?void 0:k,node:S,over:h,setNodeRef:w,setActivatorNodeRef:N,transform:y}}function Cae(){return v.useContext(wae)}const aXe="Droppable",lXe={timeout:25};function Nae(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:s}=e;const o=tw(aXe),{active:i,dispatch:a,over:c,measureDroppableContainers:u}=v.useContext(sw),d=v.useRef({disabled:n}),f=v.useRef(!1),h=v.useRef(null),p=v.useRef(null),{disabled:g,updateMeasurementsFor:b,timeout:x}={...lXe,...s},y=N0(b??r),S=v.useCallback(()=>{if(!f.current){f.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{u(Array.isArray(y.current)?y.current:[y.current]),p.current=null},x)},[x]),w=Aj({callback:S,disabled:g||!i}),C=v.useCallback((E,D)=>{w&&(D&&(w.unobserve(D),f.current=!1),E&&w.observe(E))},[w]),[N,k]=qN(C),_=N0(t);return v.useEffect(()=>{!w||!N.current||(w.disconnect(),f.current=!1,w.observe(N.current))},[N,w]),v.useEffect(()=>(a({type:ps.RegisterDroppable,element:{id:r,key:o,disabled:n,node:N,rect:h,data:_}}),()=>a({type:ps.UnregisterDroppable,key:o,id:r})),[r]),v.useEffect(()=>{n!==d.current.disabled&&(a({type:ps.SetDroppableDisabled,id:r,key:o,disabled:n}),d.current.disabled=n)},[r,o,n,a]),{active:i,rect:h,isOver:(c==null?void 0:c.id)===r,node:N,over:c,setNodeRef:k}}function cXe(e){let{animation:t,children:n}=e;const[r,s]=v.useState(null),[o,i]=v.useState(null),a=YN(n);return!n&&!r&&a&&s(a),Ra(()=>{if(!o)return;const c=r==null?void 0:r.key,u=r==null?void 0:r.props.id;if(c==null||u==null){s(null);return}Promise.resolve(t(u,o)).then(()=>{s(null)})},[t,r,o]),v.createElement(v.Fragment,null,n,r?v.cloneElement(r,{ref:i}):null)}const uXe={x:0,y:0,scaleX:1,scaleY:1};function dXe(e){let{children:t}=e;return v.createElement(sw.Provider,{value:vae},v.createElement(Rj.Provider,{value:uXe},t))}const fXe={position:"fixed",touchAction:"none"},hXe=e=>Ij(e)?"transform 250ms ease":void 0,pXe=v.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:s,children:o,className:i,rect:a,style:c,transform:u,transition:d=hXe}=e;if(!a)return null;const f=s?u:{...u,scaleX:1,scaleY:1},h={...fXe,width:a.width,height:a.height,top:a.top,left:a.left,transform:_i.Transform.toString(f),transformOrigin:s&&r?lZe(r,a):void 0,transition:typeof d=="function"?d(r):d,...c};return v.createElement(n,{className:i,style:h,ref:t},o)}),mXe=e=>t=>{let{active:n,dragOverlay:r}=t;const s={},{styles:o,className:i}=e;if(o!=null&&o.active)for(const[a,c]of Object.entries(o.active))c!==void 0&&(s[a]=n.node.style.getPropertyValue(a),n.node.style.setProperty(a,c));if(o!=null&&o.dragOverlay)for(const[a,c]of Object.entries(o.dragOverlay))c!==void 0&&r.node.style.setProperty(a,c);return i!=null&&i.active&&n.node.classList.add(i.active),i!=null&&i.dragOverlay&&r.node.classList.add(i.dragOverlay),function(){for(const[c,u]of Object.entries(s))n.node.style.setProperty(c,u);i!=null&&i.active&&n.node.classList.remove(i.active)}},gXe=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:_i.Transform.toString(t)},{transform:_i.Transform.toString(n)}]},bXe={duration:250,easing:"ease",keyframes:gXe,sideEffects:mXe({styles:{active:{opacity:"0"}}})};function xXe(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:s}=e;return Dj((o,i)=>{if(t===null)return;const a=n.get(o);if(!a)return;const c=a.node.current;if(!c)return;const u=yae(i);if(!u)return;const{transform:d}=Lo(i).getComputedStyle(i),f=cae(d);if(!f)return;const h=typeof t=="function"?t:yXe(t);return gae(c,s.draggable.measure),h({active:{id:o,data:a.data,node:c,rect:s.draggable.measure(c)},draggableNodes:n,dragOverlay:{node:i,rect:s.dragOverlay.measure(u)},droppableContainers:r,measuringConfiguration:s,transform:f})})}function yXe(e){const{duration:t,easing:n,sideEffects:r,keyframes:s}={...bXe,...e};return o=>{let{active:i,dragOverlay:a,transform:c,...u}=o;if(!t)return;const d={x:a.rect.left-i.rect.left,y:a.rect.top-i.rect.top},f={scaleX:c.scaleX!==1?i.rect.width*c.scaleX/a.rect.width:1,scaleY:c.scaleY!==1?i.rect.height*c.scaleY/a.rect.height:1},h={x:c.x-d.x,y:c.y-d.y,...f},p=s({...u,active:i,dragOverlay:a,transform:{initial:c,final:h}}),[g]=p,b=p[p.length-1];if(JSON.stringify(g)===JSON.stringify(b))return;const x=r==null?void 0:r({active:i,dragOverlay:a,...u}),y=a.node.animate(p,{duration:t,easing:n,fill:"forwards"});return new Promise(S=>{y.onfinish=()=>{x==null||x(),S()}})}}let O7=0;function vXe(e){return v.useMemo(()=>{if(e!=null)return O7++,O7},[e])}const kae=v.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:s,transition:o,modifiers:i,wrapperElement:a="div",className:c,zIndex:u=999}=e;const{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:p,draggableNodes:g,droppableContainers:b,dragOverlay:x,over:y,measuringConfiguration:S,scrollableAncestors:w,scrollableAncestorRects:C,windowRect:N}=Cae(),k=v.useContext(Rj),_=vXe(f==null?void 0:f.id),E=Sae(i,{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:p,draggingNodeRect:x.rect,over:y,overlayNodeRect:x.rect,scrollableAncestors:w,scrollableAncestorRects:C,transform:k,windowRect:N}),D=WL(h),j=xXe({config:r,draggableNodes:g,droppableContainers:b,measuringConfiguration:S}),I=D?x.setRef:void 0;return v.createElement(dXe,null,v.createElement(cXe,{animation:j},f&&_?v.createElement(pXe,{key:_,id:f.id,ref:I,as:a,activatorEvent:d,adjustScale:t,className:c,transition:o,rect:D,style:{zIndex:u,...s},transform:E},n):null))});function ub(e,t,n){const r=e.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function wXe(e,t){return e.reduce((n,r,s)=>{const o=t.get(r);return o&&(n[s]=o),n},Array(e.length))}function J1(e){return e!==null&&e>=0}function SXe(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function CXe(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const eS={scaleX:1,scaleY:1},qL=e=>{var t;let{rects:n,activeNodeRect:r,activeIndex:s,overIndex:o,index:i}=e;const a=(t=n[s])!=null?t:r;if(!a)return null;const c=NXe(n,i,s);if(i===s){const u=n[o];return u?{x:s<o?u.left+u.width-(a.left+a.width):u.left-a.left,y:0,...eS}:null}return i>s&&i<=o?{x:-a.width-c,y:0,...eS}:i<s&&i>=o?{x:a.width+c,y:0,...eS}:{x:0,y:0,...eS}};function NXe(e,t,n){const r=e[t],s=e[t-1],o=e[t+1];return!r||!s&&!o?0:n<t?s?r.left-(s.left+s.width):o.left-(r.left+r.width):o?o.left-(r.left+r.width):r.left-(s.left+s.width)}const _ae=e=>{let{rects:t,activeIndex:n,overIndex:r,index:s}=e;const o=ub(t,r,n),i=t[s],a=o[s];return!a||!i?null:{x:a.left-i.left,y:a.top-i.top,scaleX:a.width/i.width,scaleY:a.height/i.height}},tS={scaleX:1,scaleY:1},YL=e=>{var t;let{activeIndex:n,activeNodeRect:r,index:s,rects:o,overIndex:i}=e;const a=(t=o[n])!=null?t:r;if(!a)return null;if(s===n){const u=o[i];return u?{x:0,y:n<i?u.top+u.height-(a.top+a.height):u.top-a.top,...tS}:null}const c=kXe(o,s,n);return s>n&&s<=i?{x:0,y:-a.height-c,...tS}:s<n&&s>=i?{x:0,y:a.height+c,...tS}:{x:0,y:0,...tS}};function kXe(e,t,n){const r=e[t],s=e[t-1],o=e[t+1];return r?n<t?s?r.top-(s.top+s.height):o?o.top-(r.top+r.height):0:o?o.top-(r.top+r.height):s?r.top-(s.top+s.height):0:0}const jae="Sortable",Eae=v.createContext({activeIndex:-1,containerId:jae,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:_ae,disabled:{draggable:!1,droppable:!1}});function iw(e){let{children:t,id:n,items:r,strategy:s=_ae,disabled:o=!1}=e;const{active:i,dragOverlay:a,droppableRects:c,over:u,measureDroppableContainers:d}=Cae(),f=tw(jae,n),h=a.rect!==null,p=v.useMemo(()=>r.map(k=>typeof k=="object"&&"id"in k?k.id:k),[r]),g=i!=null,b=i?p.indexOf(i.id):-1,x=u?p.indexOf(u.id):-1,y=v.useRef(p),S=!SXe(p,y.current),w=x!==-1&&b===-1||S,C=CXe(o);Ra(()=>{S&&g&&d(p)},[S,p,g,d]),v.useEffect(()=>{y.current=p},[p]);const N=v.useMemo(()=>({activeIndex:b,containerId:f,disabled:C,disableTransforms:w,items:p,overIndex:x,useDragOverlay:h,sortedRects:wXe(p,c),strategy:s}),[b,f,C.draggable,C.droppable,w,p,x,c,h,s]);return v.createElement(Eae.Provider,{value:N},t)}const _Xe=e=>{let{id:t,items:n,activeIndex:r,overIndex:s}=e;return ub(n,r,s).indexOf(t)},jXe=e=>{let{containerId:t,isSorting:n,wasDragging:r,index:s,items:o,newIndex:i,previousItems:a,previousContainerId:c,transition:u}=e;return!u||!r||a!==o&&s===i?!1:n?!0:i!==s&&t===c},EXe={duration:200,easing:"ease"},Dae="transform",DXe=_i.Transition.toString({property:Dae,duration:0,easing:"linear"}),IXe={roleDescription:"sortable"};function TXe(e){let{disabled:t,index:n,node:r,rect:s}=e;const[o,i]=v.useState(null),a=v.useRef(n);return Ra(()=>{if(!t&&n!==a.current&&r.current){const c=s.current;if(c){const u=lb(r.current,{ignoreTransform:!0}),d={x:c.left-u.left,y:c.top-u.top,scaleX:c.width/u.width,scaleY:c.height/u.height};(d.x||d.y)&&i(d)}}n!==a.current&&(a.current=n)},[t,n,r,s]),v.useEffect(()=>{o&&i(null)},[o]),o}function db(e){let{animateLayoutChanges:t=jXe,attributes:n,disabled:r,data:s,getNewIndex:o=_Xe,id:i,strategy:a,resizeObserverConfig:c,transition:u=EXe}=e;const{items:d,containerId:f,activeIndex:h,disabled:p,disableTransforms:g,sortedRects:b,overIndex:x,useDragOverlay:y,strategy:S}=v.useContext(Eae),w=MXe(r,p),C=d.indexOf(i),N=v.useMemo(()=>({sortable:{containerId:f,index:C,items:d},...s}),[f,s,C,d]),k=v.useMemo(()=>d.slice(d.indexOf(i)),[d,i]),{rect:_,node:E,isOver:D,setNodeRef:j}=Nae({id:i,data:N,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:k,...c}}),{active:I,activatorEvent:T,activeNodeRect:F,attributes:P,setNodeRef:R,listeners:B,isDragging:z,over:U,setActivatorNodeRef:Y,transform:O}=iXe({id:i,data:N,attributes:{...IXe,...n},disabled:w.draggable}),K=GKe(j,R),q=!!I,M=q&&!g&&J1(h)&&J1(x),G=!y&&z,L=G&&M?O:null,V=M?L??(a??S)({rects:b,activeNodeRect:F,activeIndex:h,overIndex:x,index:C}):null,H=J1(h)&&J1(x)?o({id:i,items:d,activeIndex:h,overIndex:x}):C,A=I==null?void 0:I.id,W=v.useRef({activeId:A,items:d,newIndex:H,containerId:f}),X=d!==W.current.items,Z=t({active:I,containerId:f,isDragging:z,isSorting:q,id:i,index:C,items:d,newIndex:W.current.newIndex,previousItems:W.current.items,previousContainerId:W.current.containerId,transition:u,wasDragging:W.current.activeId!=null}),J=TXe({disabled:!Z,index:C,node:E,rect:_});return v.useEffect(()=>{q&&W.current.newIndex!==H&&(W.current.newIndex=H),f!==W.current.containerId&&(W.current.containerId=f),d!==W.current.items&&(W.current.items=d)},[q,H,f,d]),v.useEffect(()=>{if(A===W.current.activeId)return;if(A!=null&&W.current.activeId==null){W.current.activeId=A;return}const fe=setTimeout(()=>{W.current.activeId=A},50);return()=>clearTimeout(fe)},[A]),{active:I,activeIndex:h,attributes:P,data:N,rect:_,index:C,newIndex:H,items:d,isOver:D,isSorting:q,isDragging:z,listeners:B,node:E,overIndex:x,over:U,setNodeRef:K,setActivatorNodeRef:Y,setDroppableNodeRef:j,setDraggableNodeRef:R,transform:J??V,transition:re()};function re(){if(J||X&&W.current.newIndex===C)return DXe;if(!(G&&!Ij(T)||!u)&&(q||Z))return _i.Transition.toString({...u,property:Dae})}}function MXe(e,t){var n,r;return typeof e=="boolean"?{draggable:e,droppable:!1}:{draggable:(n=e==null?void 0:e.draggable)!=null?n:t.draggable,droppable:(r=e==null?void 0:e.droppable)!=null?r:t.droppable}}function XN(e){if(!e)return!1;const t=e.data.current;return!!(t&&"sortable"in t&&typeof t.sortable=="object"&&"containerId"in t.sortable&&"items"in t.sortable&&"index"in t.sortable)}const AXe=[In.Down,In.Right,In.Up,In.Left],GL=(e,t)=>{let{context:{active:n,collisionRect:r,droppableRects:s,droppableContainers:o,over:i,scrollableAncestors:a}}=t;if(AXe.includes(e.code)){if(e.preventDefault(),!n||!r)return;const c=[];o.getEnabled().forEach(f=>{if(!f||f!=null&&f.disabled)return;const h=s.get(f.id);if(h)switch(e.code){case In.Down:r.top<h.top&&c.push(f);break;case In.Up:r.top>h.top&&c.push(f);break;case In.Left:r.left>h.left&&c.push(f);break;case In.Right:r.left<h.left&&c.push(f);break}});const u=uZe({collisionRect:r,droppableRects:s,droppableContainers:c});let d=aae(u,"id");if(d===(i==null?void 0:i.id)&&u.length>1&&(d=u[1].id),d!=null){const f=o.get(n.id),h=o.get(d),p=h?s.get(h.id):null,g=h==null?void 0:h.node.current;if(g&&p&&f&&h){const x=Mj(g).some((k,_)=>a[_]!==k),y=Iae(f,h),S=RXe(f,h),w=x||!y?{x:0,y:0}:{x:S?r.width-p.width:0,y:S?r.height-p.height:0},C={x:p.left,y:p.top};return w.x&&w.y?C:k0(C,w)}}}};function Iae(e,t){return!XN(e)||!XN(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function RXe(e,t){return!XN(e)||!XN(t)||!Iae(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function FXe(e,t,n){const[r,s]=v.useState(null),[o,i]=v.useState(""),a=()=>{const g={id:`hierarchy_${Date.now()}`,label:o||"New Hierarchy",type:"static",steps:[],default:!1};t([...e,g]),i(""),s(g.id)},c=g=>{t(e.filter(b=>b.id!==g))},u=(g,b)=>{t(e.map(x=>x.id===g?{...x,...b}:x))};return{editingHierarchy:r,setEditingHierarchy:s,newHierarchyName:o,setNewHierarchyName:i,createNewHierarchy:a,deleteHierarchy:c,updateHierarchy:u,addStepToHierarchy:(g,b)=>{const x=n.find(w=>w.id===b);if(!x)return;const y={field:x,mode:"drillDown",label:`Drill to ${x.label}`,retainFilters:!0,preferredChartType:"bar"},S=e.find(w=>w.id===g);S&&u(g,{steps:[...S.steps,y]})},removeStepFromHierarchy:(g,b)=>{const x=e.find(y=>y.id===g);if(x){const y=[...x.steps];y.splice(b,1),u(g,{steps:y})}},updateStep:(g,b,x)=>{const y=e.find(S=>S.id===g);if(y){const S=y.steps.map((w,C)=>C===b?{...w,...x}:w);u(g,{steps:S})}},setDefaultHierarchy:g=>{t(e.map(b=>({...b,default:b.id===g})))}}}function PXe({step:e,hierarchyId:t,stepIndex:n,onUpdateStep:r,open:s,onOpenChange:o,trigger:i}){return l.jsxs(m.Popover,{open:s,onOpenChange:o,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:i}),l.jsx(m.PopoverContent,{className:"z-50 w-80",align:"start",children:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{children:[l.jsx(m.Label,{className:"mb-1 block text-xs font-medium",children:"Chart Type"}),l.jsxs(m.Select,{value:e.preferredChartType||"bar",onValueChange:a=>{r(t,n,{preferredChartType:a})},children:[l.jsx(m.SelectTrigger,{className:"h-8",children:l.jsx(m.SelectValue,{})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"bar",children:"Bar Chart"}),l.jsx(m.SelectItem,{value:"pie",children:"Pie Chart"}),l.jsx(m.SelectItem,{value:"line",children:"Line Chart"}),l.jsx(m.SelectItem,{value:"donut",children:"Donut Chart"}),l.jsx(m.SelectItem,{value:"table",children:"Table"}),l.jsx(m.SelectItem,{value:"metric",children:"Metric"})]})]})]}),l.jsxs("div",{children:[l.jsx(m.Label,{className:"mb-1 block text-xs font-medium",children:"Step Label"}),l.jsx(m.Input,{value:e.label||"",onChange:a=>r(t,n,{label:a.target.value}),placeholder:"Custom drill label",className:"h-8"})]}),l.jsxs("div",{children:[l.jsx(m.Label,{className:"mb-1 block text-xs font-medium",children:"Breadcrumb Label Template"}),l.jsx(m.Input,{value:e.breadcrumbLabelTemplate||"",onChange:a=>r(t,n,{breadcrumbLabelTemplate:a.target.value}),placeholder:"e.g., 'Region: {{value}}'",className:"h-8"})]}),l.jsx("div",{className:"flex items-center gap-4",children:l.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[l.jsx("input",{type:"checkbox",checked:e.retainFilters!==!1,onChange:a=>r(t,n,{retainFilters:a.target.checked}),className:"rounded"}),"Retain filters when drilling"]})}),l.jsx("div",{className:"flex justify-end",children:l.jsx(m.Button,{size:"sm",variant:"outline",onClick:()=>o(!1),children:"Done"})})]})})]})}function OXe({field:e,step:t,stepIndex:n,hierarchyId:r,onUpdateStep:s,onRemoveStep:o}){const[i,a]=v.useState(!1),{attributes:c,listeners:u,setNodeRef:d,transform:f,transition:h,isDragging:p}=db({id:`${r}-${e.id}-${n}`,disabled:!1}),g={transform:_i.Transform.toString(f),transition:h,opacity:p?.8:1,zIndex:p?1e3:1};return l.jsx("div",{ref:d,style:g,className:`relative ${i?"z-[9998]":""}`,...c,children:l.jsx(PXe,{step:t,hierarchyId:r,stepIndex:n,onUpdateStep:s,open:i,onOpenChange:a,trigger:l.jsxs("div",{className:`flex cursor-pointer items-center gap-2 rounded-lg border bg-muted px-3 py-2 transition-colors hover:bg-muted/50 ${p?"shadow-lg ring-2 ring-primary":""}`,...u,onClick:b=>{b.stopPropagation(),a(x=>!x)},children:[l.jsxs("div",{className:"pointer-events-none flex items-center gap-2",children:[l.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:e.label}),t.preferredChartType&&t.preferredChartType!=="bar"&&l.jsx("span",{className:"whitespace-nowrap rounded bg-purple-100 px-1 py-0.5 text-xs text-purple-700 dark:bg-purple-900/50 dark:text-purple-300",children:t.preferredChartType}),t.linkedInsightId&&l.jsx("span",{className:"whitespace-nowrap rounded bg-green-100 px-1 py-0.5 text-xs text-green-700 dark:bg-green-900/50 dark:text-green-300",children:"📊"})]}),l.jsx("button",{className:"pointer-events-auto ml-1 text-xs text-muted-foreground hover:text-red-800 dark:hover:text-red-400",onClick:b=>{b.stopPropagation(),o(r,n)},children:l.jsx(m.X,{className:"h-3 w-3"})})]})})})}function LXe(e){return{sensors:Tj(cg(cb,{activationConstraint:{distance:5}}),cg(rw,{coordinateGetter:GL})),handleStepDragEnd:(r,s)=>{const{active:o,over:i}=r;if(!i||o.id===i.id)return;const a=o.id.replace(`${s.id}-`,""),c=i.id.replace(`${s.id}-`,""),u=s.steps.findIndex(f=>f.field.id===a),d=s.steps.findIndex(f=>f.field.id===c);if(u!==-1&&d!==-1&&u!==d){const f=ub(s.steps,u,d);e(s.id,{steps:f})}}}}function $Xe({hierarchy:e,onUpdateStep:t,onRemoveStep:n,onUpdateHierarchy:r}){const{sensors:s}=LXe(r),[o,i]=v.useState(null),a=e.steps.filter(h=>h&&h.field&&h.field.id),u=a.map(h=>h.field).map((h,p)=>`${e.id}-${h.id}-${p}`),d=h=>{const p=h.active.id,g=Number.parseInt(p.split("-").pop()||"0"),b=a[g],x=b==null?void 0:b.field;i(x||null)},f=h=>{i(null);const{active:p,over:g}=h;if(!g||p.id===g.id)return;const b=Number.parseInt(p.id.split("-").pop()||"0"),x=Number.parseInt(g.id.split("-").pop()||"0");if(b!==x&&b<a.length&&x<a.length){const y=[...e.steps],[S]=y.splice(b,1);y.splice(x,0,S),r(e.id,{steps:y})}};return a.length===0?l.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:l.jsx("div",{className:"rounded-lg border bg-muted/50 p-2 text-sm text-muted-foreground",children:"No drill steps configured. Add steps to create a drill hierarchy."})}):l.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:l.jsxs(ow,{sensors:s,collisionDetection:nw,onDragStart:d,onDragEnd:f,children:[l.jsx(iw,{items:u,strategy:qL,children:l.jsx("div",{className:"flex flex-wrap items-center gap-2",style:{minHeight:"40px"},children:a.map((h,p)=>{if(!h||!h.field||!h.field.id)return null;const g=[];p>0&&g.push(l.jsx(Mr,{className:"pointer-events-none h-4 w-4 text-gray-400"},`arrow-${p}`));const b=p===0,x=p===a.length-1;return g.push(l.jsx(OXe,{field:h.field,step:h,stepIndex:p,hierarchyId:e.id,onUpdateStep:t,onRemoveStep:n,isFirstField:b,isLastField:x},`field-${h.field.id}-${p}`)),g})})}),typeof window<"u"&&Sr.createPortal(l.jsx(sb,{children:l.jsx(kae,{style:{zIndex:9999},children:o?l.jsx("div",{className:"flex items-center gap-2 rounded-lg border-2 border-blue-300 bg-blue-200 p-2 shadow-lg dark:border-blue-600 dark:bg-blue-900/70",children:l.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:o.label})}):null})}),document.body)]})})}var L7=1,zXe=.9,BXe=.8,VXe=.17,yT=.1,vT=.999,HXe=.9999,UXe=.99,WXe=/[\\\/_+.#"@\[\(\{&]/,qXe=/[\\\/_+.#"@\[\(\{&]/g,YXe=/[\s-]/,Tae=/[\s-]/g;function mR(e,t,n,r,s,o,i){if(o===t.length)return s===e.length?L7:UXe;var a=`${s},${o}`;if(i[a]!==void 0)return i[a];for(var c=r.charAt(o),u=n.indexOf(c,s),d=0,f,h,p,g;u>=0;)f=mR(e,t,n,r,u+1,o+1,i),f>d&&(u===s?f*=L7:WXe.test(e.charAt(u-1))?(f*=BXe,p=e.slice(s,u-1).match(qXe),p&&s>0&&(f*=Math.pow(vT,p.length))):YXe.test(e.charAt(u-1))?(f*=zXe,g=e.slice(s,u-1).match(Tae),g&&s>0&&(f*=Math.pow(vT,g.length))):(f*=VXe,s>0&&(f*=Math.pow(vT,u-s))),e.charAt(u)!==t.charAt(o)&&(f*=HXe)),(f<yT&&n.charAt(u-1)===r.charAt(o+1)||r.charAt(o+1)===r.charAt(o)&&n.charAt(u-1)!==r.charAt(o))&&(h=mR(e,t,n,r,u+1,o+2,i),h*yT>f&&(f=h*yT)),f>d&&(d=f),u=n.indexOf(c,u+1);return i[a]=d,d}function $7(e){return e.toLowerCase().replace(Tae," ")}function GXe(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,mR(e,t,$7(e),$7(t),0,0,{})}var rx='[cmdk-group=""]',wT='[cmdk-group-items=""]',KXe='[cmdk-group-heading=""]',Mae='[cmdk-item=""]',z7=`${Mae}:not([aria-disabled="true"])`,gR="cmdk-item-select",zp="data-value",ZXe=(e,t,n)=>GXe(e,t,n),Aae=Q.createContext(void 0),aw=()=>Q.useContext(Aae),Rae=Q.createContext(void 0),KL=()=>Q.useContext(Rae),Fae=Q.createContext(void 0),Pae=Q.forwardRef((e,t)=>{let n=Bp(()=>{var q,M;return{search:"",value:(M=(q=e.value)!=null?q:e.defaultValue)!=null?M:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Bp(()=>new Set),s=Bp(()=>new Map),o=Bp(()=>new Map),i=Bp(()=>new Set),a=Oae(e),{label:c,children:u,value:d,onValueChange:f,filter:h,shouldFilter:p,loop:g,disablePointerSelection:b=!1,vimBindings:x=!0,...y}=e,S=m.useId(),w=m.useId(),C=m.useId(),N=Q.useRef(null),k=aQe();Mh(()=>{if(d!==void 0){let q=d.trim();n.current.value=q,_.emit()}},[d]),Mh(()=>{k(6,F)},[]);let _=Q.useMemo(()=>({subscribe:q=>(i.current.add(q),()=>i.current.delete(q)),snapshot:()=>n.current,setState:(q,M,G)=>{var L,$,V,H;if(!Object.is(n.current[q],M)){if(n.current[q]=M,q==="search")T(),j(),k(1,I);else if(q==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let A=document.getElementById(C);A?A.focus():(L=document.getElementById(S))==null||L.focus()}if(k(7,()=>{var A;n.current.selectedItemId=(A=P())==null?void 0:A.id,_.emit()}),G||k(5,F),(($=a.current)==null?void 0:$.value)!==void 0){let A=M??"";(H=(V=a.current).onValueChange)==null||H.call(V,A);return}}_.emit()}},emit:()=>{i.current.forEach(q=>q())}}),[]),E=Q.useMemo(()=>({value:(q,M,G)=>{var L;M!==((L=o.current.get(q))==null?void 0:L.value)&&(o.current.set(q,{value:M,keywords:G}),n.current.filtered.items.set(q,D(M,G)),k(2,()=>{j(),_.emit()}))},item:(q,M)=>(r.current.add(q),M&&(s.current.has(M)?s.current.get(M).add(q):s.current.set(M,new Set([q]))),k(3,()=>{T(),j(),n.current.value||I(),_.emit()}),()=>{o.current.delete(q),r.current.delete(q),n.current.filtered.items.delete(q);let G=P();k(4,()=>{T(),(G==null?void 0:G.getAttribute("id"))===q&&I(),_.emit()})}),group:q=>(s.current.has(q)||s.current.set(q,new Set),()=>{o.current.delete(q),s.current.delete(q)}),filter:()=>a.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:S,inputId:C,labelId:w,listInnerRef:N}),[]);function D(q,M){var G,L;let $=(L=(G=a.current)==null?void 0:G.filter)!=null?L:ZXe;return q?$(q,n.current.search,M):0}function j(){if(!n.current.search||a.current.shouldFilter===!1)return;let q=n.current.filtered.items,M=[];n.current.filtered.groups.forEach(L=>{let $=s.current.get(L),V=0;$.forEach(H=>{let A=q.get(H);V=Math.max(A,V)}),M.push([L,V])});let G=N.current;R().sort((L,$)=>{var V,H;let A=L.getAttribute("id"),W=$.getAttribute("id");return((V=q.get(W))!=null?V:0)-((H=q.get(A))!=null?H:0)}).forEach(L=>{let $=L.closest(wT);$?$.appendChild(L.parentElement===$?L:L.closest(`${wT} > *`)):G.appendChild(L.parentElement===G?L:L.closest(`${wT} > *`))}),M.sort((L,$)=>$[1]-L[1]).forEach(L=>{var $;let V=($=N.current)==null?void 0:$.querySelector(`${rx}[${zp}="${encodeURIComponent(L[0])}"]`);V==null||V.parentElement.appendChild(V)})}function I(){let q=R().find(G=>G.getAttribute("aria-disabled")!=="true"),M=q==null?void 0:q.getAttribute(zp);_.setState("value",M||void 0)}function T(){var q,M,G,L;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let $=0;for(let V of r.current){let H=(M=(q=o.current.get(V))==null?void 0:q.value)!=null?M:"",A=(L=(G=o.current.get(V))==null?void 0:G.keywords)!=null?L:[],W=D(H,A);n.current.filtered.items.set(V,W),W>0&&$++}for(let[V,H]of s.current)for(let A of H)if(n.current.filtered.items.get(A)>0){n.current.filtered.groups.add(V);break}n.current.filtered.count=$}function F(){var q,M,G;let L=P();L&&(((q=L.parentElement)==null?void 0:q.firstChild)===L&&((G=(M=L.closest(rx))==null?void 0:M.querySelector(KXe))==null||G.scrollIntoView({block:"nearest"})),L.scrollIntoView({block:"nearest"}))}function P(){var q;return(q=N.current)==null?void 0:q.querySelector(`${Mae}[aria-selected="true"]`)}function R(){var q;return Array.from(((q=N.current)==null?void 0:q.querySelectorAll(z7))||[])}function B(q){let M=R()[q];M&&_.setState("value",M.getAttribute(zp))}function z(q){var M;let G=P(),L=R(),$=L.findIndex(H=>H===G),V=L[$+q];(M=a.current)!=null&&M.loop&&(V=$+q<0?L[L.length-1]:$+q===L.length?L[0]:L[$+q]),V&&_.setState("value",V.getAttribute(zp))}function U(q){let M=P(),G=M==null?void 0:M.closest(rx),L;for(;G&&!L;)G=q>0?oQe(G,rx):iQe(G,rx),L=G==null?void 0:G.querySelector(z7);L?_.setState("value",L.getAttribute(zp)):z(q)}let Y=()=>B(R().length-1),O=q=>{q.preventDefault(),q.metaKey?Y():q.altKey?U(1):z(1)},K=q=>{q.preventDefault(),q.metaKey?B(0):q.altKey?U(-1):z(-1)};return Q.createElement(m.Primitive.div,{ref:t,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:q=>{var M;(M=y.onKeyDown)==null||M.call(y,q);let G=q.nativeEvent.isComposing||q.keyCode===229;if(!(q.defaultPrevented||G))switch(q.key){case"n":case"j":{x&&q.ctrlKey&&O(q);break}case"ArrowDown":{O(q);break}case"p":case"k":{x&&q.ctrlKey&&K(q);break}case"ArrowUp":{K(q);break}case"Home":{q.preventDefault(),B(0);break}case"End":{q.preventDefault(),Y();break}case"Enter":{q.preventDefault();let L=P();if(L){let $=new Event(gR);L.dispatchEvent($)}}}}},Q.createElement("label",{"cmdk-label":"",htmlFor:E.inputId,id:E.labelId,style:cQe},c),Fj(e,q=>Q.createElement(Rae.Provider,{value:_},Q.createElement(Aae.Provider,{value:E},q))))}),XXe=Q.forwardRef((e,t)=>{var n,r;let s=m.useId(),o=Q.useRef(null),i=Q.useContext(Fae),a=aw(),c=Oae(e),u=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;Mh(()=>{if(!u)return a.item(s,i==null?void 0:i.id)},[u]);let d=Lae(s,o,[e.value,e.children,o],e.keywords),f=KL(),h=gd(k=>k.value&&k.value===d.current),p=gd(k=>u||a.filter()===!1?!0:k.search?k.filtered.items.get(s)>0:!0);Q.useEffect(()=>{let k=o.current;if(!(!k||e.disabled))return k.addEventListener(gR,g),()=>k.removeEventListener(gR,g)},[p,e.onSelect,e.disabled]);function g(){var k,_;b(),(_=(k=c.current).onSelect)==null||_.call(k,d.current)}function b(){f.setState("value",d.current,!0)}if(!p)return null;let{disabled:x,value:y,onSelect:S,forceMount:w,keywords:C,...N}=e;return Q.createElement(m.Primitive.div,{ref:m.composeRefs(o,t),...N,id:s,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!h,"data-disabled":!!x,"data-selected":!!h,onPointerMove:x||a.getDisablePointerSelection()?void 0:b,onClick:x?void 0:g},e.children)}),QXe=Q.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:s,...o}=e,i=m.useId(),a=Q.useRef(null),c=Q.useRef(null),u=m.useId(),d=aw(),f=gd(p=>s||d.filter()===!1?!0:p.search?p.filtered.groups.has(i):!0);Mh(()=>d.group(i),[]),Lae(i,a,[e.value,e.heading,c]);let h=Q.useMemo(()=>({id:i,forceMount:s}),[s]);return Q.createElement(m.Primitive.div,{ref:m.composeRefs(a,t),...o,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&Q.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:u},n),Fj(e,p=>Q.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?u:void 0},Q.createElement(Fae.Provider,{value:h},p))))}),JXe=Q.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,s=Q.useRef(null),o=gd(i=>!i.search);return!n&&!o?null:Q.createElement(m.Primitive.div,{ref:m.composeRefs(s,t),...r,"cmdk-separator":"",role:"separator"})}),eQe=Q.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,s=e.value!=null,o=KL(),i=gd(u=>u.search),a=gd(u=>u.selectedItemId),c=aw();return Q.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),Q.createElement(m.Primitive.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":a,id:c.inputId,type:"text",value:s?e.value:i,onChange:u=>{s||o.setState("search",u.target.value),n==null||n(u.target.value)}})}),tQe=Q.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...s}=e,o=Q.useRef(null),i=Q.useRef(null),a=gd(u=>u.selectedItemId),c=aw();return Q.useEffect(()=>{if(i.current&&o.current){let u=i.current,d=o.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let p=u.offsetHeight;d.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return h.observe(u),()=>{cancelAnimationFrame(f),h.unobserve(u)}}},[]),Q.createElement(m.Primitive.div,{ref:m.composeRefs(o,t),...s,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:c.listId},Fj(e,u=>Q.createElement("div",{ref:m.composeRefs(i,c.listInnerRef),"cmdk-list-sizer":""},u)))}),nQe=Q.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:s,contentClassName:o,container:i,...a}=e;return Q.createElement(Pk,{open:n,onOpenChange:r},Q.createElement(Ok,{container:i},Q.createElement(yg,{"cmdk-overlay":"",className:s}),Q.createElement(vg,{"aria-label":e.label,"cmdk-dialog":"",className:o},Q.createElement(Pae,{ref:t,...a}))))}),rQe=Q.forwardRef((e,t)=>gd(n=>n.filtered.count===0)?Q.createElement(m.Primitive.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),sQe=Q.forwardRef((e,t)=>{let{progress:n,children:r,label:s="Loading...",...o}=e;return Q.createElement(m.Primitive.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":s},Fj(e,i=>Q.createElement("div",{"aria-hidden":!0},i)))}),bo=Object.assign(Pae,{List:tQe,Item:XXe,Input:eQe,Group:QXe,Separator:JXe,Dialog:nQe,Empty:rQe,Loading:sQe});function oQe(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function iQe(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Oae(e){let t=Q.useRef(e);return Mh(()=>{t.current=e}),t}var Mh=typeof window>"u"?Q.useEffect:Q.useLayoutEffect;function Bp(e){let t=Q.useRef();return t.current===void 0&&(t.current=e()),t}function gd(e){let t=KL(),n=()=>e(t.snapshot());return Q.useSyncExternalStore(t.subscribe,n,n)}function Lae(e,t,n,r=[]){let s=Q.useRef(),o=aw();return Mh(()=>{var i;let a=(()=>{var u;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(u=d.current.textContent)==null?void 0:u.trim():s.current}})(),c=r.map(u=>u.trim());o.value(e,a,c),(i=t.current)==null||i.setAttribute(zp,a),s.current=a}),s}var aQe=()=>{let[e,t]=Q.useState(),n=Bp(()=>new Map);return Mh(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,s)=>{n.current.set(r,s),t({})}};function lQe(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function Fj({asChild:e,children:t},n){return e&&Q.isValidElement(t)?Q.cloneElement(lQe(t),{ref:t.ref},n(t.props.children)):n(t)}var cQe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Pj=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo,{ref:n,className:m.cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));Pj.displayName=bo.displayName;const ZL=Q.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[l.jsx(Ws,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(bo.Input,{ref:n,className:m.cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));ZL.displayName=bo.Input.displayName;const Oj=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo.List,{ref:n,className:m.cn("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));Oj.displayName=bo.List.displayName;const Lj=Q.forwardRef((e,t)=>l.jsx(bo.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));Lj.displayName=bo.Empty.displayName;const $j=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo.Group,{ref:n,className:m.cn("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));$j.displayName=bo.Group.displayName;const $ae=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo.Separator,{ref:n,className:m.cn("-mx-1 h-px bg-border",e),...t}));$ae.displayName=bo.Separator.displayName;const zj=Q.forwardRef(({className:e,...t},n)=>l.jsx(bo.Item,{ref:n,className:m.cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",e),...t}));zj.displayName=bo.Item.displayName;function uQe({hierarchy:e,sampleFieldReferences:t,onUpdateHierarchy:n,onDeleteHierarchy:r,onUpdateStep:s,onRemoveStep:o,onAddStep:i}){const[a,c]=v.useState(!1),{attributes:u,listeners:d,setNodeRef:f,transform:h,transition:p}=db({id:e.id,disabled:!1}),g={transform:_i.Transform.toString(h),transition:p},b=e.steps.filter(x=>x.field).map(x=>x.field.id);return l.jsxs("div",{ref:f,style:g,className:"hierarchy-container relative rounded-lg border bg-background p-3 transition-shadow hover:shadow-md",children:[l.jsxs("div",{className:"mb-3 flex cursor-move items-center justify-between",...u,...d,children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("div",{onPointerDown:x=>x.stopPropagation(),onClick:x=>x.stopPropagation(),onKeyDown:x=>x.stopPropagation(),children:l.jsx(Zi,{value:e.label||"",onSave:x=>{n(e.id,{label:x})},placeholder:"Hierarchy Name",displayClassName:"font-medium",inputClassName:"font-medium"})})}),l.jsx("div",{className:"flex items-center gap-1",children:l.jsx(m.Button,{size:"sm",variant:"ghost",onClick:x=>{x.stopPropagation(),r(e.id)},onPointerDown:x=>x.stopPropagation(),children:l.jsx(yl,{className:"h-3 w-3"})})})]}),l.jsx($Xe,{hierarchy:e,onUpdateStep:s,onRemoveStep:o,onUpdateHierarchy:n}),l.jsx("div",{className:"mt-3 border-t pt-3","data-hierarchy-editing":!0,children:a?l.jsxs(Pj,{className:"rounded-lg border",children:[l.jsx(ZL,{placeholder:"Search fields..."}),l.jsxs(Oj,{children:[l.jsx(Lj,{children:"No field found."}),l.jsx($j,{children:t.filter(x=>!b.includes(x.id)).map(x=>l.jsx(zj,{value:x.label,onSelect:()=>{i(e.id,x.id),c(!1)},children:x.label},x.id))})]})]}):l.jsxs(m.Button,{type:"button",variant:"outline",size:"sm",onClick:x=>{x.preventDefault(),x.stopPropagation(),c(!0)},children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Add Step"]})})]})}function dQe({open:e,onOpenChange:t,drillHierarchies:n,onUpdateHierarchies:r,availableFields:s}){const[o,i]=v.useState(n);v.useEffect(()=>{e&&i(n)},[e,n]);const a=v.useMemo(()=>s.filter(S=>m.getDataType(S.dataType)==="string"),[s]),c=Tj(cg(cb),cg(rw,{coordinateGetter:GL})),{createNewHierarchy:u,deleteHierarchy:d,updateHierarchy:f,addStepToHierarchy:h,removeStepFromHierarchy:p,updateStep:g,setDefaultHierarchy:b}=FXe(o,i,a),x=S=>{const{active:w,over:C}=S;if(w.id!==(C==null?void 0:C.id)){const N=o.findIndex(_=>_.id===w.id),k=o.findIndex(_=>_.id===(C==null?void 0:C.id));i(ub(o,N,k))}},y=S=>{S||r(o),t(S)};return l.jsx(Oo,{modal:!0,open:e,onOpenChange:y,children:l.jsx(mo,{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden p-0",onInteractOutside:S=>S.preventDefault(),onEscapeKeyDown:S=>S.preventDefault(),children:l.jsx(m.FocusScope,{trapped:!1,children:l.jsxs("div",{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden",children:[l.jsxs(na,{className:"border-b px-6 pb-4 pt-6",children:[l.jsx(go,{children:"Manage Drill Hierarchies"}),l.jsx(si,{children:"Create multiple drill paths for different analysis scenarios. Define step-by-step navigation through your dimensions."})]}),l.jsx(m.ScrollArea,{className:"flex-1 px-6",children:l.jsxs("div",{className:"space-y-4 py-4",children:[o.length>0&&l.jsx("div",{className:"flex justify-end",children:l.jsxs(m.Button,{type:"button",size:"sm",onClick:S=>{S.preventDefault(),S.stopPropagation(),u()},children:[l.jsx(dr,{className:"mr-1 h-4 w-4"}),"Add Hierarchy"]})}),o.length>0?l.jsx(ow,{sensors:c,collisionDetection:nw,onDragEnd:x,children:l.jsx(iw,{items:o.map(S=>S.id),strategy:YL,children:l.jsx("div",{className:"space-y-4",children:o.map(S=>l.jsx(uQe,{hierarchy:S,sampleFieldReferences:a,onUpdateHierarchy:f,onDeleteHierarchy:d,onSetDefaultHierarchy:b,onUpdateStep:g,onRemoveStep:p,onAddStep:h},S.id))})})}):l.jsxs("div",{className:"rounded-lg border border-dashed p-8 text-center",children:[l.jsx("p",{className:"mb-2 text-sm text-muted-foreground",children:"No hierarchies configured yet"}),l.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:"Create your first hierarchy to enable drill-down interactions"}),l.jsxs(m.Button,{type:"button",size:"sm",variant:"outline",onClick:S=>{S.preventDefault(),S.stopPropagation(),u()},children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Create First Hierarchy"]})]})]})}),l.jsx("div",{className:"flex justify-end gap-2 border-t px-6 py-4",children:l.jsx(m.Button,{variant:"outline",onClick:()=>y(!1),children:"Done"})})]})})})})}function j0(e){switch(e){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];case"hour":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:00 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:00 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"minute":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:00 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"second":return[{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}}function fQe({interaction:e,onUpdate:t,card:n,availableFields:r,onUpdateHierarchies:s,onManageHierarchies:o}){var I;const[i,a]=v.useState(!1),[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,p]=v.useState(!1),[g,b]=v.useState({}),x=v.useMemo(()=>{var T;return((T=n.interactionConfig)==null?void 0:T.drillHierarchies)||[]},[(I=n.interactionConfig)==null?void 0:I.drillHierarchies]),y=v.useMemo(()=>{var R,B;const T=[],F=e.trigger;if(!F)return T;let P;if(F.type==="attribute"){const z=r.find(Y=>Y.id===F.field.id);z&&(z.dataType==="date"||z.dataType==="timestamp")&&(P=z)}else if(F.type==="metric"){const z=(B=(R=n.config)==null?void 0:R.groupByColumns)==null?void 0:B.find(U=>U.dataType==="date"||U.dataType==="timestamp");z&&(P=z)}if(P&&m.shouldAutoGenerateDateHierarchy(P,x)){const z=m.generateDateHierarchy(P);T.push(z)}return T},[r,x,e.trigger,n.config]),S=v.useMemo(()=>[...x,...y],[x,y]),w=S.find(T=>T.id===e.hierarchyId);Q.useEffect(()=>{i&&w&&w.type==="date"?f(w.id):i||f(null)},[i,w]);const C=T=>{if(y.some(P=>P.id===T)&&s){const P=y.find(R=>R.id===T);P&&s([...x,P])}t({...e,hierarchyId:T}),a(!1)},N=()=>{a(!1),u(!0),o&&o()},k=T=>{s&&s(T)},_=T=>T.steps.map(P=>P.field.label||P.field.name).join(" → "),E=T=>T&&T.charAt(0).toUpperCase()+T.slice(1),D=(T,F,P)=>{const R=[...T.steps];R[F]={...R[F],field:{...R[F].field,dateFormat:P,customFormat:P==="custom"?g[F]||"":void 0}};const B={...T,steps:R};if(s){const z=x.findIndex(U=>U.id===T.id);if(z>=0){const U=[...x];U[z]=B,s(U)}else s([...x,B])}},j=(T,F,P)=>{b(z=>({...z,[F]:P}));const R=[...T.steps];R[F]={...R[F],field:{...R[F].field,dateFormat:"custom",customFormat:P}};const B={...T,steps:R};if(s){const z=x.findIndex(U=>U.id===T.id);if(z>=0){const U=[...x];U[z]=B,s(U)}else s([...x,B])}};return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Choose hierarchy"}),l.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Select which hierarchy to drill through when this interaction triggers"}),S.length>0?l.jsxs(l.Fragment,{children:[l.jsxs(m.Popover,{open:i,onOpenChange:a,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsxs(m.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[l.jsx("div",{className:"flex flex-1 flex-col items-start text-left",children:w?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{className:"font-medium",children:w.label||"Unnamed Hierarchy"})}),l.jsx("span",{className:"text-xs text-muted-foreground",children:_(w)})]}):l.jsx("span",{className:"text-muted-foreground",children:"Select hierarchy..."})}),l.jsxs("div",{className:"flex items-center gap-2",children:[w&&w.type==="date"&&l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:T=>{T.stopPropagation(),p(!h)},children:l.jsx(xF,{className:"h-3 w-3"})}),l.jsx(Mr,{className:"h-4 w-4 shrink-0 opacity-50"})]})]})}),l.jsxs(m.PopoverContent,{className:"w-[500px] p-0",align:"start",children:[l.jsxs("div",{className:"flex items-center justify-between border-b p-3",children:[l.jsx("span",{className:"text-sm font-medium",children:"Select Hierarchy"}),l.jsxs(m.Button,{variant:"ghost",size:"sm",onClick:N,children:[l.jsx(dr,{className:"mr-1.5 h-3.5 w-3.5"}),"Create new"]})]}),l.jsxs("div",{className:"p-2",children:[y.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-3 py-2",children:l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"AUTO-GENERATED"})}),y.map(T=>l.jsx("div",{className:`cursor-pointer rounded-md p-3 hover:bg-muted ${e.hierarchyId===T.id?"bg-muted":""}`,onClick:()=>C(T.id),children:l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{className:"text-sm font-medium",children:T.label||"Unnamed Hierarchy"})}),l.jsx("div",{className:"text-xs text-muted-foreground",children:_(T)})]})},T.id))]}),x.length>0&&l.jsxs(l.Fragment,{children:[y.length>0&&l.jsx("div",{className:"my-2 border-t"}),x.map(T=>l.jsx("div",{className:`cursor-pointer rounded-md p-3 hover:bg-muted ${e.hierarchyId===T.id?"bg-muted":""}`,onClick:()=>C(T.id),children:l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{className:"text-sm font-medium",children:T.label||"Unnamed Hierarchy"})}),l.jsx("div",{className:"text-xs text-muted-foreground",children:_(T)})]})},T.id))]})]})]})]}),w&&w.type==="date"&&h&&l.jsxs("div",{className:"mt-3 space-y-3 rounded-md border border-border p-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Customize Date Formats"}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 text-xs",onClick:()=>p(!1),children:"Close"})]}),w.steps.map((T,F)=>{var z;const P=T.field.granularity;if(!P)return null;const R=j0(P),B=T.field.dateFormat||((z=R[0])==null?void 0:z.value);return l.jsxs("div",{className:"space-y-1",children:[l.jsx(m.Label,{className:"text-xs font-medium text-muted-foreground",children:T.field.label||E(P)}),l.jsxs(m.Select,{value:B,onValueChange:U=>{D(w,F,U)},children:[l.jsx(m.SelectTrigger,{className:"h-8 text-xs",children:l.jsx(m.SelectValue,{})}),l.jsx(m.SelectContent,{children:R.map(U=>l.jsx(m.SelectItem,{value:U.value,className:"text-xs",children:U.label},U.value))})]}),B==="custom"&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx(m.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD)",value:T.field.customFormat||g[F]||"",onChange:U=>{j(w,F,U.target.value)},className:"h-8 text-xs"}),l.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Common tokens: YYYY (year), MM (month), DD (day), HH (hour), mm (minute)"})]})]},F)})]})]}):l.jsxs("div",{className:"rounded-md border border-dashed p-6 text-center",children:[l.jsx("p",{className:"mb-2 text-sm text-muted-foreground",children:"No hierarchies configured"}),l.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:"Create a hierarchy to define your drill path"}),l.jsxs(m.Button,{variant:"outline",size:"sm",onClick:N,children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Create hierarchy"]})]})]}),l.jsx(dQe,{open:c,onOpenChange:u,drillHierarchies:x,onUpdateHierarchies:k,availableFields:r})]})}function hQe({fields:e,selectedFieldIds:t,onSelectionChange:n,searchPlaceholder:r="Search fields...",className:s=""}){const[o,i]=v.useState(""),a=e.filter(d=>d.label.toLowerCase().includes(o.toLowerCase())||d.qualifiedEntityName&&d.qualifiedEntityName.toLowerCase().includes(o.toLowerCase())),c=()=>{const d=[...new Set([...t,...a.map(f=>f.id)])];n(d)},u=()=>{const d=a.map(f=>f.id);n(t.filter(f=>!d.includes(f)))};return l.jsxs("div",{className:`space-y-2 ${s}`,children:[l.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[l.jsx(m.Input,{placeholder:r,value:o,onChange:d=>i(d.target.value),className:"flex-1"}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[a.length," fields"]})]}),l.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[l.jsx(m.Button,{size:"sm",variant:"outline",onClick:c,children:"Select All"}),l.jsx(m.Button,{size:"sm",variant:"outline",onClick:u,children:"Deselect All"}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," selected"]})]}),l.jsx("div",{className:"grid max-h-32 grid-cols-2 gap-2 overflow-y-auto rounded border p-2",children:a.map(d=>l.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded p-2 text-xs hover:bg-muted/50",children:[l.jsx(Ln,{checked:t.includes(d.id),onCheckedChange:f=>{n(f?[...t,d.id]:t.filter(h=>h!==d.id))}}),l.jsx("span",{className:"font-medium",children:d.label})]},d.id))}),o&&a.length===0&&l.jsxs("div",{className:"py-4 text-center text-sm text-muted-foreground",children:['No fields found matching "',o,'"']})]})}const pQe=e=>["string","boolean"].includes(m.getDataType(e.dataType));function mQe({interaction:e,availableFields:t,onUpdate:n}){var i;const r=t.filter(pQe),s=((i=e.availableFields)==null?void 0:i.map(a=>a.id))||[],o=a=>{const c=r.filter(u=>a.includes(u.id));n({...e,availableFields:c})};return l.jsx("div",{className:"space-y-4",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{children:"Available dimensions"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose which fields users can explore dynamically"}),l.jsx(hQe,{fields:r,selectedFieldIds:s,onSelectionChange:o,searchPlaceholder:"Search fields..."}),s.length===0&&l.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ Please select at least one field"})]})})}function gQe({value:e,onChange:t}){const[n,r]=v.useState(!1),[s,o]=v.useState(""),[i,a]=v.useState("all"),{currentUser:c}=ta(),{data:u,isLoading:d}=MF(Xr.DASHBOARD,s),f=(u==null?void 0:u.dashboards)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(c==null?void 0:c.id):!0),p=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),o("")};return l.jsxs(m.Popover,{open:n,onOpenChange:r,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsx(m.Button,{variant:"outline",className:m.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:p?l.jsx("span",{className:"truncate",children:p.title}):"Choose dashboard..."})}),l.jsx(m.PopoverContent,{className:"w-[500px] p-0",align:"start",children:l.jsxs(m.Tabs,{value:i,onValueChange:b=>a(b),children:[l.jsx("div",{className:"p-3 border-b",children:l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),l.jsx(m.Input,{placeholder:"Search all dashboards...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]})}),l.jsxs(m.TabsList,{className:"w-full justify-start rounded-none border-b bg-transparent p-0",children:[l.jsx(m.TabsTrigger,{value:"me",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"created by me"}),l.jsx(m.TabsTrigger,{value:"all",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"all"})]}),l.jsx(m.TabsContent,{value:i,className:"mt-0",children:l.jsx(m.ScrollArea,{className:"h-[300px]",children:d?l.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading dashboards..."}):h.length===0?l.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:s?`No dashboards found matching "${s}"`:i==="me"?"No dashboards created by you":"No dashboards available"}):l.jsx("div",{className:"p-2",children:h.map(b=>l.jsxs("button",{onClick:()=>g(b),className:m.cn("w-full flex items-start gap-3 p-3 rounded-md hover:bg-muted/50 transition-colors text-left",e===b.id&&"bg-muted"),children:[l.jsx(Rm,{className:"h-5 w-5 mt-0.5 text-muted-foreground flex-shrink-0"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"font-medium text-sm truncate",children:b.title}),l.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:bQe(b.createdAt)})]})]},b.id))})})})]})})]})}function bQe(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear()){const i=t.getHours(),a=t.getMinutes(),c=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${c}`}const s=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),o=t.getDate();return`${s} ${o}`}function xQe({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Target dashboard"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select which dashboard to navigate to when this interaction triggers"}),l.jsx(gQe,{value:e.targetDashboardId,onChange:(n,r)=>{const s={...e,targetDashboardId:n};!e.label&&r&&(s.label=r),t(s)}})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Propagate Filters"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose what filters to pass to the target dashboard"}),l.jsxs(m.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsxs(m.SelectValue,{placeholder:"Choose context mode...",children:[e.contextMode==="interactionFilters"&&"Interaction Filters",(e.contextMode==="full"||!e.contextMode)&&"All Filters",e.contextMode==="none"&&"None"]})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"interactionFilters",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"Interaction Filters"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass only the clicked element as a filter"})]})}),l.jsx(m.SelectItem,{value:"full",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"All Filters"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass current dashboard filters + clicked element"})]})}),l.jsx(m.SelectItem,{value:"none",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"None"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Navigate without passing any filters"})]})})]})]})]}),!e.targetDashboardId&&l.jsx("div",{className:"rounded-md bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3",children:l.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"⚠ Please select a target dashboard to complete this configuration"})}),e.targetDashboardId&&l.jsx("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:l.jsx("p",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Dashboard drill-through configured successfully"})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(m.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:tp(e.mode)}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function yQe({value:e,onChange:t}){const[n,r]=v.useState(!1),[s,o]=v.useState(""),[i,a]=v.useState("all"),{currentUser:c}=ta(),{data:u,isLoading:d}=MF(Xr.VISUAL,s),f=(u==null?void 0:u.visuals)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(c==null?void 0:c.id):!0),p=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),o("")};return l.jsxs(m.Popover,{open:n,onOpenChange:r,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsx(m.Button,{variant:"outline",className:m.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:p?l.jsx("span",{className:"truncate",children:p.title}):"Choose insight..."})}),l.jsx(m.PopoverContent,{className:"w-[500px] p-0",align:"start",children:l.jsxs(m.Tabs,{value:i,onValueChange:b=>a(b),children:[l.jsx("div",{className:"p-3 border-b",children:l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),l.jsx(m.Input,{placeholder:"Search all insights...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]})}),l.jsxs(m.TabsList,{className:"w-full justify-start rounded-none border-b bg-transparent p-0",children:[l.jsx(m.TabsTrigger,{value:"me",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"created by me"}),l.jsx(m.TabsTrigger,{value:"all",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"all"})]}),l.jsx(m.TabsContent,{value:i,className:"mt-0",children:l.jsx(m.ScrollArea,{className:"h-[300px]",children:d?l.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading insights..."}):h.length===0?l.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:s?`No insights found matching "${s}"`:i==="me"?"No insights created by you":"No insights available"}):l.jsx("div",{className:"p-2",children:h.map(b=>l.jsxs("button",{onClick:()=>g(b),className:m.cn("w-full flex items-start gap-3 p-3 rounded-md hover:bg-muted/50 transition-colors text-left",e===b.id&&"bg-muted"),children:[l.jsx(m.ChartColumn,{className:"h-5 w-5 mt-0.5 text-muted-foreground flex-shrink-0"}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"font-medium text-sm truncate",children:b.title}),l.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:vQe(b.createdAt)})]})]},b.id))})})})]})})]})}function vQe(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear()){const i=t.getHours(),a=t.getMinutes(),c=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${c}`}const s=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),o=t.getDate();return`${s} ${o}`}function wQe({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Target insight"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select the saved insight to navigate to"}),l.jsx(yQe,{value:e.targetInsightId,onChange:(n,r)=>{const s={...e,targetInsightId:n};!e.label&&r&&(s.label=r),t(s)}})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Propagate Filters"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose what filters to pass to the insight"}),l.jsxs(m.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsxs(m.SelectValue,{placeholder:"Choose context mode...",children:[e.contextMode==="interactionFilters"&&"Interaction Filters",(e.contextMode==="full"||!e.contextMode)&&"All Filters",e.contextMode==="none"&&"None"]})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"interactionFilters",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"Interaction Filters"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass only the clicked element as a filter"})]})}),l.jsx(m.SelectItem,{value:"full",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"All Filters"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass all current filters and selections"})]})}),l.jsx(m.SelectItem,{value:"none",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"None"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Open insight without any filters"})]})})]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Display mode"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose how the insight should be displayed"}),l.jsxs(m.Select,{value:e.displayMode||"modal",onValueChange:n=>t({...e,displayMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsx(m.SelectValue,{placeholder:"Choose display mode..."})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"modal",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"Open in modal"})})}),l.jsx(m.SelectItem,{value:"replace-card",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"Replace the card"})})})]})]})]}),!e.targetInsightId&&l.jsx("div",{className:"rounded-md bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3",children:l.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"⚠ Please enter a target insight ID to complete this configuration"})}),e.targetInsightId&&l.jsx("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:l.jsx("p",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Insight drill-through configured successfully"})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(m.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:tp(e.mode)}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function SQe(e){return e.filter(t=>t.role==="groupby"||t.role==="pivotby").map(t=>({id:t.name,label:t.label||t.name,category:"attribute",field:t}))}function CQe(){return[{id:"card_id",label:"Card ID",category:"identifier"},{id:"frame_id",label:"Frame ID",category:"identifier"},{id:"sheet_id",label:"Sheet ID",category:"identifier"}]}function NQe(e,t){const n=`{{${t}}}`;return e.includes(n)}function kQe(e,t){return t.filter(n=>NQe(e,n.id))}function _Qe(e,t,n){const r=`{{${t}}}`,s=e.slice(0,n)+r+e.slice(n),o=n+r.length;return{newTemplate:s,newCursorPosition:o}}function jQe(e,t){let n=e;return t.forEach(r=>{const s=`{{${r.id}}}`;let o;if(r.category==="identifier")o=`${r.id.toUpperCase()}-abc123`;else{const i=r.label.toLowerCase();i.includes("name")?o="Example Name":i.includes("region")||i.includes("location")?o="California":i.includes("id")?o="ID-12345":i.includes("category")?o="Category A":o="Sample Value"}n=n.replace(new RegExp(s,"g"),o)}),n}function EQe({open:e,onOpenChange:t,interaction:n,availableFields:r,onSave:s}){const[o,i]=v.useState(n.urlTemplate||""),[a,c]=v.useState(0),[u,d]=v.useState(n.encodeParameters!==!1),[f,h]=v.useState(n.label||""),p=v.useRef(null);v.useEffect(()=>{e&&(i(n.urlTemplate||""),d(n.encodeParameters!==!1),h(n.label||""),c(0))},[e,n.urlTemplate,n.encodeParameters,n.label]);const g=SQe(r),b=CQe(),x=[...g,...b],y=kQe(o,x),S=m.validateURLTemplate(o),w=o&&S.valid?jQe(o,y):"",C=j=>{i(j.target.value),c(j.target.selectionStart)},N=j=>{const I=j.target;c(I.selectionStart)},k=j=>{const I=j.target;c(I.selectionStart)},_=j=>{const{newTemplate:I,newCursorPosition:T}=_Qe(o,j.id,a);i(I),c(T),p.current&&(p.current.focus(),setTimeout(()=>{p.current&&p.current.setSelectionRange(T,T)},0))},E=()=>{S.valid&&(s({...n,urlTemplate:o,parameters:y,encodeParameters:u,label:f}),t(!1))},D=()=>{t(!1)};return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{className:"max-h-[90vh] max-w-5xl overflow-y-auto",onOpenAutoFocus:j=>{j.preventDefault(),setTimeout(()=>{var I;(I=p.current)==null||I.focus()},0)},children:[l.jsxs(na,{children:[l.jsx(go,{children:"Configure Drill to URL"}),l.jsx(si,{children:"Build a custom URL with dynamic parameters that will open when users click on chart elements."})]}),l.jsxs("div",{className:"flex flex-col gap-6 py-4",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[l.jsxs("div",{className:"flex flex-col gap-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(m.Label,{htmlFor:"url-template",children:"URL"}),l.jsx(m.TooltipProvider,{children:l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Info,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(m.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-xs",children:"Enter your URL and click parameters from the right panel to insert them. Parameters will be replaced with actual values when the URL is opened."})})]})})]}),l.jsx(Bh,{ref:p,id:"url-template",value:o,onChange:C,onClick:N,onKeyUp:k,placeholder:"https://example.com/product/{{product_id}}?region={{region}}",className:"min-h-[200px] font-mono text-sm"}),!S.valid&&o&&l.jsx("div",{className:"rounded-lg border border-destructive bg-destructive/10 p-3",children:l.jsx("div",{className:"text-sm text-destructive",children:S.errors.map((j,I)=>l.jsx("div",{children:j},I))})}),w&&l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-xs text-muted-foreground",children:"Preview:"}),l.jsx("div",{className:"rounded-md bg-muted p-3",children:l.jsx("p",{className:"break-all font-mono text-xs",children:w})})]})]}),l.jsxs("div",{className:"flex flex-col gap-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(m.Label,{children:"Parameters"}),l.jsx(m.TooltipProvider,{children:l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Info,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(m.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-xs",children:"Click any parameter to insert it into your URL at the cursor position. Attributes come from your chart data, Identifiers are system values."})})]})})]}),l.jsxs("div",{className:"flex flex-col gap-6 rounded-lg border p-4",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Attributes"}),l.jsxs("div",{className:"space-y-1",children:[g.map(j=>l.jsx(B7,{parameter:j,isUsed:y.some(I=>I.id===j.id),onClick:()=>_(j)},j.id)),g.length===0&&l.jsx("p",{className:"text-sm text-muted-foreground",children:"No attributes available"})]})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Identifiers"}),l.jsx("div",{className:"space-y-1",children:b.map(j=>l.jsx(B7,{parameter:j,isUsed:y.some(I=>I.id===j.id),onClick:()=>_(j)},j.id))})]})]})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ln,{id:"encode-params",checked:u,onCheckedChange:j=>d(j===!0)}),l.jsx(m.Label,{htmlFor:"encode-params",className:"cursor-pointer text-sm font-normal",children:"URL encode parameters"}),l.jsx(m.TooltipProvider,{children:l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Info,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(m.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-xs",children:"Recommended. Encodes special characters in parameter values to ensure valid URLs (e.g., spaces become %20)."})})]})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(m.TooltipProvider,{children:l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx(m.Info,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(m.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-xs",children:"How this interaction appears when multiple actions are available"})})]})})]}),l.jsx(m.Input,{value:f,onChange:j=>h(j.target.value),placeholder:tp("drillToURL")})]}),l.jsxs("div",{className:"flex items-start gap-2 rounded-lg border bg-muted/50 p-3",children:[l.jsx(m.Info,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"URLs will always open in a new browser tab when clicked."})]})]}),l.jsxs(Gc,{children:[l.jsx(m.Button,{variant:"outline",onClick:D,children:"Cancel"}),l.jsx(m.Button,{onClick:E,disabled:!S.valid,children:"Save"})]})]})})}function B7({parameter:e,isUsed:t,onClick:n}){var o,i;const r=e.category==="attribute"?"🏷️":"#",s=((o=e.field)==null?void 0:o.qualifiedFieldName)||((i=e.field)==null?void 0:i.name);return l.jsxs(m.Button,{type:"button",variant:"ghost",className:"h-auto w-full justify-start gap-2 px-3 py-2 font-normal hover:bg-accent",onClick:n,children:[l.jsx("span",{className:"text-base",children:r}),l.jsxs("div",{className:"flex flex-1 flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-sm",children:e.label}),s&&l.jsx("span",{className:"text-xs text-muted-foreground",children:s})]}),t&&l.jsx(Yr,{variant:"secondary",className:"ml-auto gap-1",children:l.jsx(m.Check,{className:"h-3 w-3"})})]})}function DQe({interaction:e,availableFields:t,onUpdate:n}){const[r,s]=v.useState(!1),o=!!e.urlTemplate;return l.jsxs("div",{className:"flex flex-col gap-4",children:[o?l.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border p-4",children:[l.jsxs("div",{className:"flex items-start justify-between gap-4",children:[l.jsxs("div",{className:"flex-1 space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Am,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{className:"text-sm font-medium",children:"URL Template"})]}),l.jsx("div",{className:"rounded-md bg-muted p-3",children:l.jsx("p",{className:"break-all font-mono text-xs",children:e.urlTemplate})})]}),l.jsxs(m.Button,{variant:"outline",size:"sm",onClick:()=>s(!0),children:[l.jsx(jk,{className:"mr-2 h-4 w-4"}),"Edit"]})]}),e.parameters&&e.parameters.length>0&&l.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.parameters.length," parameter",e.parameters.length!==1?"s":""," configured"]}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["URL encoding:"," ",e.encodeParameters!==!1?"enabled":"disabled"]})]}):l.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border border-dashed p-8",children:[l.jsx(Am,{className:"h-8 w-8 text-muted-foreground"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"No URL configured"}),l.jsx(m.Button,{variant:"outline",size:"sm",onClick:()=>s(!0),children:"Add Custom URL"})]}),l.jsx(EQe,{open:r,onOpenChange:s,interaction:e,availableFields:t,onSave:n})]})}function IQe({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Fetch mode"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose when to load the detailed data"}),l.jsxs(m.Select,{value:e.fetchMode||"lazy",onValueChange:n=>t({...e,fetchMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsx(m.SelectValue,{placeholder:"Choose fetch mode..."})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"lazy",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"Lazy loading"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Fetch data only when user clicks"})]})}),l.jsx(m.SelectItem,{value:"preloaded",children:l.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[l.jsx("span",{className:"font-medium",children:"Preloaded"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"Fetch all data when dashboard loads"})]})})]})]}),l.jsxs("div",{className:"rounded-md bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 p-3 flex gap-2",children:[l.jsx(m.Info,{className:"h-4 w-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0"}),l.jsx("div",{className:"text-xs text-blue-800 dark:text-blue-200",children:e.fetchMode==="lazy"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"font-medium",children:"Lazy loading"}),l.jsx("div",{className:"mt-1",children:"Data is fetched on-demand when the user clicks. Best for large datasets or when detailed data isn't always needed."})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"font-medium",children:"Preloaded"}),l.jsx("div",{className:"mt-1",children:"Data is fetched when the dashboard loads. Best for small datasets or when instant drill-down is required."})]})})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Record limit"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Maximum number of detailed records to show (0 for unlimited)"}),l.jsx(m.Input,{type:"number",min:"0",placeholder:"100",value:e.inlineLimit??100,onChange:n=>{const r=parseInt(n.target.value)||0;t({...e,inlineLimit:r})}})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Display mode"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"How to display the detailed records"}),l.jsxs(m.Select,{value:e.displayMode||"table",onValueChange:n=>t({...e,displayMode:n}),children:[l.jsx(m.SelectTrigger,{children:l.jsx(m.SelectValue,{placeholder:"Choose display mode..."})}),l.jsxs(m.SelectContent,{children:[l.jsx(m.SelectItem,{value:"table",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"Table view"})})}),l.jsx(m.SelectItem,{value:"list",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"List view"})})}),l.jsx(m.SelectItem,{value:"cards",children:l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("span",{children:"Card view"})})})]})]})]}),l.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 bg-background",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Show in modal"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Display detailed records in a modal overlay"})]}),l.jsx(m.Switch,{checked:e.showInModal??!1,onCheckedChange:n=>t({...e,showInModal:n})})]}),l.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 bg-background",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Allow export"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Enable users to export the detailed records"})]}),l.jsx(m.Switch,{checked:e.allowExport??!0,onCheckedChange:n=>t({...e,allowExport:n})})]}),l.jsxs("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:[l.jsx("div",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Inline drill configured successfully"}),l.jsxs("div",{className:"mt-2 space-y-1 text-xs text-green-700 dark:text-green-300",children:[l.jsxs("div",{children:["Mode: ",e.fetchMode==="lazy"?"Lazy loading":"Preloaded"]}),l.jsxs("div",{children:["Limit: ",e.inlineLimit===0?"Unlimited":`${e.inlineLimit} records`]}),l.jsxs("div",{children:["Display: ",e.displayMode==="table"?"Table view":e.displayMode==="list"?"List view":"Card view"]})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-sm font-medium",children:"Menu label"}),l.jsx(m.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:tp(e.mode)}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function TQe({interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i,onRemove:a}){const c=e.trigger!==void 0,u=e.mode!==void 0,d=c&&u,[f,h]=v.useState(!d),p=()=>{var y;if(!c)return"Configure interaction";const b=`When ${((y=e.trigger)==null?void 0:y.field.label)||"..."}`;if(!u)return`${b} → Choose action`;const x=e.label||tp(e.mode);return`${b} → ${x}`},g=u?UN(e.mode):null;return l.jsxs(Tm,{className:"relative p-0",children:[l.jsx(m.Button,{variant:"ghost",size:"sm",className:"absolute right-2 top-2 z-10 h-8 w-8 p-0",onClick:a,"aria-label":"Remove interaction",children:l.jsx(m.X,{className:"h-3 w-3"})}),l.jsxs(Vc,{open:f,onOpenChange:h,children:[l.jsx(Hc,{asChild:!0,children:l.jsxs(m.Button,{variant:"ghost",className:"h-auto w-full justify-between p-4 pr-12 hover:bg-muted/50",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[g&&l.jsx(g,{className:"h-4 w-4 flex-shrink-0"}),l.jsx("span",{className:"text-left text-sm font-medium",children:p()})]}),f?l.jsx(pF,{className:"h-3 w-3 flex-shrink-0"}):l.jsx(_k,{className:"h-3 w-3 flex-shrink-0"})]})}),l.jsx(Uc,{children:l.jsxs("div",{className:"space-y-6 border-t p-6",children:[l.jsx("div",{className:"space-y-3",children:c?l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"text-sm font-medium",children:["When I click on"," ",l.jsx("span",{className:"text-muted-foreground",children:"(value of)"})]}),e.trigger&&l.jsxs("div",{className:"inline-flex cursor-pointer items-center gap-2 rounded-md border bg-background px-3 py-2 hover:bg-muted/50",onClick:()=>{i({...e,trigger:void 0})},children:[WN(e.trigger.field.dataType),l.jsx("span",{className:"text-sm font-medium",children:e.trigger.field.label})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"text-sm font-medium",children:"When I click on"}),l.jsx(WKe,{value:e.trigger,onChange:b=>{i({...e,trigger:b})},metrics:t,attributes:n})]})}),c&&l.jsx(l.Fragment,{children:l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"text-sm font-medium",children:"I want to"}),l.jsx(qKe,{value:e.mode,onChange:b=>{if(!e.trigger){console.error("Trigger must be defined before selecting action");return}const x={mode:b,trigger:e.trigger};switch(b){case"clickFilter":i({...x,mode:"clickFilter",filterFields:[]});break;case"drillDown":i({...x,mode:"drillDown",filterFields:[]});break;case"dynamicDrill":i({...x,mode:"dynamicDrill",availableFields:[]});break;case"drillThrough":i({...x,mode:"drillThrough",filterFields:[],targetDashboardId:""});break;case"drillToDetail":i({...x,mode:"drillToDetail",filterFields:[]});break;case"drillToURL":i({...x,mode:"drillToURL",filterFields:[],urlTemplate:"",parameters:[],encodeParameters:!0});break;case"inlineDrill":i({...x,mode:"inlineDrill",filterFields:[]});break}}})]})}),c&&u&&l.jsxs(l.Fragment,{children:[l.jsx(m.Separator,{}),l.jsx(MQe,{interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i})]})]})})]})]})}function MQe({interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i}){switch(e.mode){case"clickFilter":return l.jsx(YKe,{interaction:e,onUpdate:a=>i(a)});case"drillDown":return l.jsx(fQe,{interaction:e,onUpdate:a=>i(a),card:s,availableFields:r,onUpdateHierarchies:o});case"dynamicDrill":return l.jsx(mQe,{interaction:e,onUpdate:a=>i(a),availableFields:r});case"drillThrough":return l.jsx(xQe,{interaction:e,onUpdate:a=>i(a)});case"drillToDetail":return l.jsx(wQe,{interaction:e,onUpdate:a=>i(a)});case"drillToURL":return l.jsx(DQe,{interaction:e,availableFields:[...t,...n],onUpdate:a=>i(a)});case"inlineDrill":return l.jsx(IQe,{interaction:e,onUpdate:a=>i(a)});default:return l.jsx("div",{className:"text-sm text-muted-foreground",children:"Unknown interaction type"})}}function AQe({interactions:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onChange:i}){const[a,c]=v.useState(null),u=()=>{const h=OGe().id,p={id:h};i([...e,p]),c(h)},d=(h,p)=>{const g=e[h],b={...p,id:p.id||(g==null?void 0:g.id)},x=[...e];x[h]=b,i(x)},f=h=>{var g;const p=e.filter((b,x)=>x!==h);i(p),a===((g=e[h])==null?void 0:g.id)&&c(null)};return l.jsxs("div",{className:"space-y-4",children:[e.length>0?l.jsx("div",{className:"space-y-3",children:e.map((h,p)=>l.jsx(TQe,{interaction:h,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:g=>d(p,g),onRemove:()=>f(p)},h.id||p))}):l.jsx("div",{className:"border rounded-lg p-8 text-center bg-muted/30",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"No interactions configured"}),l.jsx("div",{className:"text-xs text-muted-foreground",children:'Click "Add Interaction" to create your first interaction'}),l.jsx("div",{className:"pt-2",children:l.jsxs(m.Button,{onClick:u,size:"sm",variant:"outline",children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Add First Interaction"]})})]})}),e.length>0&&l.jsx("div",{className:"flex justify-start pt-2",children:l.jsxs(m.Button,{onClick:u,size:"sm",variant:"outline",children:[l.jsx(dr,{className:"mr-2 h-4 w-4"}),"Add Interaction"]})})]})}const RQe=[],FQe=[],PQe=[];function ST(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function OQe(e){return e.flatMap(t=>t.columns.map(n=>({...n,id:n.id||`${t.entityId}-${n.name}`,name:n.name,qualifiedFieldName:n.qualifiedFieldName||n.name,dataType:n.dataType,qualifiedEntityName:n.qualifiedEntityName||t.qualifiedEntityName,label:n.label||m.toTitleCase(n.name),description:n.description,entityId:n.entityId||t.entityId,entityName:n.entityName||t.entityName,entityType:n.entityType||t.entityType})))}function XL(e){var C;const{tokenProps:t}=Ct(),n=m.useDashboardStore(N=>N.authToken)||e,{selectedConnection:r,hasSchemaSupport:s}=FZ(e),o=m.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.connectionId}),i=m.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.semanticDomainId}),a=m.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.selectedEntities}),c=v.useMemo(()=>(a==null?void 0:a.filter(N=>N.type==="model"))||RQe,[a]),u=v.useMemo(()=>(a==null?void 0:a.filter(N=>m.DATABASE_ENTITY_TYPES.includes(N.type)))||FQe,[a]),d=v.useMemo(()=>(a==null?void 0:a.filter(N=>N.type==="dataset"))||PQe,[a]);function f(N){var k;if(N.type==="dataset")return!!o&&!!N.domainId&&!!N.name;if(N.type==="model")return!!o&&!!N.id;if(m.DATABASE_ENTITY_TYPES.includes(N.type)){const _=((k=r==null?void 0:r.capabilities)==null?void 0:k.path)||[],E=_.includes("database"),D=_.includes("schema")||s;return!(!o||!N.name||E&&!N.database||D&&!N.schema)}return!1}const h=[...c,...u,...d],p=hg({queries:h.map(N=>{let k={};return N.type==="model"?k=ST({connection_id:o,datamodel_id:N.id,database_name:"",schema_name:"",table_name:""}):N.type==="dataset"?k=ST({connection_id:N.connectionId,domain_id:N.domainId,dataset_name:N.name,database_name:N.database,schema_name:N.schema,table_name:N.table}):k=ST({connection_id:o,datamodel_id:"",database_name:N.database,schema_name:N.schema,table_name:N.name}),{queryKey:["columns",o,N,i||null],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",k),enabled:!!o&&f(N)}})}),g=p.some(N=>N.isPending&&N.fetchStatus==="fetching"),b=p.some(N=>N.isError),x=(C=p.find(N=>N.isError))==null?void 0:C.error,y=p.map((N,k)=>{var T,F;const _=h[k],E=((T=N.data)==null?void 0:T.columns)||[],D=_.type==="dataset"?(F=E.find(P=>P.entityName))==null?void 0:F.entityName:void 0,j=D||_.name,I=m.getQualifiedEntityName(_.type==="dataset"&&D?{..._,name:D}:_);return{entityId:_.id||_.name,entityType:_.type,entityName:j,label:_.label,description:_.description,qualifiedEntityName:I,columns:E.map(P=>{const R=_.type==="dataset"?P.entityName||j:_.name,B=P.qualifiedEntityName||(_.type==="dataset"&&R?m.getQualifiedEntityName({..._,name:R}):I);return{id:`${R}-${P.column_name}`,name:P.column_name,qualifiedFieldName:P.qualifiedFieldName||P.column_name,dataType:P.data_type,label:P.label||m.toLabel(P.column_name),description:P.description||"",qualifiedEntityName:B,entityId:P.entityId||_.id||_.id||R,entityName:R,entityType:P.entityType||_.type,role:P.role,expression:P.expression,calculatedFormula:P.calculatedFormula,format:m.fromSemanticFormat(P.format),aggregate:P.aggregate}})}}).filter(N=>{var k;return((k=N==null?void 0:N.columns)==null?void 0:k.length)>0})||[],S=p.flatMap(N=>{var k;return((k=N.data)==null?void 0:k.calculatedFields)||[]}).map(N=>({...N,id:m.getStableDomainCalculatedFieldId({...N}),fieldScope:"domain"}));if(S.length>0){const N=new Map;S.forEach(k=>{const _=m.getStableDomainCalculatedFieldId(k);N.has(_)||N.set(_,k)}),y.unshift({entityId:m.CALCULATED_FIELDS_GROUP_ID,entityType:"dataset",entityName:m.CALCULATED_FIELDS_GROUP_NAME,label:"Calculated Fields",description:"Domain-level calculated metrics and dimensions",qualifiedEntityName:m.CALCULATED_FIELDS_GROUP_NAME,columns:Array.from(N.values())})}const w=OQe(y);return{columnGroups:y,columns:w,isLoading:g,hasError:b,error:x,refetch:async()=>{await Promise.all(p.map(N=>N.refetch()))}}}function LQe(e){const t=n=>{if(!n||typeof n!="object")return!1;const r=n;return Array.isArray(r.cards)};if(!e)return null;if(typeof e=="string")try{const n=JSON.parse(e);return t(n)?n:null}catch{return null}return t(e)?e:null}function QN(e){return Array.isArray(e)?e.map(t=>QN(t)):e&&typeof e=="object"?Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).reduce((t,[n,r])=>(t[n]=QN(r),t),{}):e}function CT(e,t){return JSON.stringify(QN(e))===JSON.stringify(QN(t))}function $Qe(){var V,H,A,W,X,Z,J,re,fe;const{open:e,frameId:t,cardId:n,closePopover:r,anchorPosition:s}=TP(),{authToken:o,tokenProps:i}=Ct(),a=ns(),{updateCurrentDashboardCard:c,updateFrameCard:u}=m.useDashboardActions(),{setCard:d}=m.useEditorActions(),f=m.useDashboardStore(de=>de.dashboard),h=((V=f==null?void 0:f.sheets)==null?void 0:V.flatMap(de=>de.frames||[]).find(de=>(de==null?void 0:de.id)===t))||null,p=h&&n?h.cards.find(de=>de.id===n):null,g=!!(h!=null&&h.visualId&&p),b=Ak((h==null?void 0:h.visualId)||"",{enabled:e&&g&&!!(o!=null&&o.accessToken)&&!!(i!=null&&i.apiServiceUrl)}),x=((H=b.data)==null?void 0:H.frameObject)||((W=(A=b.data)==null?void 0:A.visual)==null?void 0:W.frameObject),y=v.useMemo(()=>LQe(x),[x]),S=((X=b.data)==null?void 0:X.lastModified)||((J=(Z=b.data)==null?void 0:Z.visual)==null?void 0:J.lastModified),w=v.useMemo(()=>{if(!p||!h||!y)return null;const de=p.linkedSourceCardId&&y.cards.find(ue=>ue.id===p.linkedSourceCardId);if(de)return de;const Se=h.cards.findIndex(ue=>ue.id===p.id);return Se>=0&&y.cards[Se]||null},[p,h,y]),C=v.useMemo(()=>{const de=new Map;return!h||!y||h.cards.forEach((Se,ue)=>{var xe;const ve=Se.linkedSourceCardId||((xe=y.cards[ue])==null?void 0:xe.id);ve&&de.set(ve,Se.id)}),de},[h,y]),N=v.useMemo(()=>{var Se;if(!w)return[];const de=of((Se=w.interactionConfig)==null?void 0:Se.interactions);return JS(de,C)},[w,C]),k=v.useMemo(()=>p?fT(N,p.linkedInteractionTargetOverrides):[],[p,N]),_=g?w:p,E=g&&!!x&&!y&&!b.isFetching;v.useEffect(()=>{if(!e)return;const de=g&&w||p;de&&d(de)},[e,g,w,p,d]);const{columns:D}=XL(),j=_==null?void 0:_.config,I=D,T=(j==null?void 0:j.metricColumns)||[],F=[...(j==null?void 0:j.groupByColumns)||[],...(j==null?void 0:j.pivotByColumns)||[]],[P,R]=v.useState(((re=_==null?void 0:_.interactionConfig)==null?void 0:re.drillHierarchies)||[]),[B,z]=v.useState(((fe=_==null?void 0:_.interactionConfig)==null?void 0:fe.allowedDrillTargets)||[]),[U,Y]=v.useState([]),[O,K]=v.useState(!1),q=v.useRef(null),M=v.useMemo(()=>`${e}-${t}-${n}-${g?(w==null?void 0:w.id)||"loading":(p==null?void 0:p.id)||"none"}`,[e,t,n,g,w==null?void 0:w.id,p==null?void 0:p.id]);v.useEffect(()=>{e||(q.current=null)},[e]),v.useEffect(()=>{var de,Se,ue;!e||!_||g&&!w||q.current!==M&&(R(((de=_.interactionConfig)==null?void 0:de.drillHierarchies)||[]),z(((Se=_.interactionConfig)==null?void 0:Se.allowedDrillTargets)||[]),Y(g?k:of((ue=_.interactionConfig)==null?void 0:ue.interactions)),q.current=M)},[e,_,M,g,w,k]);const G=async()=>{var de,Se,ue,ve,xe;if(p){K(!0);try{const ke=of(m.normalizeInteractionsForSave(U));if(!g||!(h!=null&&h.visualId)||!y||!w){const Xe={...p,interactionConfig:{...p.interactionConfig,drillHierarchies:P,allowedDrillTargets:B,interactions:ke}},et=(Se=(de=f==null?void 0:f.sheets)==null?void 0:de.find(tt=>(tt.frames||[]).some(me=>me.id===(h==null?void 0:h.id))))==null?void 0:Se.id;et&&(h!=null&&h.id)&&u?u(et,h.id,Xe):c(Xe),d(Xe),r();return}const se=of((ue=w.interactionConfig)==null?void 0:ue.interactions),be=FGe(ke,se),Ce=((ve=w.interactionConfig)==null?void 0:ve.drillHierarchies)||[],ge=((xe=w.interactionConfig)==null?void 0:xe.allowedDrillTargets)||[],ee=!CT(P,Ce)||!CT(B,ge)||!CT(be,se),te={...w,interactionConfig:{...w.interactionConfig,drillHierarchies:P,allowedDrillTargets:B,interactions:be}},ce={...y,cards:y.cards.map(Xe=>Xe.id===w.id?te:Xe)};if(ee){if(!(i!=null&&i.apiServiceUrl)||!(o!=null&&o.accessToken))throw new Error("Missing authentication context for visual update");const Xe=await fetch(`${i.apiServiceUrl}/management/v1/visuals/${h.visualId}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(o==null?void 0:o.accessToken)||""}`},body:JSON.stringify({frameObject:ce,expectedLastModified:S})});if(!Xe.ok){const tt=await Xe.json().catch(()=>({})),me=new Error((tt==null?void 0:tt.error)||"Failed to update visual");throw me.status=Xe.status,me}const et=await Xe.json();a.setQueryData(["resource-by-id","visual",h.visualId],et)}const le=JS(of(be),C),Ee=le.filter(Xe=>Xe.id).map(Xe=>Xe.id),ye=g7(PGe(ke,le),Ee),ne=fT(le,ye),je={...p,linkedSourceCardId:p.linkedSourceCardId||w.id,linkedInteractionTargetOverrides:ye,interactionConfig:{...p.interactionConfig,drillHierarchies:P,allowedDrillTargets:B,interactions:ne}},Ue=Xe=>{const et=new Map;return Xe.cards.forEach((tt,me)=>{var Ve;const Ye=tt.linkedSourceCardId||((Ve=y.cards[me])==null?void 0:Ve.id);Ye&&et.set(Ye,tt.id)}),et},Be=Xe=>{const et=Xe.cards.find(me=>me.linkedSourceCardId===w.id);if(et)return et;const tt=y.cards.findIndex(me=>me.id===w.id);return tt>=0&&Xe.cards[tt]||null},rt=[];if((f.sheets||[]).forEach(Xe=>{(Xe.frames||[]).forEach(et=>{if(et.visualId!==h.visualId)return;const tt=Be(et);if(!tt)return;const me=Ue(et),Ye=JS(of(be),me),Ve=Ye.filter(He=>He.id).map(He=>He.id),$e=et.id===h.id&&tt.id===p.id?ye:tt.linkedInteractionTargetOverrides,Ae=g7($e,Ve),Re=fT(Ye,Ae);rt.push({sheetId:Xe.id,frameId:et.id,isCurrentCard:et.id===h.id&&tt.id===p.id,card:{...tt,linkedSourceCardId:tt.linkedSourceCardId||w.id,linkedInteractionTargetOverrides:Ae,interactionConfig:{...tt.interactionConfig,drillHierarchies:P,allowedDrillTargets:B,interactions:Re}}})})}),rt.length>0&&u){rt.forEach(et=>{u(et.sheetId,et.frameId,et.card)});const Xe=rt.find(et=>et.isCurrentCard);Xe||c(je),d((Xe==null?void 0:Xe.card)||je)}else c(je),d(je);r()}catch(ke){ke.status===409?(ut.error("This saved visual was updated by another editor. Refresh and retry."),q.current=null,await b.refetch()):ut.error(ke.message||"Failed to save interactions")}finally{K(!1)}}},L=()=>{q.current=null,r()};if(!e||!t||!n||!p||!s)return null;const $={position:"fixed",left:`${s.left}px`,top:`${s.top}px`,width:`${s.width}px`,height:`${s.height}px`};return l.jsxs(m.Popover,{modal:!1,open:e,onOpenChange:de=>!de&&r(),children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsx("div",{style:$,className:"pointer-events-none invisible","aria-hidden":"true"})}),l.jsxs(m.PopoverContent,{onEscapeKeyDown:de=>de.preventDefault(),className:"mt-5 flex max-h-[70vh] w-[600px] max-w-4xl flex-col overflow-hidden p-0",align:"start",side:"right",sideOffset:20,children:[l.jsx(m.Arrow2,{className:"fill-border",width:12,height:8}),l.jsxs("div",{className:"flex flex-col border-b px-6 py-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h2",{className:"text-lg font-semibold",children:"Configure Interactions"}),U.length>0&&l.jsx(Yr,{variant:"default",className:"h-5 min-w-5 rounded-full px-1.5 text-xs",children:U.length})]}),l.jsxs("p",{className:"text-sm text-muted-foreground",children:["Set up drill behaviors for"," ",(p==null?void 0:p.title)||"this chart"]}),g&&l.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Logic is owned by the saved visual. Filter target routing is saved per dashboard instance."})]}),l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:l.jsx("div",{className:"space-y-6 p-6",children:g&&!w?l.jsx("p",{className:"text-sm text-muted-foreground",children:b.isFetching?"Loading saved visual interaction config...":E?"Unable to load interaction settings for this saved visual. Please refresh or relink the visual.":"Unable to map this dashboard card to its source card in the saved visual. Re-link the visual to continue."}):l.jsx("div",{children:l.jsx("div",{className:"grid grid-cols-1 gap-4",children:l.jsx(AQe,{interactions:U,metrics:T,attributes:F,availableFields:I,card:{..._||p,interactionConfig:{...(_==null?void 0:_.interactionConfig)||p.interactionConfig,drillHierarchies:P}},onUpdateHierarchies:R,onChange:de=>Y(de)})})})})}),l.jsxs("div",{className:"flex justify-end gap-2 border-t px-6 py-4",children:[l.jsx(m.Button,{variant:"outline",onClick:L,children:"Cancel"}),l.jsx(m.Button,{onClick:G,disabled:O||g&&!w,children:O?"Saving...":g?"Save to Library":"Accept"})]})]})]})}function bR(e,t){return Mo.serializeLayoutsForDirtyCheck(e)!==Mo.serializeLayoutsForDirtyCheck(t)}function zQe(e,t){return t&&bR(e,t)?t:null}function BQe(e){return!!e.expression}function VQe(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function HQe(e){const t=VQe(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function zae(e){return e.fieldScope==="domain"&&e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===m.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===m.CALCULATED_FIELDS_GROUP_NAME}function UQe(e){return zae(e)}function WQe(e){return e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||(e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card")&&HQe(e.id)&&!e.entityName}function bd(e){return BQe(e)?UQe(e)?"domain_calculated":WQe(e)?"user_calculated":"inline_expression":"none"}function fb(e){return bd(e)!=="none"}function ka(e){if(!fb(e))return!1;const t=bd(e);return t==="domain_calculated"||t==="user_calculated"?!0:e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card"}function Bae(e){return ka(e)&&e.fieldScope!=="card"}function Vae(e,t,n){return fb(e)?t==="editor"?!0:t==="filter"?ka(e)&&e.fieldScope!=="card":ka(e)&&(n==null?void 0:n.isValuePickSafe)!==!1:!1}function NT(e,t){return e.map(n=>({...n,fieldScope:t}))}function Hae(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=XL(),i=m.useEditorStore(_=>_.frame.calculatedFields),a=m.useEditorStore(_=>_.card.calculatedFields),c=m.useEditorStore(_=>_.card.config),u=m.useDashboardStore(_=>_.dashboard),d=m.useDashboardStore(_=>_.visualEditPendingDashboardCalculatedFields),f=m.useDashboardStore(_=>_.selectedSheetId),h=m.useDashboardStore(_=>_.selectedFrameId),p=m.useDashboardStore(_=>_.isVisualEditing),g=v.useMemo(()=>e.filter(_=>bd(_)==="domain_calculated"),[e]),b=v.useMemo(()=>e.filter(_=>bd(_)!=="domain_calculated"),[e]),x=v.useMemo(()=>{var E;if(p)return i||[];const _=(E=u==null?void 0:u.sheets)==null?void 0:E.find(D=>D.id===f);return m.getSheetCalculatedFields(_)},[u==null?void 0:u.sheets,i,p,h,f]),y=v.useMemo(()=>{const _=d??(u==null?void 0:u.calculatedFields)??[];return _.length?NT(_,"dashboard"):[]},[u==null?void 0:u.calculatedFields,d]),S=v.useMemo(()=>x.length?NT(x,"sheet"):[],[x]),w=v.useMemo(()=>m.buildCalculatedFieldComparableKeySet([...y,...S]),[y,S]),C=v.useMemo(()=>{const _=(a||[]).filter(T=>ka(T)&&T.fieldScope!=="domain"),E=((c==null?void 0:c.metricColumns)||[]).filter(T=>ka(T)&&T.fieldScope!=="domain"),D=((c==null?void 0:c.groupByColumns)||[]).filter(T=>ka(T)&&T.fieldScope!=="domain"),I=m.dedupeCalculatedFields([..._,...E,...D]).filter(T=>!w.has(m.getCalculatedFieldComparableKey(T)));return NT(I,"card").map(T=>({...T,id:`card-source-${T.id}`}))},[a,c==null?void 0:c.groupByColumns,c==null?void 0:c.metricColumns,w]),N=v.useMemo(()=>[...g,...y,...S,...C,...b],[C,b,y,g,S]),k=v.useMemo(()=>t.filter(_=>_.entityId!==m.CALCULATED_FIELDS_GROUP_ID),[t]);return{columns:e,columnGroups:k,rawColumnGroups:t,columnFields:b,domainCalculatedFields:g,dashboardCalculatedFields:y,sheetCalculatedFields:S,cardCalculatedFields:C,scopedFields:N,isLoading:n,hasError:r,error:s,refetch:o}}function qQe(e){const t="expression"in e&&e.expression||"",n=e.qualifiedEntityName||e.entityName||"",r=e.fieldScope||"unscoped",s=e.qualifiedFieldName||e.name;return t?["calculated",r,e.role||"field",n,s,t].join("::"):["calculated",r,e.role||"field",n,m.normalizeCalculatedFieldId(e.id)||s].join("::")}function YQe(e){return["physical",e.fieldScope||"physical",e.role||"field",e.qualifiedEntityName||"",e.qualifiedFieldName||e.name,e.name].join("::")}function Vp(e){const t=new Map;return e.forEach(n=>{const r=fb(n)?qQe(n):YQe(n);t.has(r)||t.set(r,n)}),Array.from(t.values())}function QL(e){return!Cr.isCalculatedMetric(e)}function kT(e,t){return Vp(e.filter(n=>Vae(n,t,{isValuePickSafe:QL(n)})))}function GQe(e){return!fb(e)||Vae(e,"inline-filter",{isValuePickSafe:QL(e)})}function KQe(e){return!fb(e)||Bae(e)}function Uae(){const e=Hae(),t=v.useMemo(()=>Vp(e.scopedFields),[e.scopedFields]),n=v.useMemo(()=>Vp([...e.columns,...e.dashboardCalculatedFields,...e.sheetCalculatedFields]),[e.columns,e.dashboardCalculatedFields,e.sheetCalculatedFields]),r=v.useMemo(()=>Vp(n.filter(KQe)),[n]),s=v.useMemo(()=>kT(t,"editor"),[t]),o=v.useMemo(()=>kT(n.filter(Bae),"filter"),[n]),i=v.useMemo(()=>Vp(t.filter(QL)),[t]),a=v.useMemo(()=>Vp(i.filter(GQe)),[i]),c=v.useMemo(()=>kT(a,"inline-filter"),[a]);return{...e,filterableFields:t,sharedFilterableFields:n,dashboardFilterableFields:r,inlineFilterableFields:a,scopedCalculatedFields:s,sharedCalculatedFields:o,inlineCalculatedFields:c,valuePickFilterableFields:i}}const Wae=Q.forwardRef(function({icon:t,label:n,asButton:r,disabled:s,labelWrapper:o,inQuery:i,trailing:a,kebab:c,showKebab:u,onKebabClick:d,selected:f,dragging:h,disableHover:p,className:g,...b},x){const y=l.jsx("span",{className:"block min-w-0 flex-1 truncate text-[13px] text-foreground/90",children:n}),S=m.cn("group/field-row relative flex h-7 items-center gap-2 px-4 transition-colors",h&&"opacity-40",f?"bg-muted":i?"bg-foreground/[0.06] hover:bg-foreground/[0.09]":!p&&"hover:bg-muted/60",r&&"w-full text-left disabled:cursor-not-allowed",g),w=l.jsxs(l.Fragment,{children:[t,o?o(y):y,i&&l.jsx("span",{className:"sr-only",children:"In query"}),a,(c||u)&&l.jsx("button",{type:"button","aria-label":"Field actions",onClick:C=>{C.stopPropagation(),d==null||d(C)},onPointerDown:C=>C.stopPropagation(),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:opacity-100 group-focus-within/field-row:opacity-100 [@media(hover:none)]:opacity-100",children:c??l.jsx(ja,{className:"h-3 w-3"})})]});return r?l.jsx("button",{ref:x,type:"button",disabled:s,"data-selected":f?"true":void 0,className:S,...b,children:w}):l.jsx("div",{ref:x,"data-selected":f?"true":void 0,className:S,...b,children:w})});function JL(e){const{tokenProps:t,authToken:n}=Ct(),r=t==null?void 0:t.apiServiceUrl;return On({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return m.getRequest(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function qae(e,t,n){if(t==="source")return{isValid:!0};const r=m.getDataType(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function Yae(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function ZQe(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const XQe=new Set(["COUNT","DISTINCT"]),QQe=new Set(["running_total","moving_average","previous_period_delta"]);function JQe(e){return m.getDataType(e.dataType||"")==="number"?!0:e.aggregate?XQe.has(e.aggregate.toUpperCase()):!1}function eJe(e,t){var r,s;return!!((s=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:s.function)}function e3(e,t){var n,r;return e==="aggregateTable"&&((((n=t.rowAggregates)==null?void 0:n.length)??0)>0||(((r=t.columnAggregates)==null?void 0:r.length)??0)>0)}function Gae({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,c;if(e==="detailTable"||e==="kpi")return{supported:!1,reason:"Metric transforms are not supported for this card type."};if((((i=t.groupByColumns)==null?void 0:i.length)??0)===0)return{supported:!1,reason:"Metric transforms require at least one grouped dimension."};if(!JQe(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const s=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,o=e==="pivotTable"||e3(e,t);return s&&!o?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:QQe.has(r)&&(((c=t.groupByColumns)==null?void 0:c.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function tJe(e){return e.find(t=>m.getDataType(t.dataType||"")==="date")}function nJe(e){return e}function vy({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(o=>o.id&&o.id!==n).map(o=>o.id),s=[];if(e==="pivotTable"||e3(e,t))for(const o of t.pivotByColumns||[])o.id&&s.push(o.id);return Array.from(new Set([...r,...s]))}function rJe({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const s=r||((i=tJe(n.groupByColumns||[]))==null?void 0:i.id),o=vy({cardType:t,cardConfig:n,orderByFieldId:s});return e==="moving_average"?{function:"moving_average",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,frame:"unbounded_preceding"}}const sJe=new Set(["table","aggregateTable","pivotTable","detailTable"]);function oJe(e){return e.alias||e.label||e.name}function Kae(e,t,n){var a,c,u;if(!e)return null;const r=m.fromSemanticFormat(t.format);if(!r)return null;const s=n||{};let o=s,i=!1;if(sJe.has(e.type)){const d=m.toColumnNumberFormat(r),f=oJe(t);if(d&&!((c=(a=s.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:c[f])){const p=so();o={...o,tablePrefs:{...o.tablePrefs||{},columnSettingsMap:{...((u=o.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...p,type:"number",textAlign:"right",numberFormat:{...p.numberFormat,...d}}}}},i=!0}if(!s.formatNumber){const h=m.toLegacyFormatNumber(r);h&&(o={...o,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?o:null}const Zae=e=>{var L;const t=(L=e==null?void 0:e.dataSource)==null?void 0:L.semanticDomainId,{data:n}=JL(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=m.useEditorActions(),p=m.useEditorStore($=>$.card.type),g=e==null?void 0:e.id,b=($,V)=>{if($.id)return $.id;const H=$.qualifiedEntityName||$.entityName||V;return`${V}-${H}-${$.name}`},x=v.useCallback($=>{if(!(e!=null&&e.config))return[];switch($){case"groupBy":return(e.config.groupByColumns||[]).map(V=>({...V,id:b(V,"groupBy"),label:V.label!==void 0?V.label:V.name}));case"metrics":return(e.config.metricColumns||[]).map(V=>({...V,id:b(V,"metrics"),label:V.label!==void 0?V.label:V.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map(V=>({id:b(V,"pivotBy"),name:V.name,dataType:V.dataType,label:V.label!==void 0?V.label:V.name,qualifiedEntityName:V.qualifiedEntityName,entityId:V.entityId,entityName:V.entityName,entityType:V.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(V=>({id:b(V,"sortBy"),name:V.name,dataType:V.dataType,label:V.label!==void 0?V.label:V.name,qualifiedEntityName:V.qualifiedEntityName,entityId:V.entityId,entityName:V.entityName,entityType:V.entityType,direction:V.direction}));case"detailColumns":return ZQe(e.config.detailColumns,V=>b(V,"detailColumns"));case"source":return[];default:return[]}},[e]),y=v.useCallback(($,V)=>{if(g)switch($){case"groupBy":{r(g,{groupByColumns:V});break}case"metrics":{r(g,{metricColumns:V});break}case"pivotBy":{r(g,{pivotByColumns:V});break}case"sortBy":{r(g,{sortByColumns:V});break}case"detailColumns":{r(g,{detailColumns:V});break}}},[g,r]),S=v.useCallback(($,V,H)=>{if(!g)return;const A=x($),W=A[V];if(W)switch($){case"groupBy":s(g,W.id,{label:H});break;case"metrics":o(g,W.id,{label:H});break;case"pivotBy":i(g,W.id,{label:H});break;case"sortBy":a(g,W.id,{label:H});break;case"detailColumns":{const X=A.map((Z,J)=>J===V?{...Z,label:H}:Z);r(g,{detailColumns:X});break}}},[g,x,s,o,i,a,r]),w=v.useCallback(($,V)=>{if(!g)return;const A=x("metrics")[$];A&&o(g,A.id,{aggregate:V,label:oee(A.name,V)})},[g,x,o]),C=v.useCallback(($,V,H,A="groupBy")=>{if(!g)return;const W=x(A),X=W[$];if(!X)return;const Z={dateFormat:V,customFormat:V==="custom"&&H?H:void 0};if(A==="detailColumns"){const J=W.map((re,fe)=>fe===$?{...re,...Z}:re);r(g,{detailColumns:J});return}s(g,X.id,Z)},[g,x,r,s]),N=v.useCallback(($,V)=>{if(!g)return;const A=x("groupBy")[$];A&&s(g,A.id,{granularity:V})},[g,x,s]),k=v.useCallback(($,V)=>{if(!g)return;const A=x("metrics")[$];A&&o(g,A.id,{aliasTemplate:V})},[g,x,o]),_=v.useCallback(($,V)=>{if(console.log("handleValueAliasesChange",$,V),!g)return;console.log("handleValueAliasesChange",$,V);const A=x("metrics")[$];A&&(console.log("handleValueAliasesChange",V),o(g,A.id,{valueAliases:V}))},[g,x,o]),E=v.useCallback(($,V)=>{var W,X;if(!g)return;const A=x("metrics")[$];A&&(o(g,A.id,{format:V}),p==="kpi"&&((X=(W=e==null?void 0:e.preferences)==null?void 0:W.kpiVisualOptions)!=null&&X.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,g,p,x,h,o]),D=v.useCallback(($,V)=>{var X;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=V!=="none"&&((X=A.parameters)==null?void 0:X.windowTransform);o(g,A.id,{comparisonType:V,...V!=="target"?{targetValue:void 0}:{},...W?{parameters:{...A.parameters||{},windowTransform:void 0}}:{}})},[g,x,o]),j=v.useCallback(($,V)=>{var fe,de,Se;if(!g||!(e!=null&&e.config))return;const A=x("metrics")[$];if(!A)return;if(V==="none"){o(g,A.id,{parameters:{...A.parameters||{},windowTransform:void 0}});return}const W=Gae({cardType:p,cardConfig:e.config,metric:A,transformMode:V});if(!W.supported){ut.error(W.reason||"Metric transform is not supported here.");return}const X=new Set((e.config.groupByColumns||[]).map(ue=>ue.id)),Z=(Se=(de=(fe=A.parameters)==null?void 0:fe.windowTransform)==null?void 0:de.orderBy)==null?void 0:Se.fieldId,J=Z&&X.has(Z)?Z:void 0,re=rJe({transformMode:V,cardType:p,cardConfig:e.config,fallbackOrderByFieldId:J});o(g,A.id,{comparisonType:"none",targetValue:void 0,parameters:{...A.parameters||{},windowTransform:re}})},[e,g,p,x,o]),I=v.useCallback(($,V)=>{var re,fe;if(!g||!(e!=null&&e.config))return;const A=x("metrics")[$];if(!A)return;const W=(re=A.parameters)==null?void 0:re.windowTransform;if(!W||!["running_total","moving_average","previous_period_delta"].includes(W.function))return;const X=vy({cardType:p,cardConfig:e.config,orderByFieldId:V}),J=(W.partitionByFieldIds||X).filter(de=>de!==V);o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,orderBy:{fieldId:V,direction:((fe=W.orderBy)==null?void 0:fe.direction)||"asc"},partitionByFieldIds:J}}})},[e,g,p,x,o]),T=v.useCallback(($,V)=>{var X;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(X=A.parameters)==null?void 0:X.windowTransform;!W||!["running_total","moving_average","previous_period_delta"].includes(W.function)||o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,orderBy:W.orderBy?{...W.orderBy,direction:V}:W.orderBy}}})},[g,x,o]),F=v.useCallback(($,V)=>{var J,re;if(!g||!(e!=null&&e.config))return;const A=x("metrics")[$];if(!A)return;const W=(J=A.parameters)==null?void 0:J.windowTransform;if(!W)return;const X=vy({cardType:p,cardConfig:e.config,orderByFieldId:(re=W.orderBy)==null?void 0:re.fieldId}),Z=new Set(W.partitionByFieldIds||X);Z.has(V)?Z.delete(V):Z.add(V),o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,partitionByFieldIds:Array.from(Z)}}})},[e,g,p,x,o]),P=v.useCallback(($,V)=>{var re,fe;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(re=A.parameters)==null?void 0:re.windowTransform;if(!W||W.function!=="moving_average")return;const X=Math.max(1,Math.floor(V||1)),Z=((fe=W.movingAverage)==null?void 0:fe.minPeriods)||1,J=Math.min(Z,X);o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,movingAverage:{windowSize:X,minPeriods:J}}}})},[g,x,o]),R=v.useCallback(($,V)=>{var J,re;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(J=A.parameters)==null?void 0:J.windowTransform;if(!W||W.function!=="moving_average")return;const X=((re=W.movingAverage)==null?void 0:re.windowSize)||7,Z=Math.max(1,Math.min(Math.floor(V||1),X));o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,movingAverage:{windowSize:X,minPeriods:Z}}}})},[g,x,o]),B=v.useCallback(($,V)=>{var X;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(X=A.parameters)==null?void 0:X.windowTransform;!W||W.function!=="previous_period_delta"||o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,previousPeriodDelta:{mode:V}}}})},[g,x,o]),z=v.useCallback(($,V)=>{var Z;if(!g||!(e!=null&&e.config))return;const A=x("metrics")[$];if(!A)return;const W=(Z=A.parameters)==null?void 0:Z.windowTransform;if(!W||W.function!=="percent_of_total")return;const X=V==="grand_total"?[]:(W.partitionByFieldIds||[]).length>0?W.partitionByFieldIds||[]:vy({cardType:p,cardConfig:e.config,orderByFieldId:void 0});o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,partitionByFieldIds:X,percentOfTotal:{...W.percentOfTotal||{},scope:V}}}})},[e,g,p,x,o]),U=v.useCallback(($,V)=>{var X;if(!g)return;const A=x("metrics")[$];if(!A)return;const W=(X=A.parameters)==null?void 0:X.windowTransform;!W||W.function!=="percent_of_total"||o(g,A.id,{parameters:{...A.parameters||{},windowTransform:{...W,percentOfTotal:{...W.percentOfTotal||{},output:V}}}})},[g,x,o]),Y=v.useCallback($=>{g&&r(g,{showTrendline:$})},[g,r]),O=v.useCallback($=>{g&&r(g,{trendlineWindow:$})},[g,r]),K=v.useCallback($=>{g&&r(g,{trendlineGranularity:$})},[g,r]),q=v.useCallback(($,V)=>{if(!g)return;const A=x("metrics")[$];A&&o(g,A.id,{targetValue:V})},[g,x,o]),M=v.useCallback(async $=>{var re;if(!g)return;const V=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy"),...x("detailColumns")],H=$,A=FFe(H,V,{joinPlan:(re=e==null?void 0:e.config)==null?void 0:re.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t,datasetAliases:n==null?void 0:n.datasets});if(!A.isValid){A.showError&&eee();return}const W=qFe(H,V,p);if(!W){ut.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const X=qae(H,W,p);if(!X.isValid){ut.error("Invalid Field Type",{description:X.reason,position:"top-center",duration:3e3});return}const Z=x(W);if(tee(H,Z))return;const J=iee(H,W,Z);if(J){const fe=[...Z,J];if(y(W,fe),W==="metrics"){const de=Kae(e,J,e==null?void 0:e.preferences);de&&h(de),Yae(p,e==null?void 0:e.config,r,g,fe)}}},[g,e,x,y,t,n,p,r,h]),G=v.useCallback(($,V)=>{if(!g)return;const A=x($)[V];if(A){if($!=="sortBy"){const W=x("sortBy"),X=W.filter(Z=>!(Z.name===A.name&&Z.qualifiedEntityName===A.qualifiedEntityName));X.length!==W.length&&r(g,{sortByColumns:X})}switch($){case"groupBy":c(g,A.id);break;case"metrics":u(g,A.id);break;case"pivotBy":d(g,A.id);break;case"sortBy":f(g,A.id);break;case"detailColumns":{r(g,{detailColumns:(x("detailColumns")||[]).filter((W,X)=>X!==V)});break}}}},[g,x,c,u,d,f,r]);return{getFieldsForContainer:x,setFieldsForContainer:y,updateLabel:S,handleAggregationChange:w,handleDateFormatChange:C,handleGranularityChange:N,handleAliasTemplateChange:k,handleValueAliasesChange:_,handleMetricFormatChange:E,removeField:G,handleFieldClick:M,handleMetricComparisonChange:D,handleMetricWindowTransformChange:j,handleMetricWindowOrderByChange:I,handleMetricWindowDirectionChange:T,handleMetricWindowPartitionToggle:F,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:R,handleMetricPreviousPeriodDeltaModeChange:B,handleMetricPercentOfTotalScopeChange:z,handleMetricPercentOfTotalOutputChange:U,handleKpiShowTrendlineChange:Y,handleKpiTrendlineWindowChange:O,handleKpiTrendlineGranularityChange:K,handleMetricTargetValueChange:q,cardType:p}};function Xae(e){var y;const{tokenProps:t}=Ct(),n=m.useDashboardStore(S=>S.authToken)||e,r=m.useEditorStore(S=>S.selectedConnectionId),s=m.useEditorStore(S=>S.selectedDatabaseName),o=m.useEditorStore(S=>S.selectedDatamodelId),i=m.useEditorStore(S=>S.selectedSchemaName),a=m.useEditorStore(S=>S.selectedTableName),{selectedConnection:c}=Xc(),u=c==null?void 0:c.type,{data:d,isLoading:f,isFetching:h,isError:p,refetch:g}=On({queryKey:["columns",r,s,o,i,a],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",{connection_id:r,datamodel_id:o||"",database_name:s,schema_name:i,table_name:a}),enabled:b(u)});function b(S){var _;if(!(n!=null&&n.accessToken))return!1;if(o&&o)return!0;if(!r||!S)return!1;const w=((_=c==null?void 0:c.capabilities)==null?void 0:_.path)||[],C=w.includes("database"),N=w.includes("schema"),k=w.includes("table");return!(C&&(!s||s==="NA")||N&&!i||k&&!a)}return{columns:(y=d==null?void 0:d.columns)==null?void 0:y.map(S=>({...S,data_type:S.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:p,refetchColumns:g}}function iJe(e){const t=m.useDashboardStore(g=>g.selectedLensId),n=m.useDashboardStore(g=>g.dashboard.filters),r=m.useFinalFilterGroupKey(e)||"",{cardFilterValues:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:c,queryRelevantConfig:u}=PO(e),d=c_([e],{authority:"editor",queryRelevantConfigsByCardId:{[e.id]:u}}).payload,f=hv({card:e,cardConfig:u,semanticExecutionPayload:d}),h=(e==null?void 0:e.sql)||"",{queryKey:p}=CP(e,{finalFiltersKey:r,selectedLensId:t,cardFilterValues:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:c,queryRelevantConfig:u,filters:n,resolvedPrimaryDateField:f});return{queryKey:p,sql:h,cardFilterValues:s,controlValues:o}}function Bj(e,t){var ne,je,Ue,Be,rt,Xe,et,tt;const{tokenProps:n}=Ct(),r=ns(),s=Ct().authToken||e,o=m.useEditorStore(me=>me.selectedConnectionId),i=m.useEditorStore(me=>me.card),{queryKey:a}=iJe(i),c=m.useEditorStore(me=>me.selectedDatamodelId),u=m.useEditorStore(me=>me.isDevMode),d=m.useEditorStore(me=>me.selectedDatabaseName),f=m.useEditorStore(me=>me.selectedSchemaName),h=m.useEditorStore(me=>me.selectedTableName),p=m.useEditorStore(me=>me.actions.setSelectedConnectionId),g=m.useEditorStore(me=>me.actions.setSelectedDatamodelId),b=m.useEditorStore(me=>me.actions.setSelectedDatabaseName),x=m.useEditorStore(me=>me.actions.setSelectedSchemaName),y=m.useEditorStore(me=>me.actions.setSelectedTableName);m.useEditorStore(me=>me.actions.setCardSql);const{setQueryConfig:S}=m.useEditorActions();function w(me){var Re;if(!o||!me)return!1;const Ye=((Re=D==null?void 0:D.capabilities)==null?void 0:Re.path)||[],Ve=Ye.includes("database"),$e=Ye.includes("schema");return!(!Ye.includes("table")||Ve&&(!d||d==="NA")||$e&&!f)}function C(me){var Ye;return!o||!me?!1:!!((Ye=D==null?void 0:D.capabilities)!=null&&Ye.path.includes("database"))}const{refetchConnections:N,connectionsData:k,isConnectionsLoading:_,isConnectionsError:E,selectedConnection:D}=Xc(e),{refetch:j,data:I,isLoading:T,isError:F}=On({queryKey:["models",o],queryFn:()=>m.getRequest(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),P=D==null?void 0:D.type,R=((ne=D==null?void 0:D.capabilities)==null?void 0:ne.path.includes("schema"))??!1,B=((je=D==null?void 0:D.capabilities)==null?void 0:je.path.length)===1&&((Ue=D==null?void 0:D.capabilities)==null?void 0:Ue.path[0])==="table",z=B,{data:U,isLoading:Y,isFetching:O,isError:K,refetch:q}=On({queryKey:["databases",o],queryFn:()=>m.getRequest(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:C(P)}),{data:M,isLoading:G,isFetching:L,isError:$,refetch:V}=On({queryKey:["schemas",o,d],queryFn:()=>m.getRequest(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&R&&d!=="NA"}),{data:H,isLoading:A,isFetching:W,isError:X,refetch:Z}=On({queryKey:["tables",o,d,f],queryFn:()=>m.getRequest(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:w(P)}),{columns:J,isColumnsLoading:re,isColumnsFetching:fe,isColumnsError:de,refetchColumns:Se}=Xae(e);v.useEffect(()=>{B&&(b(""),x(""),g(""),P==="API"&&y("api"))},[P,y,b,x,g,B]);const ue=(D==null?void 0:D.type)==="API"?(Be=D==null?void 0:D.type)==null?void 0:Be.toLowerCase():h||"",ve=R&&f||"";function xe(me){y(me),S(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function ke(me){x(me),y("")}function se(me){b(me==="none"?"":me),x(""),y(""),me!=="none"&&me!==""&&g("")}function be(me){p(me)}function Ce(me){g(me==="none"?"":me),me!=="none"&&me!==""&&b("")}U&&((rt=U==null?void 0:U.databases)==null?void 0:rt.length)>0,M&&((Xe=M==null?void 0:M.schemas)==null?void 0:Xe.length)>0;const ge=k==null?void 0:k.connections.map(me=>({id:me.id,name:me.name,type:me.type})),ee=(et=I==null?void 0:I.datamodels)==null?void 0:et.map(me=>({id:me.id,name:me.name})),te=U==null?void 0:U.databases.map(me=>({id:me.database_name,name:me.database_name})),ce=M==null?void 0:M.schemas.map(me=>({id:me.schema_name,name:me.schema_name})),le=H==null?void 0:H.tables.map(me=>({id:me.table_name,name:me.table_name})),Ee=(tt=I==null?void 0:I.datamodels.find(me=>me.id===c))==null?void 0:tt.name,ye=D!=null&&D.capabilities?m.getFormattedTableNameForQuery({schemaName:ve,tableName:ue,modelName:Ee,databaseName:d||"",capabilities:D.capabilities}):ue;return{connectionItems:ge,selectedConnectionId:o,selectedConnection:D,isConnectionsLoading:_,isConnectionsError:E,modelItems:ee,selectedDatamodelId:c,selectedDatamodelName:Ee,isModelsLoading:T,isModelsError:F,selectedDatabaseName:d,databaseItems:te,isDatabasesLoadingOrFetching:Y||O,isDatabaseError:K,schemaItems:ce,selectedSchemaName:f,isSchemaLoadingOrFetching:G||L,isSchemaError:$,tableItems:le,selectedTableName:h,isTableLoadingOrFetching:A||W,isTableError:X,columns:J,isColumnsLoadingOrFetching:re||fe,isColumnsError:de,isNonDbConnection:z,connectionType:P,tableName:ue,formattedTableName:ye,schemaName:ve,refetchConnections:N,refetchModels:j,refetchDatabases:q,refetchSchemas:V,refetchTables:Z,refetchColumns:Se,handleConnectionChange:be,handleDatamodelChange:Ce,handleDatabaseChange:se,handleSchemaChange:ke,handleTableChange:xe}}function nS(e){return`${e}-${m.v4()}`}function V7(e,t){const n=m.toTitleCase(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function aJe(e,t){const n=m.toTitleCase(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function t3(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return{tableName:void 0,schemaName:void 0,databaseName:void 0,connectionId:e==null?void 0:e.connectionId,connectionType:e==null?void 0:e.connectionType};const t=e.selectedEntities[0];return{tableName:t==null?void 0:t.name,schemaName:t==null?void 0:t.schema,databaseName:t==null?void 0:t.database,connectionId:e.connectionId,connectionType:e.connectionType}}function Qae(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Jae(){const e=m.useEditorStore(_=>_.sqlGen),t=m.useEditorStore(_=>_.isDevMode),n=m.useEditorStore(_=>_.card.dataSource),r=m.useEditorStore(_=>{var E,D;return(D=(E=_.card)==null?void 0:E.queryConfig)==null?void 0:D.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=t3(n),a=Qae(n),c=m.useEditorStore(_=>_.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:g}=m.useEditorActions(),{modelItems:b,selectedDatamodelName:x}=Bj(),{selectedConnection:y}=Xc(),S=y==null?void 0:y.capabilities,w=_=>({column_name:_.name,data_type:_.dataType,label:_.label,description:_.description});return{handleDevModeFieldClick:_=>{var D;if(!t)return;const E=w(_);if(t&&a&&s&&S){const j=m.createSqlGenConfig(E,e);p(j);const I=(D=b==null?void 0:b.find(F=>F.id===c))==null?void 0:D.name,T=m.getSql(j,o||"",s,I||"",i||"",S,_.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(m.isTextDataType(E.data_type))if(r&&r.length>0){const j={...E,role:"groupby",id:nS(E.column_name),name:E.column_name,type:E.data_type};d(j)}else{const j={...E,role:"metric",id:nS(E.column_name),name:E.column_name,label:V7(E.column_name,"COUNT"),type:E.data_type,aggregate:"COUNT"};u(j)}if(m.isDateDataType(E.data_type)){const j={...E,role:"groupby",id:nS(E.column_name),name:E.column_name,type:E.data_type,label:aJe(E.column_name,"month"),granularity:"month"};d(j)}if(m.isNumberDataType(E.data_type)){const j={...E,role:"metric",id:nS(E.column_name),name:E.column_name,label:V7(E.column_name,"SUM"),type:E.data_type,aggregate:"SUM"};u(j)}}},handleShowSample:()=>{if(!a||!s||!S){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=m.getFormattedTableNameForQuery({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:S});g(!1);const D=(y==null?void 0:y.type)==="MSSQL"?`SELECT top 10 * FROM ${_}`:`SELECT * FROM ${_} LIMIT 10`;f(D),h(!0)},handleShowCount:()=>{if(!a||!s||!S){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=m.getFormattedTableNameForQuery({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:S});f(`SELECT COUNT(*) as count FROM ${_}`),h(!0)},isNumberField:_=>m.isNumberDataType(_.dataType)}}function ele(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>m.fmt(o)).join("."),s=m.fmt(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function n3(e){const t=e;return{id:e.id,name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,fieldScope:e.fieldScope,expression:t.expression,calculatedFormula:t.calculatedFormula}}function r3(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function E0(e){var t,n;return e?!!(e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function H7(e){return e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e}function ug(e,t){var b,x,y,S,w,C,N;if(!e.fieldMeta)return e.column===t.qualifiedFieldName||e.column===t.name;const n=H7((b=e.fieldMeta)==null?void 0:b.id),r=H7(t.id),s=((x=e.fieldMeta)==null?void 0:x.qualifiedFieldName)||e.column,o=s===t.qualifiedFieldName||s===t.name,i=(y=e.fieldMeta)==null?void 0:y.qualifiedEntityName,a=!i||!t.qualifiedEntityName||i===t.qualifiedEntityName,c=(S=e.fieldMeta)==null?void 0:S.entityId,u=!c||!t.entityId||c===t.entityId,d=(w=e.fieldMeta)==null?void 0:w.fieldScope;if(d&&t.fieldScope&&d!==t.fieldScope)return!1;const f=(C=e.fieldMeta)==null?void 0:C.role;if(f&&t.role&&f!==t.role)return!1;const h=E0(e.fieldMeta)||E0(t);if(h&&n&&r&&n===r)return!0;if(!h&&(!a||!u))return!1;const p=(N=e.fieldMeta)==null?void 0:N.expression,g=t.expression;return p||g?o&&a&&u&&p===g:o&&a&&u}function lJe(){const e=m.useDashboardStore(c=>c.dashboard.filters)||[],t=m.useDashboardStore(c=>c.selectedSheetId),n=m.useDashboardStore(c=>c.actions.addFilter),r=m.useDashboardStore(c=>c.actions.removeFilter),{removeFilterValues:s}=m.useDashboardActions(),o=m.useEditorStore(c=>c.card.dataSource),{selectedConnection:i}=Xc();function a(c,u="sheet"){var g;const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=ele(c);let p;if(u==="sheet"&&t){const b=Nd(e,t);p=b.find(x=>x.fieldMeta&&ug(x,c))||xke(b.filter(x=>!x.fieldMeta),d,f,t)}else p=e==null?void 0:e.find(b=>ug(b,c)||!b.fieldMeta&&Vm(b.column)===Vm(d));if(p)s(p.id),r(p.id);else{const b=m.v4(),x=n3(c),y=r3(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),S=E0(x),w=!!((o==null?void 0:o.mode)==="semanticDomain"&&((g=y==null?void 0:y.selectedEntities)!=null&&g.length||y!=null&&y.semanticDomainId)),C=u==="sheet"&&t?[t]:void 0,N=m.getDataType(c.dataType)==="date"?"between":"in";return n({id:b,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:N,applyToSheetIds:C,sql:S||w?"":tL(c.dataType,f,h),fieldMeta:x,semanticContext:y}),b}}return{assignFilter:a}}function cJe({column:e}){const[t,n]=v.useState(!1),r=m.useEditorStore(w=>w.isDevMode),s=m.useEditorStore(w=>w.card.dataSource),{tableName:o,schemaName:i,databaseName:a}=t3(s),c=m.useEditorStore(w=>w.selectedDatamodelId),u=m.useEditorStore(w=>w.sqlGen),{modelItems:d,selectedConnection:f}=Bj(),h=f==null?void 0:f.capabilities,p=m.useEditorStore(w=>w.actions.setSqlGen),g=m.useEditorStore(w=>w.actions.setCardSql),b=m.useEditorStore(w=>w.actions.setRunSql),x=Qae(s);function y(w,C){var D,j;if(!x||!o){console.warn("Cannot generate SQL: missing table metadata");return}const N=m.createSqlGenConfig(w,u,C),k=(D=d==null?void 0:d.find(I=>I.id===c))==null?void 0:D.name;if(p(N),!h){console.warn("Cannot generate SQL: missing connection capabilities");return}const _=(j=w.qualifiedFieldName)==null?void 0:j.split(".").slice(0,-1).join("."),E=m.getSql(N,i||"",o,k||"",a||"",h,_);E&&(g(E),b(!0)),n(!1)}function S(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>y(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>y(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>y(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>y(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>y(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return!r||!x?null:l.jsxs(Pg,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Og,{asChild:!0,children:l.jsx(Lh,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(cd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:S()})]})}const U7="bg-emerald-500/90 text-white",uJe="bg-blue-500/90 text-white";function s3(e){const t=bd(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:U7}:{label:"fx",badgeClassName:e.role==="metric"?U7:uJe}}function dJe(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),e.prefix&&t.push({label:"Prefix",value:e.prefix}),e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const s=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:s})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function fJe(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,s)=>{const o=t[Number(s)];return o?`{${o.name||o.label}}`:r}):e.expression}function hJe({field:e,fieldState:t}){const n=fJe(e),r=dJe(e.format),s=!!s3(e);return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-start gap-1.5 px-3 pt-2.5",children:[l.jsx("span",{className:"flex h-[18px] shrink-0 items-center",children:l.jsx(Qv,{dataType:e.dataType,calculated:s})}),l.jsx("p",{className:"min-w-0 flex-1 break-words text-[13px] font-semibold leading-[18px] text-foreground",children:e.label||e.name})]}),l.jsx("div",{className:"px-3 pb-2 pt-0.5",children:l.jsx("code",{className:"font-mono text-[11px] text-muted-foreground",children:e.dataType})}),e.description&&l.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[12px] leading-[1.55] text-muted-foreground",children:e.description}),n&&l.jsxs("div",{className:"border-t border-border/60 bg-muted/40 px-3 py-2",children:[l.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Expression"}),l.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-[11px] leading-[1.55] text-foreground/90",children:n})]}),r.length>0&&l.jsxs("div",{className:"border-t border-border/60 px-3 py-2",children:[l.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Format"}),l.jsx("dl",{className:"grid grid-cols-[64px_1fr] gap-x-3 gap-y-1 text-[11px]",children:r.map(o=>l.jsxs("div",{className:"contents",children:[l.jsx("dt",{className:"font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o.label}),l.jsx("dd",{className:"truncate font-mono tabular-nums text-foreground/90",children:o.value})]},`${o.label}-${o.value}`))})]}),t&&t.tooltip&&l.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[11px] text-muted-foreground",children:t.tooltip}),l.jsx("div",{className:"border-t border-border/60 px-3 py-2",children:l.jsx("code",{className:"block break-all font-mono text-[11px] leading-[1.45] text-muted-foreground",children:e.name})})]})}function W7({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o,onHover:i}){const a=m.useEditorStore(W=>W.isDevMode),c=t==="inline-filter"||t==="document-filter",u=t==="filter"||c,d=a||u||(n==null?void 0:n.state)==="unreachable"&&!u,f=m.useDashboardStore(W=>W.dashboard.filters),h=m.useDashboardStore(W=>W.selectedSheetId),p=m.useDashboardStore(W=>W.actions.removeFilter),{removeFilterValues:g}=m.useDashboardActions(),{assignFilter:b}=lJe(),x=t==="filter"?Nd(f,h):f,y=t==="filter"?x==null?void 0:x.find(W=>{if(ug(W,e))return!0;if(W.fieldMeta)return!1;const X=Vm(W.column||""),Z=Vm(e.name);return X.endsWith(`.${Z}`)||X===Z}):void 0,S=!!y,w=c&&(s==null?void 0:s.some(W=>ug(W,e))),C=S||w,N=y&&u?f==null?void 0:f.find(W=>W.id===y.id):void 0,k=N&&(N.applyToSheetIds&&N.applyToSheetIds.length>1||N.excludeSheetIds&&N.excludeSheetIds.length>0||!N.applyToSheetIds&&!N.excludeSheetIds&&!N.sheetId),[_,E]=v.useState(!1),[,D]=v.useState(null),{attributes:j,listeners:I,setNodeRef:T,transform:F,transition:P,isDragging:R}=db({id:e.id,disabled:d}),B=m.useEditorStore(W=>W.card),{handleFieldClick:z}=Zae(B),{handleDevModeFieldClick:U,isNumberField:Y}=Jae(),O=()=>{N&&(console.log("[SourceField] Removing multi-sheet filter:",N.id),g(N.id),p(N.id)),D(null),E(!1)},K=()=>{if(c&&r){r(e);return}t==="filter"?C&&k?(D(e),E(!0)):b(e,"sheet"):a?U(e):z(e)},q={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},M={transform:_i.Transform.toString(F),transition:P};function G(W){return W==="domain"?{label:"Semantic domain",Icon:kme}:W==="sheet"?{label:"Sheet",Icon:Rm}:W==="dashboard"?{label:"Dashboard",Icon:Rm}:{label:"Card",Icon:Eq}}const L=s3(e),$=e.fieldScope,V=$&&!L?G($):null,H=(n==null?void 0:n.state)==="unreachable",A=(n==null?void 0:n.state)==="indirect";return l.jsxs(l.Fragment,{children:[l.jsx(Wae,{ref:T,style:M,...d?{}:j,...d?{}:I,onClick:K,onMouseEnter:W=>i==null?void 0:i(!0,W.currentTarget),onMouseLeave:()=>i==null?void 0:i(!1),title:n==null?void 0:n.tooltip,selected:S,dragging:R,disableHover:H,inQuery:!u&&!!(n!=null&&n.isSelected),icon:l.jsx(Qv,{dataType:e.dataType,calculated:!!L}),label:e.label||e.name,trailing:l.jsxs(l.Fragment,{children:[a&&!u&&Y(e)&&l.jsx("span",{onClick:W=>W.stopPropagation(),onPointerDown:W=>W.stopPropagation(),children:l.jsx(cJe,{column:q})}),o?l.jsx("span",{className:"pointer-events-none inline-flex items-center opacity-0 transition-opacity group-hover/field-row:pointer-events-auto group-hover/field-row:opacity-100 group-focus-within/field-row:pointer-events-auto group-focus-within/field-row:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",onClick:W=>W.stopPropagation(),onPointerDown:W=>W.stopPropagation(),children:o}):t==="editor"?l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Field actions",onClick:W=>W.stopPropagation(),onPointerDown:W=>W.stopPropagation(),className:"pointer-events-none inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:pointer-events-auto group-hover/field-row:opacity-100 group-focus-within/field-row:pointer-events-auto group-focus-within/field-row:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",children:l.jsx(ja,{className:"h-3 w-3"})})}),l.jsx(fo,{align:"end",className:"w-44",children:l.jsx(jn,{onClick:W=>{W.stopPropagation(),navigator.clipboard.writeText(e.name).then(()=>{ut.success(`Copied "${e.name}"`)}).catch(()=>{ut.error("Could not copy field name")})},children:"Copy field name"})})]}):null,t==="editor"&&V&&l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx("span",{"aria-label":`${V.label} calculated field`,className:"inline-flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",onClick:W=>W.stopPropagation(),onPointerDown:W=>W.stopPropagation(),children:l.jsx(V.Icon,{className:"h-3 w-3"})})}),l.jsxs(m.TooltipContent,{side:"top",align:"end",children:[V.label," calculated field"]})]})]}),className:m.cn((a||u)&&"cursor-pointer",!d&&!a&&!u&&"cursor-grab active:cursor-grabbing",H&&"cursor-not-allowed opacity-50",A&&"text-muted-foreground/80",w&&"bg-primary/10 hover:bg-primary/15")}),l.jsx(Lc,{open:_,onOpenChange:E,children:l.jsxs(vl,{children:[l.jsxs(wl,{children:[l.jsx(Cl,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Nl,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Sl,{children:[l.jsx(_l,{children:"Cancel"}),l.jsx(kl,{onClick:O,children:"Remove Filter"})]})]})})]})}var za="Accordion",pJe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[o3,mJe,gJe]=m.createCollection(za),[Vj]=m.createContextScope(za,[gJe,mie]),i3=mie(),tle=v.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return l.jsx(o3.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?l.jsx(vJe,{...o,ref:t}):l.jsx(yJe,{...s,ref:t})})});tle.displayName=za;var[nle,bJe]=Vj(za),[rle,xJe]=Vj(za,{collapsible:!1}),yJe=v.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,c]=m.useControllableState({prop:n,defaultProp:r??"",onChange:s,caller:za});return l.jsx(nle,{scope:e.__scopeAccordion,value:v.useMemo(()=>a?[a]:[],[a]),onItemOpen:c,onItemClose:v.useCallback(()=>o&&c(""),[o,c]),children:l.jsx(rle,{scope:e.__scopeAccordion,collapsible:o,children:l.jsx(sle,{...i,ref:t})})})}),vJe=v.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=m.useControllableState({prop:n,defaultProp:r??[],onChange:s,caller:za}),c=v.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=v.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return l.jsx(nle,{scope:e.__scopeAccordion,value:i,onItemOpen:c,onItemClose:u,children:l.jsx(rle,{scope:e.__scopeAccordion,collapsible:!0,children:l.jsx(sle,{...o,ref:t})})})}),[wJe,Hj]=Vj(za),sle=v.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=v.useRef(null),c=m.useComposedRefs(a,t),u=mJe(n),f=m.useDirection(s)==="ltr",h=m.composeEventHandlers(e.onKeyDown,p=>{var E;if(!pJe.includes(p.key))return;const g=p.target,b=u().filter(D=>{var j;return!((j=D.ref.current)!=null&&j.disabled)}),x=b.findIndex(D=>D.ref.current===g),y=b.length;if(x===-1)return;p.preventDefault();let S=x;const w=0,C=y-1,N=()=>{S=x+1,S>C&&(S=w)},k=()=>{S=x-1,S<w&&(S=C)};switch(p.key){case"Home":S=w;break;case"End":S=C;break;case"ArrowRight":o==="horizontal"&&(f?N():k());break;case"ArrowDown":o==="vertical"&&N();break;case"ArrowLeft":o==="horizontal"&&(f?k():N());break;case"ArrowUp":o==="vertical"&&k();break}const _=S%y;(E=b[_].ref.current)==null||E.focus()});return l.jsx(wJe,{scope:n,disabled:r,direction:s,orientation:o,children:l.jsx(o3.Slot,{scope:n,children:l.jsx(m.Primitive.div,{...i,"data-orientation":o,ref:c,onKeyDown:r?void 0:h})})})}),JN="AccordionItem",[SJe,a3]=Vj(JN),ole=v.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=Hj(JN,n),i=bJe(JN,n),a=i3(n),c=m.useId(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return l.jsx(SJe,{scope:n,open:u,disabled:d,triggerId:c,children:l.jsx(xie,{"data-orientation":o.orientation,"data-state":dle(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});ole.displayName=JN;var ile="AccordionHeader",ale=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Hj(za,n),o=a3(ile,n);return l.jsx(m.Primitive.h3,{"data-orientation":s.orientation,"data-state":dle(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});ale.displayName=ile;var xR="AccordionTrigger",lle=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Hj(za,n),o=a3(xR,n),i=xJe(xR,n),a=i3(n);return l.jsx(o3.ItemSlot,{scope:n,children:l.jsx(PYe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});lle.displayName=xR;var cle="AccordionContent",ule=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Hj(za,n),o=a3(cle,n),i=i3(n);return l.jsx(OYe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});ule.displayName=cle;function dle(e){return e?"open":"closed"}var CJe=tle,NJe=ole,kJe=ale,fle=lle,hle=ule;const l3=CJe,D0=Q.forwardRef(({className:e,...t},n)=>l.jsx(NJe,{ref:n,className:m.cn("border-b",e),...t}));D0.displayName="AccordionItem";const I0=Q.forwardRef(({className:e,children:t,...n},r)=>l.jsx(kJe,{className:"flex",children:l.jsxs(fle,{ref:r,className:m.cn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,l.jsx(m.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));I0.displayName=fle.displayName;const T0=Q.forwardRef(({className:e,children:t,...n},r)=>l.jsx(hle,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:l.jsx("div",{className:m.cn("pb-4 pt-0",e),children:t})}));T0.displayName=hle.displayName;let ple=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const Uj=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",insertTemplate:()=>"({a} + {b})",insertHint:"A + B",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",insertTemplate:()=>"({a} - {b})",insertHint:"A − B",requiresTwoInputs:!0},{id:"product",label:"Product",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",insertTemplate:()=>"({a} * {b})",insertHint:"A × B",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",insertTemplate:()=>"({a} / NULLIF({b}, 0))",insertHint:"A ÷ B (null-safe)",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",insertTemplate:()=>"(({b} - {a}) / NULLIF({a}, 0))",insertHint:"% change A → B",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",insertTemplate:()=>"(({a} / NULLIF({b}, 0)) * 100)",insertHint:"(A ÷ B) × 100",requiresTwoInputs:!0},{id:"scale",label:"Scale",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",insertTemplate:()=>"({a} * 1.0)",insertHint:"A × constant",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],_Je=Uj.filter(e=>e.id!=="custom"&&!!e.insertTemplate),c3=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),ek=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function mle(e,t){e.forEach(n=>{var i;const r=n.id||n.qualifiedFieldName||n.name;if(r&&t.visited.has(r))return;if(r&&t.visited.add(r),zae(n)){t.disqualified=!0;return}const s=(i=n.calculatedFormula)==null?void 0:i.inputFields;if(s!=null&&s.length){mle(s,t);return}if(n.expression&&!(bd(n)==="inline_expression"&&ka(n)&&n.fieldScope==="domain")){t.disqualified=!0;return}if(!n.entityName||!n.entityId){t.disqualified=!0;return}const o=n.qualifiedEntityName||n.entityId||n.entityName;t.entities.has(o)||t.entities.set(o,{entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName})})}function u3(e){const t={entities:new Map,disqualified:!1,visited:new Set};if(mle(e,t),t.disqualified||t.entities.size!==1)return{kind:"multi-entity"};const[n]=Array.from(t.entities.values());return!(n!=null&&n.entityName)||!n.entityId?{kind:"multi-entity"}:{kind:"inline",entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName}}const q7="calculated_fields";function jJe(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function EJe(e){return e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===q7||e.qualifiedEntityName===q7||jJe(e.id)}function DJe(e){return e.aggregate?e.aggregate:AO(e.dataType)}function IJe(e,t){const n=DJe(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function TJe(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const s=Number(r),o=t[s];return!o||EJe(o)||typeof o.expression=="string"&&nee(o.expression)?n:IJe(n,o)})}function MJe(e,t,n,r,s,o,i,a,c,u){if(!Uj.find(S=>S.id===t))throw new Error(`Unknown operation: ${t}`);let f,h=[],p;{if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}const g={operation:t,inputFields:h,...p!==void 0},b=c3(e),x=u3(h);return{id:i||`calc_${ple(10)}`,name:b,label:e,alias:b,qualifiedFieldName:b,dataType:"number",role:"metric",expression:f,calculatedFormula:g,entityId:x.kind==="inline"?x.entityId:o,entityName:x.kind==="inline"?x.entityName:Cr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:x.kind==="inline"?x.qualifiedEntityName:void 0,entityType:x.kind==="inline"?"dataset":"table",description:`Calculated field: ${e}`}}function AJe(e){var r,s;const t=Uj.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function RJe(e,t,n,r,s,o){const i=c3(e),a=u3(n);return ree({id:o||`calc_dim_${ple(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(c=>c.role==="metric"?{...c,role:"metric"}:{...c,role:"groupby"})},entityId:a.kind==="inline"?a.entityId:s,entityName:a.kind==="inline"?a.entityName:Cr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:a.kind==="inline"?a.qualifiedEntityName:void 0,entityType:a.kind==="inline"?"dataset":"table",description:`Calculated field: ${e.trim()}`})}function gle(e){return e==="metric"?"Calculated Metric":"Calculated Column"}function FJe(e){return e==="inline"?"Single dataset":"Cross-entity"}function $x(e){switch(e){case"card":return"This card";case"sheet":return"This sheet";case"dashboard":return"This dashboard";case"domain":return"Semantic domain"}}function Y7(e){return e.replace(/\s+/g,"")}function PJe(e){var s;const t=e.calculatedFormula;if(!t||t.operation==="custom")return;const n=Uj.find(o=>o.id===t.operation),r=(s=n==null?void 0:n.template)==null?void 0:s.call(n);if(r)return t.operation!=="scale"?r:r.replace("{constant}",String(t.constant??1))}function OJe(e){var r;const t=e.expression||"",n=PJe(e);return!n||Y7(t)!==Y7(n)?t:TJe(t,((r=e.calculatedFormula)==null?void 0:r.inputFields)||[])}function LJe(e){const t=new Set,n=/\{field_(\d+)\}/g;let r=n.exec(e);for(;r;)t.add(Number(r[1])),r=n.exec(e);return[...t].sort((s,o)=>s-o)}function $Je(e){var o;const t=e.expression||"",n=LJe(t);if(n.length===0)return{readOnly:!1};const r=((o=e.calculatedFormula)==null?void 0:o.inputFields)||[];return n[n.length-1]<r.length?{readOnly:!1}:{readOnly:!0,reason:"This legacy metric uses saved field tokens but is missing the input metadata needed to reopen it safely. It can be viewed, but editing is disabled to avoid changing query semantics."}}function zJe(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function BJe(e){var r;const t=new Map;return(((r=e==null?void 0:e.calculatedFormula)==null?void 0:r.inputFields)||[]).forEach(s=>{const o=ek(s.id);o&&t.set(o,s),s.qualifiedFieldName&&t.set(s.qualifiedFieldName,s),s.name&&t.set(s.name,s)}),t}function VJe(e,t){const n=ek(e.id);return n&&t.get(n)||e.qualifiedFieldName&&t.get(e.qualifiedFieldName)||t.get(e.name)}function HJe(e){const t=AO(e.dataType);if(e.role==="metric"){const n=e;return n.aggregate||n.expression||n.calculatedFormula?n:{...n,aggregate:t}}return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}}function UJe(e,t){const n=BJe(t);return e.map(r=>{const s=VJe(r,n);return(s==null?void 0:s.role)==="metric"?s:HJe(r)})}function WJe({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:s,targetQualifiedEntityName:o}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=bd(i);if(r==="inline"){const c=m.getCalculatedFieldNamespace(i),u=o||s;return a==="inline_expression"&&!!u&&c===u}return a==="domain_calculated"})}function qJe({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(c=>s.includes(c)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return l.jsx(m.Tabs,{value:a,onValueChange:c=>t(c),className:"w-fit shrink-0",children:l.jsx(m.TabsList,{size:"xs",children:o.map(c=>l.jsx(m.TabsTrigger,{value:c,disabled:i,children:gle(c)},c))})})}const d3=Q.forwardRef(({className:e,sideOffset:t=8,...n},r)=>l.jsx(m.Portal$2,{children:l.jsx(sb,{children:l.jsx(m.Content2$1,{ref:r,sideOffset:t,className:m.cn("z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})})}));d3.displayName="ValidationTooltipContent";const ble=m.Arrow2$1;function _T(e,t){return`${e} ${t}${e===1?"":"s"}`}function YJe({result:e}){const t=e.errors.length>0,n=_T(e.tokens.length,"token"),r=e.errors.length>0?_T(e.errors.length,"error"):null,s=e.warnings.length>0?_T(e.warnings.length,"warning"):null,o=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
1301
1301
  `);return l.jsxs(m.Tooltip,{delayDuration:120,children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":t?"Validation failed. Hover to view details.":"Validation passed. Hover to view details.",className:m.cn("inline-flex h-5 w-5 items-center justify-center rounded-full transition-colors",t?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-emerald-600 text-white hover:bg-emerald-700"),children:t?l.jsx(m.X,{className:"h-3 w-3","aria-hidden":!0}):l.jsx(m.Check,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(d3,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[l.jsxs("div",{className:"space-y-2.5 p-3 text-xs",children:[l.jsx("div",{className:m.cn("font-semibold",t?"text-destructive":"text-emerald-700"),children:t?"Validation failed":"Validation passed"}),l.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:n}),r&&l.jsx("span",{children:r}),s&&l.jsx("span",{children:s}),e.inferredDataType&&l.jsxs("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&l.jsxs("div",{className:"space-y-1.5 border-t pt-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),l.jsx("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((i,a)=>l.jsxs("div",{className:"flex items-start gap-1.5",children:[l.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${i.token}}`}),l.jsx(Sk,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),i.field?l.jsx("span",{className:"break-all text-muted-foreground",children:i.field.qualifiedFieldName||i.field.name}):l.jsx("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${i.token}-${a}`))})]}),e.errors.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),l.jsx(Ac,{text:o,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.warnings.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-amber-700 select-text",children:e.warnings.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.inferredDataType&&l.jsxs("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),l.jsx(ble,{className:"fill-popover"})]})]})}function GJe({onValidate:e,isValidating:t,validationResult:n,error:r,disabled:s}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(m.Button,{type:"button",variant:"outline",size:"xs",onClick:e,disabled:t||s,className:"text-[11px]",children:t?"Validating…":"Validate"}),n&&l.jsx(YJe,{result:n}),!n&&r&&l.jsxs(m.Tooltip,{delayDuration:120,children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Validation failed. Hover to view details.",className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90",children:l.jsx(m.X,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(d3,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-semibold text-destructive",children:"Validation failed"}),l.jsx(Ac,{text:r,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:r})]}),l.jsx(ble,{className:"fill-popover"})]})]})]})}const KJe={metric:["Average revenue per order","Profit margin %","Active customers last 30 days"],dimension:["Order month from created_at","Bucket revenue into 'Large' / 'Small'","Country and state combined"]};function ZJe({mode:e,fieldType:t,prompt:n,onPromptChange:r,generated:s,explanation:o,isGenerating:i,error:a,onGenerate:c,onTryAgain:u,onCancel:d,onUseDraft:f,disabled:h}){const p=e==="result",g=e==="loading"||i,b=KJe[t],x=t==="metric"?"e.g. average revenue per order, in dollars":"e.g. bucket orders into 'Large' / 'Small' by amount";return l.jsxs("div",{"data-testid":"ai-compose-panel","data-mode":e,className:"rounded-[6px] border border-blue-200 bg-blue-50/40 dark:border-blue-900/40 dark:bg-blue-950/20",children:[l.jsxs("div",{className:"flex items-center gap-2 border-b border-blue-200/60 px-3 py-2 dark:border-blue-900/30",children:[l.jsx(Fm,{className:"h-3 w-3 text-blue-600 dark:text-blue-400","aria-hidden":!0}),l.jsx("span",{className:"text-[11px] font-medium text-zinc-900 dark:text-zinc-100",children:p?"AI draft — ready to use":"Compose with AI"}),l.jsx("span",{className:"text-[10px] text-zinc-500 dark:text-zinc-400",children:p?"Review before using.":"Describe in plain English. AI knows your fields."}),l.jsx("button",{type:"button","aria-label":"Close AI compose",onClick:d,disabled:h,className:"ml-auto text-blue-700/70 hover:text-blue-900 disabled:opacity-50 dark:text-blue-300/70 dark:hover:text-blue-100",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"space-y-2 p-3",children:p?l.jsxs(l.Fragment,{children:[n.trim()&&l.jsxs("div",{className:"flex items-start gap-1.5 rounded-[4px] bg-white px-2 py-1.5 text-[11px] dark:bg-zinc-950",children:[l.jsx("span",{className:"shrink-0 text-zinc-400",children:"›"}),l.jsxs("span",{className:"italic text-zinc-600 dark:text-zinc-400",children:["“",n.trim(),"”"]})]}),l.jsx("div",{className:"overflow-hidden rounded-[5px] border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950",children:l.jsx("div",{className:"max-h-[180px]",children:l.jsx(m.CodeEditor,{value:s,language:"sql-jinja",readOnly:!0,embedded:!0,hideLineNumbers:!0,dense:!0,ariaLabel:"Generated expression"})})}),o?l.jsx("p",{className:"text-[11px] text-zinc-500 dark:text-zinc-400",children:o}):null]}):l.jsxs(l.Fragment,{children:[l.jsx(m.Label,{htmlFor:"ai-compose-prompt",className:"sr-only",children:"Describe what you want to calculate"}),l.jsx(Bh,{id:"ai-compose-prompt",value:n,onChange:y=>r(y.target.value),placeholder:x,rows:2,disabled:g||h,className:"resize-none border-zinc-200 bg-white text-[13px] text-zinc-900 shadow-none placeholder:text-zinc-400 focus:border-zinc-400 focus-visible:ring-0 disabled:opacity-60 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50"}),!g&&l.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[l.jsx("span",{className:"mr-1 text-[10px] uppercase tracking-[0.08em] text-zinc-400",children:"Try"}),b.map(y=>l.jsx("button",{type:"button",onClick:()=>r(y),disabled:h,className:"inline-flex h-5 items-center rounded-[4px] border border-zinc-200 bg-white px-1.5 text-[11px] text-zinc-600 hover:bg-zinc-50 hover:text-zinc-900 disabled:opacity-50 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-400 dark:hover:bg-zinc-900 dark:hover:text-zinc-100",children:y},y))]}),a&&l.jsx("p",{className:"whitespace-pre-wrap text-[11px] text-destructive",children:a})]})}),l.jsx("div",{className:"flex items-center justify-end gap-1.5 border-t border-blue-200/60 px-3 py-2 dark:border-blue-900/30",children:p?l.jsxs(l.Fragment,{children:[l.jsx(m.Button,{type:"button",variant:"outline",size:"xs",onClick:u,disabled:h,children:"Try again"}),l.jsx(m.Button,{type:"button",variant:"outline",size:"xs",onClick:d,disabled:h,children:"Cancel"}),l.jsx(m.Button,{type:"button",size:"xs",onClick:f,disabled:h||!s.trim(),children:"Use draft"})]}):l.jsxs(l.Fragment,{children:[l.jsx(m.Button,{type:"button",variant:"outline",size:"xs",onClick:d,disabled:h,children:"Cancel"}),l.jsx(m.Button,{type:"button",size:"xs",onClick:c,disabled:g||h||!n.trim(),className:m.cn("gap-1.5",g&&"pointer-events-none"),children:g?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin","aria-hidden":!0}),"Generating…"]}):l.jsxs(l.Fragment,{children:[l.jsx(Fm,{className:"h-3 w-3","aria-hidden":!0}),"Generate"]})})]})})]})}function XJe({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,c=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const p=f.toLowerCase(),g=h.toLowerCase();return p.startsWith(`${g}.`)?f.slice(h.length+1):f},d=(f,h)=>{const g=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),b=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const x of b){const y=u(g,x);if(y!==g)return y}return g.includes(".")&&g.split(".").pop()||g};return l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2",children:[a&&l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[l.jsx(Ws,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("input",{type:"text",value:t,onChange:f=>n(f.target.value),placeholder:"Search fields",className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),t&&l.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>n(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),l.jsx(zl,{className:"min-h-0 flex-1",children:e.length===0?l.jsx("div",{className:"rounded-[5px] border border-dashed border-border px-3 py-6 text-center text-[12px] text-muted-foreground",children:"No fields match your search."}):l.jsx(l3,{type:"multiple",defaultValue:c,className:"space-y-1",children:e.map(f=>l.jsxs(D0,{value:f.id,className:"border-none",children:[l.jsx(I0,{className:"group flex w-full items-center gap-1.5 rounded-[4px] px-1.5 py-1.5 text-left hover:bg-muted hover:no-underline [&>svg]:order-first [&>svg]:h-3 [&>svg]:w-3 [&>svg]:-rotate-90 [&>svg]:text-muted-foreground/70 data-[state=open]:[&>svg]:rotate-90",children:l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l.jsx("span",{className:"max-w-[180px] truncate text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:f.label}),l.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:f.fields.length})]})}),l.jsx(T0,{className:"pb-1",children:l.jsx("div",{children:f.fields.map(h=>{const p=i.has(h.id),g=!h.isCompatible||o,b=d(h,f.label);return l.jsx(Wae,{asButton:!0,disabled:g,icon:l.jsx(Qv,{dataType:h.dataType,calculated:h.isCalculated}),label:b,selected:p,disableHover:g,onClick:()=>{r(h)},className:m.cn(g?"cursor-not-allowed opacity-50":"cursor-pointer"),trailing:p?l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Selected"}):void 0},h.id)})})})]},f.id))})})]})}function QJe({groups:e,searchTerm:t,onSearchTermChange:n,onFieldSelect:r,selectedFieldIds:s,disabled:o}){const[i,a]=v.useState(!1);return l.jsxs(m.Popover,{open:i,onOpenChange:a,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsxs(m.Button,{type:"button",variant:"outline",size:"xs",disabled:o,className:"gap-1.5",children:[l.jsx(dr,{className:"h-3 w-3","aria-hidden":!0}),"Insert field"]})}),l.jsx(m.PopoverContent,{align:"end",sideOffset:6,className:"z-[51] w-[320px] max-w-[min(320px,calc(100vw-32px))] p-2",children:l.jsx("div",{className:"flex h-[360px] min-h-0 flex-col",children:l.jsx(XJe,{groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:c=>{r(c),a(!1)},selectedFieldIds:s,disabled:o})})})]})}function JJe({onInsert:e,disabled:t}){return l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsxs(m.Button,{type:"button",variant:"outline",size:"xs",disabled:t,className:"gap-1.5",children:["Templates",l.jsx(m.ChevronDown,{className:"h-3 w-3","aria-hidden":!0})]})}),l.jsx(fo,{align:"end",className:"w-[300px]",children:_Je.map(n=>{var r;return l.jsxs(jn,{onSelect:s=>{var i;s.preventDefault();const o=(i=n.insertTemplate)==null?void 0:i.call(n);o&&e(o)},className:"flex items-start justify-between gap-3 py-2",children:[l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"font-mono text-[12px] text-muted-foreground",children:n.symbol}),l.jsx("span",{className:"text-[12px] font-medium",children:n.label})]}),l.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-muted-foreground",children:(r=n.insertTemplate)==null?void 0:r.call(n)})]}),n.insertHint?l.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:n.insertHint}):null]},n.id)})})]})}const eet="Calculated fields";function tet(e){var t;if(e.kind==="inline"){const n=(t=e.entityName)==null?void 0:t.trim();if(n)return`${n} dataset`}return eet}function net({fieldType:e,inlineAnalysis:t,availability:n,hasInputFields:r=!0}){const s=[{label:"Type",value:gle(e)}];return e==="metric"&&s.push({label:"Compute",value:"After aggregation"}),r&&(s.push({label:"Uses",value:FJe(t.kind)}),s.push({label:"Stored with",value:tet(t)})),s.push({label:"Available in",value:$x(n)}),s}function ret(e){const t=net(e);return l.jsxs("div",{className:"flex items-center justify-between gap-3 border-t bg-muted/40 px-5 py-2","data-testid":"calculated-field-summary-ribbon",children:[l.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:t.map(n=>l.jsxs("span",{className:"inline-flex items-baseline gap-1.5 rounded-[4px] border bg-background px-1.5 py-0.5 text-[11px]",children:[l.jsx("span",{className:"text-[9px] font-medium uppercase tracking-[0.06em] text-muted-foreground/80",children:n.label}),l.jsx("span",{className:"text-foreground",children:n.value})]},n.label))}),l.jsx("span",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"Derived"})]})}function set(e){var r;const t=m.getRequestErrorMessage(e,"AI generation failed"),n=(r=m.getRequestErrorViolations(e))==null?void 0:r[0];return n?n.hint?`${n.message} Hint: ${n.hint}`:n.message||t:t}function oet({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=Ct(),[o,i]=v.useState(!1),[a,c]=v.useState(null),u=v.useCallback(async f=>{var h;if(!e)return c("AI generation is not available"),null;if(!f.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const p={type:"calculated-field-expression",context:{userQuery:f,availableFields:t.map(b=>({name:b.tokenLabel,dataType:b.dataType,...b.role==="metric"||b.role==="groupby"?{role:b.role}:{}})),fieldType:n},options:{dialect:r}},g=await m.postRequestRegular(e,(s==null?void 0:s.accessToken)||"",p);if(!g.success||!((h=g.result)!=null&&h.generated))throw new Error(g.error||"No expression generated");return{generated:g.result.generated,explanation:g.result.explanation}}catch(p){return c(set(p)),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),d=v.useCallback(()=>c(null),[]);return{generateExpression:u,isGenerating:o,error:a,resetError:d}}const iet=/\{([^}]+)\}/g;function Wj(e){return e.trim().toLowerCase()}function xle(e){return Array.from(e.matchAll(iet)).map(t=>t[1]).filter(Boolean)}function aet(e){const t=new Set,n=[];return e.forEach(r=>{const s=Wj(r);t.has(s)||(t.add(s),n.push(r))}),n}function f3(e){const t=new Map,n=(r,s)=>{const o=Wj(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function tC(e,t){const n=xle(e),r=aet(n),s=f3(t),o=r.map(a=>{const c=s.get(Wj(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!o[c]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function yR(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${cet(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function cet(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const uet=e=>e.entityName===m.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===m.CALCULATED_FIELDS_GROUP_NAME||e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER?"Calculated Fields":e.qualifiedEntityName?m.toLabel(e.entityName||e.qualifiedEntityName):m.toLabel(e.entityName||"Other");function det(e){return e.entityName===m.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===m.CALCULATED_FIELDS_GROUP_NAME||e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER?m.CALCULATED_FIELDS_GROUP_NAME:e.qualifiedEntityName||e.entityName||"Other"}function fet(e){return e.role!=="metric"?!1:e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===Cr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===m.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===m.CALCULATED_FIELDS_GROUP_NAME}function het(e,t){const n=new Set((t||[]).map(r=>ek(r)));return e.filter(r=>{const s=ek(r.id);return!(s&&n.has(s))})}function pet(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==Cr.CALCULATED_FIELD_ENTITY_MARKER?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function met(e,t,n,r){return t==="dimension"?e.map(s=>({...s,isCompatible:!fet(s)})).filter(s=>r):t!=="metric"?e.map(s=>({...s,isCompatible:!0})):e.map(s=>({...s,isCompatible:!0}))}function get(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function bet(e){const t=new Map;return e.forEach(n=>{var s;const r=det(n);t.has(r)||t.set(r,{id:r,label:uet(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function xet({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=v.useMemo(()=>het(e,r),[e,r]),a=v.useMemo(()=>pet(i),[i]),c=v.useMemo(()=>i.map(g=>{const b=g.label||g.name,x=g.role==="metric"&&Cr.isCalculatedMetric(g)||g.role==="groupby"&&Cr.isCalculatedDimension(g);return{...g,baseLabel:b,tokenLabel:a.get(g.id)||b,isCalculated:x,isCompatible:!0}}),[i,a]),u=v.useMemo(()=>met(c,t,s,o),[c,t,s,o]),d=v.useMemo(()=>get(u,n),[u,n]),f=v.useMemo(()=>u.filter(g=>g.isCompatible),[u]),h=v.useMemo(()=>f3(f),[f]),p=v.useMemo(()=>bet(d),[d]);return{allFields:c,filteredFields:d,groups:p,tokenCandidates:h,tokenFields:f}}const yet=e=>m.getDataType(e.dataType||"")==="number",G7=e=>yet(e)?"SUM":"COUNT",vet=e=>{if(e.role==="metric"){const n=e;return{...n,aggregate:n.aggregate||G7(e)}}const t=G7(e);return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}},wet=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1)return m.getDataType(((r=t[0])==null?void 0:r.dataType)||"")}};function Cet({expression:e,availableFields:t,validationEndpoint:n,connectionId:r,dialect:s,fieldType:o,outputType:i,validationContext:a}){const{authToken:c}=Ct(),[u,d]=v.useState(null),[f,h]=v.useState(!1),[p,g]=v.useState(null),b=v.useMemo(()=>f3(t),[t]),x=v.useMemo(()=>xle(e).map(N=>{const k=b.get(Wj(N))||[];return{token:N,field:k.length===1?k[0]:null}}),[e,b]),y=v.useCallback((C,N)=>{const k=[{code:"SQL_VALIDATION_ERROR",message:C,suggestion:(N==null?void 0:N.suggestion)||(N==null?void 0:N.errorCode)}];return{isValid:!1,tokens:x,errors:k,warnings:[]}},[x]),S=v.useCallback(async()=>{var P;g(null);const C=n==null?void 0:n.trim();if(!C){const R=y("Validation endpoint is not configured");return d(R),R}if(!!!(a!=null&&a.cardConfig&&(a!=null&&a.cardDataSource)&&(a!=null&&a.cardId)&&(a!=null&&a.connectionId||r))){const R=y("Validation context is incomplete for server-side validation");return d(R),R}const{orderedTokens:k,orderedFields:_}=tC(e,t),E=[],D=[];k.forEach((R,B)=>{const z=_[B];z&&(E.push(R),D.push(z))});const j=o==="metric"?D.map(vet):D,I=wet(e,D),T=yR(e,E),F={type:"calculated-field-expression",fieldType:o,expression:T,inputFields:j,outputType:i,options:{validateWithExplain:!0},context:{connectionId:(a==null?void 0:a.connectionId)||r,cardId:a==null?void 0:a.cardId,cardConfig:a==null?void 0:a.cardConfig,cardDataSource:a==null?void 0:a.cardDataSource,activeFilters:(a==null?void 0:a.activeFilters)||[],cardType:(a==null?void 0:a.cardType)||"table",dialect:s}};h(!0);try{const R=await m.postRequestRegular(C,(c==null?void 0:c.accessToken)||"",F),B=R==null?void 0:R.status,z=R==null?void 0:R.error,U=R==null?void 0:R.errorCode,Y=[],O=[];B==="invalid"?Y.push({code:"SQL_VALIDATION_ERROR",message:z||"Expression failed SQL validation",suggestion:U?`Validation code: ${U}`:void 0}):B==="unverified"?O.push({code:"EXECUTION_UNVERIFIED",message:z||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):B!=="valid"&&Y.push({code:"SQL_VALIDATION_ERROR",message:z||"Unexpected SQL validation response from server",suggestion:U?`Validation code: ${U}`:void 0});const K={isValid:(B==="valid"||B==="unverified")&&Y.length===0,tokens:x,errors:Y,warnings:O,inferredDataType:(R==null?void 0:R.inferredDataType)??((P=R==null?void 0:R.metadata)==null?void 0:P.inferredDataType)??I??i??void 0};return d(K),K}catch(R){const B=(R==null?void 0:R.error)||(R==null?void 0:R.message)||"Expression validation failed";g(B);const z=y(B);return d(z),z}finally{h(!1)}},[n,a,r,e,t,o,i,s,c==null?void 0:c.accessToken,y,x]),w=v.useCallback(()=>{d(null),g(null)},[]);return{validationResult:u,isValidating:f,serverError:p,validateExpression:S,resetValidation:w}}const K7=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],Net=[],ket="https://docs.semaphor.cloud/docs/concepts/calculated-fields/metrics",_et="https://docs.semaphor.cloud/docs/concepts/calculated-fields/dimensions",jet="SUM({revenue}) / NULLIF(COUNT({order_id}), 0)",Eet="DATE_TRUNC('month', {created_at})";function yle({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToSheet:i,onSaveToDashboard:a,cardId:c,initialFieldType:u="metric",allowedFieldTypes:d}){var wt;const{tokenProps:f}=Ct(),{selectedConnection:h}=FZ(),p=m.useEditorStore(Pe=>{var St;return(St=Pe.card)==null?void 0:St.config}),g=m.useEditorStore(Pe=>{var St;return(St=Pe.card)==null?void 0:St.dataSource}),b=m.useEditorStore(Pe=>{var St;return(St=Pe.card)==null?void 0:St.type}),y=m.useEditorStore(Pe=>Pe.filterValues)??Net,[S,w]=v.useState(u),[C,N]=v.useState(""),[k,_]=v.useState(""),[E,D]=v.useState(null),[j,I]=v.useState("card"),[T,F]=v.useState({}),[P,R]=v.useState(""),[B,z]=v.useState(!1),[U,Y]=v.useState(""),[O,K]=v.useState(""),[q,M]=v.useState(void 0),[G,L]=v.useState(null),[$,V]=v.useState(!1),[H,A]=v.useState(!1),[W,X]=v.useState(null),Z=v.useId(),J=v.useRef(!1),re=v.useRef(null),{userContext:fe}=ta(),de=v.useMemo(()=>n.filter(Pe=>Pe.fieldScope==="domain"&&!!Pe.expression),[n]),Se=v.useMemo(()=>de.filter(Pe=>Pe.role==="metric"),[de]),ue=v.useMemo(()=>de.filter(Pe=>Pe.role==="groupby"),[de]),xe=!((fe==null?void 0:fe.type)==="organization"),ke=!!W,se=xe||ke,be=!!i,Ce=!!a,ge=(wt=f==null?void 0:f.apiServiceUrl)==null?void 0:wt.replace(/\/$/,""),ee=ge?`${ge}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",te=ge?`${ge}/v1/ai/generate`:"/v1/ai/generate",ce=v.useMemo(()=>{var pe;const Pe=[...n];return(((pe=r==null?void 0:r.calculatedFormula)==null?void 0:pe.inputFields)||[]).forEach(Oe=>{Pe.some(It=>It.id===Oe.id||It.qualifiedFieldName===Oe.qualifiedFieldName||It.name===Oe.name)||Pe.push(Oe)}),Pe},[n,r]),{tokenFields:le,groups:Ee}=xet({fields:ce,mode:S,searchTerm:P,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:void 0,showIncompatible:!0}),ye=le,{generateExpression:ne,isGenerating:je,error:Ue,resetError:Be}=oet({endpoint:te,availableFields:ye,fieldType:S,dialect:h==null?void 0:h.dialect}),rt=je?"loading":O?"result":"prompt",{validationResult:Xe,validateExpression:et,isValidating:tt,serverError:me,resetValidation:Ye}=Cet({expression:k,availableFields:ye,validationEndpoint:ee,connectionId:h==null?void 0:h.id,dialect:h==null?void 0:h.dialect,fieldType:S,outputType:E||void 0,validationContext:{connectionId:(h==null?void 0:h.id)||(g==null?void 0:g.connectionId),cardId:c,cardConfig:p||{},cardDataSource:g||null,activeFilters:y,cardType:b}}),Ve=Xe==null?void 0:Xe.inferredDataType,$e=E||Ve||"string",Ae=v.useCallback(()=>{z(!1),Y(""),K(""),M(void 0),Be()},[Be]),Re=v.useCallback(()=>{se||(K(""),M(void 0),Be(),z(!0))},[se,Be]),He=v.useCallback(async()=>{if(!U.trim())return;const Pe=await ne(U);Pe&&(K(Pe.generated),M(Pe.explanation))},[U,ne]),Ge=v.useCallback(()=>{K(""),M(void 0),Be()},[Be]),ht=v.useCallback(()=>{O.trim()&&(_(O),Ye(),Ae())},[O,Ae,Ye]),lt=v.useMemo(()=>{const{orderedFields:Pe}=tC(k,ye);return Pe.filter(St=>!!St)},[ye,k]),st=v.useMemo(()=>u3(lt),[lt]),Fe=v.useMemo(()=>{if(!C.trim())return!1;const Pe=c3(C);return WJe({fields:S==="metric"?Se:ue,normalizedName:Pe,existingFieldId:s==="domain"?r==null?void 0:r.id:void 0,targetKind:st.kind==="inline"?"inline":"root",targetEntityName:st.kind==="inline"?st.entityName:void 0,targetQualifiedEntityName:st.kind==="inline"?st.qualifiedEntityName:void 0})},[st,ue,Se,r,s,S,C]),Ke=v.useMemo(()=>lt.map(Pe=>Pe.id),[lt]),_t=Pe=>{se||r||w(Pe)},Te=v.useCallback(()=>{N(""),_(""),D(null),I("card"),F({}),R(""),z(!1),Y(""),K(""),M(void 0),X(null),L(null),V(!1),Ye(),Be(),t(!1)},[t,Ye,Be]),Ze=v.useCallback((Pe,St)=>Pe.replace(/\{field_(\d+)\}/g,(pe,Oe)=>{var nn;const Je=St[Number(Oe)];return Je?`{${((nn=ye.find(Rt=>Rt.id===Je.id))==null?void 0:nn.tokenLabel)||Je.label||Je.name}}`:pe}),[ye]),at=v.useCallback(Pe=>{var Oe;const St=((Oe=Pe.calculatedFormula)==null?void 0:Oe.inputFields)||[],pe=Pe.role==="metric"?OJe(Pe):Pe.expression||"";_(Ze(pe,St))},[Ze]);v.useEffect(()=>{if(!e){J.current=!1,re.current=null;return}const Pe=r?`${r.role}-${r.id||r.name}`:"new";if(J.current&&re.current===Pe)return;if(J.current=!0,re.current=Pe,F({}),R(""),Ye(),r){if(r.role==="metric"){const Je=$Je(r);w("metric"),N(r.label||r.name),I(s||"card"),X(Je.reason||null),at(r),D(null);return}X(null),w("dimension");const pe=r;N(pe.label||pe.name),I(s||"card"),at(pe);const Oe=K7.some(Je=>Je.value===pe.dataType)?pe.dataType:"string";D(Oe);return}const St=d&&d.length>0?d.includes(u)?u:d[0]:u;w(St),N(""),_(""),D(null),X(null),I("card")},[e,r,s,u,d,at,Ye]);const bt=v.useCallback(Pe=>{const St=typeof document<"u"?document.getElementById(Z):null;if(!St){_(Je=>Je+Pe);return}const pe=St.selectionStart||0,Oe=St.selectionEnd||0;_(Je=>`${Je.slice(0,pe)}${Pe}${Je.slice(Oe)}`),requestAnimationFrame(()=>{St.focus();const Je=pe+Pe.length;St.setSelectionRange(Je,Je)})},[Z]),ft=Pe=>{if(se)return;const St=Pe.tokenLabel||Pe.label||Pe.name;bt(`{${St}}`)},Et=Pe=>{se||bt(Pe)},Wt=async()=>{const Pe={};return C.trim()||(Pe.name="Name is required"),k.trim()||(Pe.expression="Expression is required"),Pe.expression||(await et()).isValid||(Pe.expression="Fix validation errors before saving"),F(Pe),Object.keys(Pe).length===0},En=()=>{const{orderedTokens:Pe,orderedFields:St}=tC(k,ye),pe=St.filter(It=>!!It),Oe=yR(k,Pe),Je=RJe(C,Oe,pe,$e,c,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...Je}:Je},zn=()=>{const{orderedTokens:Pe,orderedFields:St}=tC(k,ye),pe=St.filter(nn=>!!nn),Oe=UJe(pe,(r==null?void 0:r.role)==="metric"?r:void 0),Je=yR(k,Pe),It=MJe(C,"custom",null,null,{},c,r==null?void 0:r.id,Je,void 0,Oe);return r&&r.role==="metric"?zJe(r,It):It},xt=async Pe=>{if(Pe==="domain"){F(pe=>({...pe,scope:"Domain scope is not available in this explorer."}));return}const St=S==="dimension"?En():zn();if(Pe==="sheet"){if(!i){F(pe=>({...pe,scope:"Sheet scope is not available"}));return}await i(St),Te();return}if(Pe==="dashboard"){if(!a){F(pe=>({...pe,scope:"Dashboard scope is not available"}));return}await a(St),Te();return}await o(St),Te()},Dt=async()=>{if(se||(F({}),!await Wt()))return;const Pe=be||Ce?j:s||"card";if(S==="metric"&&Pe!=="domain"&&Fe&&!r){L(Pe),V(!0);return}A(!0);try{await xt(Pe)}finally{A(!1)}},Lt=S==="metric"?ket:_et,Ft=S==="metric"?jet:Eet,pt=S==="metric"?"Metric formula":"Column expression",ae=be||Ce,qe=d||["metric","dimension"];return l.jsxs(l.Fragment,{children:[l.jsxs(Oo,{modal:!1,open:e,onOpenChange:Pe=>{Pe?t(!0):Te()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(mo,{className:"max-w-3xl max-h-[90vh] overflow-hidden p-0",onInteractOutside:Pe=>{Pe.preventDefault()},children:[l.jsxs(na,{className:"space-y-2 border-b py-3 pl-5 pr-12",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(go,{className:"shrink-0 text-[14px] font-semibold",children:r?"Edit field":"New field"}),l.jsx(qJe,{value:S,onChange:_t,disabled:se||!!r,options:qe}),l.jsx(m.Input,{id:"calculated-name",value:C,onChange:Pe=>N(Pe.target.value),placeholder:"Field name","aria-label":"Field name","aria-invalid":!!T.name,className:`h-7 flex-1 ${T.name?"border-destructive":""}`,disabled:se})]}),l.jsx(si,{className:"sr-only",children:"Build a calculated metric or column using expressions."}),T.name&&l.jsx("p",{className:"text-xs text-destructive",children:T.name}),W&&l.jsxs("div",{className:"rounded-control border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:[l.jsx("p",{className:"font-medium text-foreground",children:"Read-only legacy metric"}),l.jsx("p",{children:W})]})]}),l.jsxs("div",{className:"flex max-h-[calc(80vh-180px)] min-h-0 flex-col gap-4 overflow-y-auto px-5 py-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs("div",{className:"flex items-baseline gap-2 whitespace-nowrap",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:pt}),S==="metric"&&l.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",title:"Phase 1 metrics run on aggregated values such as SUM(revenue) / COUNT(orders). Per-row metrics aren't saveable yet — use Calculated Column for row-level math.",children:[l.jsx("span",{className:"text-muted-foreground/70",children:"·"}),l.jsx("span",{className:"font-medium text-foreground",children:"After aggregation"}),l.jsx(m.Info,{className:"h-2.5 w-2.5 text-muted-foreground/70","aria-hidden":!0})]})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(QJe,{groups:Ee,searchTerm:P,onSearchTermChange:R,onFieldSelect:ft,selectedFieldIds:Ke,disabled:se||B}),S==="metric"&&l.jsx(JJe,{onInsert:Et,disabled:se||B}),!!te&&!se&&l.jsxs(m.Button,{type:"button",variant:B?"default":"outline",size:"xs",onClick:Re,disabled:B,className:"gap-1.5",children:[l.jsx(Fm,{className:"h-3 w-3","aria-hidden":!0}),B?"Composing…":"Generate"]}),l.jsxs("a",{href:Lt,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground",children:["Docs ",l.jsx(Am,{className:"h-2.5 w-2.5"})]})]})]}),B?l.jsx(ZJe,{mode:rt,fieldType:S,prompt:U,onPromptChange:Y,generated:O,explanation:q,isGenerating:je,error:Ue,onGenerate:()=>void He(),onTryAgain:Ge,onCancel:Ae,onUseDraft:ht}):l.jsxs(l.Fragment,{children:[l.jsx("div",{"aria-invalid":!!T.expression,className:`overflow-hidden rounded-control border ${T.expression?"border-destructive":"border-input"}`,children:l.jsx("div",{className:"h-[160px]",children:l.jsx(m.CodeEditor,{value:k,onValueChange:_,language:"sql-jinja",placeholder:Ft,ariaLabel:S==="metric"?"Metric formula":"Column expression",textareaId:Z,readOnly:se,embedded:!0,flushGutter:!0,dense:!0})})}),l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx(GJe,{onValidate:et,isValidating:tt,validationResult:Xe,error:me,disabled:se}),l.jsx("span",{className:"text-[11px] text-muted-foreground",children:S==="metric"?"Aggregate functions allowed":"Aggregate functions not allowed"})]}),T.expression&&l.jsx("p",{className:"text-xs text-destructive",children:T.expression})]})]}),S==="dimension"&&l.jsxs("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Output type"}),l.jsxs(m.Select,{value:$e,onValueChange:Pe=>D(Pe),disabled:se,children:[l.jsx(m.SelectTrigger,{className:"h-7 w-44 text-[12px]",children:l.jsx(m.SelectValue,{placeholder:"Select output type"})}),l.jsx(m.SelectContent,{children:K7.map(Pe=>l.jsx(m.SelectItem,{value:Pe.value,children:Pe.label},Pe.value))})]}),Ve&&!E&&l.jsxs("p",{className:"col-start-2 text-[11px] text-muted-foreground",children:["Suggested type: ",Ve]})]}),ae&&l.jsxs("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Availability"}),l.jsx(m.Tabs,{value:j,onValueChange:Pe=>I(Pe),className:"w-fit",children:l.jsxs(m.TabsList,{size:"xs",children:[l.jsx(m.TabsTrigger,{value:"card",disabled:se,children:$x("card")}),be&&l.jsx(m.TabsTrigger,{value:"sheet",disabled:se,children:$x("sheet")}),Ce&&l.jsx(m.TabsTrigger,{value:"dashboard",disabled:se,children:$x("dashboard")})]})}),T.scope&&l.jsx("p",{className:"col-start-2 text-xs text-destructive",children:T.scope})]})]}),l.jsx(ret,{fieldType:S,inlineAnalysis:st,availability:ae?j:s||"card",hasInputFields:lt.length>0}),l.jsxs(Gc,{className:"gap-1.5 border-t px-5 py-2.5",children:[l.jsx(m.Button,{variant:"outline",size:"xs",onClick:Te,disabled:H,children:"Cancel"}),l.jsx(m.Button,{size:"xs",onClick:()=>void Dt(),disabled:H||tt||se,children:H?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"mr-1.5 h-3 w-3 animate-spin"}),"Applying…"]}):ke?"Read-only":"Apply"})]})]})]}),l.jsx(Lc,{open:$,onOpenChange:V,children:l.jsxs(vl,{children:[l.jsxs(wl,{children:[l.jsx(Cl,{children:"Name conflict"}),l.jsxs(Nl,{children:['A domain metric named "',C.trim(),'" already exists. Your local version will override it for the selected availability:'," ",$x(G||"card"),". Continue?"]})]}),l.jsxs(Sl,{children:[l.jsx(_l,{onClick:()=>{L(null)},children:"Choose different name"}),l.jsx(kl,{onClick:async()=>{if(G){V(!1),A(!0);try{await xt(G)}finally{A(!1),L(null)}}},children:"Continue"})]})]})})]})}function Det(e,t){const n=e.fieldScope==="sheet"||e.fieldScope==="dashboard";if(e.role==="metric"){const r=t.metricFields.find(s=>m.matchesCalculatedField(s,e,{allowComparableFallback:n}));if(r)return r}if(e.role==="groupby"){const r=t.groupByFields.find(s=>m.matchesCalculatedField(s,e,{allowComparableFallback:n}));if(r)return r}return t.storedCalculatedFields.find(r=>m.matchesCalculatedField(r,e,{allowComparableFallback:n}))}function Iet(e,t){const n={...e,fieldScope:"domain"};return t.find(r=>r.fieldScope==="domain"&&m.matchesCalculatedField(r,n))}function qj(e,t){var n,r,s,o;if(e.role==="metric"&&t.role==="metric"){const i=e,a=t;return{...a,parameters:i.parameters||a.parameters?{filters:((n=i.parameters)==null?void 0:n.filters)??((r=a.parameters)==null?void 0:r.filters),windowTransform:((s=i.parameters)==null?void 0:s.windowTransform)??((o=a.parameters)==null?void 0:o.windowTransform)}:void 0,aliasTemplate:i.aliasTemplate??a.aliasTemplate,valueAliases:i.valueAliases??a.valueAliases,customFormat:i.customFormat??a.customFormat,comparisonType:i.comparisonType??a.comparisonType,comparisonDisplay:i.comparisonDisplay??a.comparisonDisplay,targetValue:i.targetValue??a.targetValue}}if(e.role==="groupby"&&t.role==="groupby"){const i=e,a=t;return{...a,granularity:i.granularity??a.granularity,dateFormat:i.dateFormat??a.dateFormat,customFormat:i.customFormat??a.customFormat,timeDrillPath:i.timeDrillPath??a.timeDrillPath}}return t}function h3(e,t,n,r){if(!n)return null;const s=n||t,o=m.findCalculatedFieldIndex(e,s,r);if(n&&o<0)return null;if(o>=0){const i=e[o],a=i==null?void 0:i.id,c=r!=null&&r.mergeMatchedField?r.mergeMatchedField(i,t):t,d=a&&a!==c.id&&!((i==null?void 0:i.fieldScope)==="domain"&&c.fieldScope==="domain")?{...c,id:a}:c;return e.map((f,h)=>h===o?d:f)}return null}function p3(e,t){return{...e,fieldScope:t}}function Tet(e,t,n){return m.matchesCalculatedField(e,t,n)?!0:e.role&&t.role&&e.role!==t.role?m.matchesCalculatedField(e,{...t,role:e.role},n):!1}function Met(e,t,n,r){if(!(e!=null&&e.length)||!n)return null;const s=e.findIndex(u=>Tet(u,n,r));if(s<0)return null;const o=e[s],i=qj(o,{...t,role:o.role}),a=(()=>{if(o.role==="sortby")return{...i,role:"sortby",direction:o.direction};if(o.role==="detail"){const u=o;return{...i,role:"detail",dateFormat:u.dateFormat??i.dateFormat,customFormat:u.customFormat??i.customFormat}}return i})(),c=o.id&&o.id!==i.id?{...a,id:o.id}:a;return e.map((u,d)=>d===s?c:u)}function vR(e){const t=p3(e.updatedField,"card"),n=h3(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard",mergeMatchedField:qj}),r=m.upsertCalculatedField(e.storedFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard"}),s=(e.previousScope==="sheet"||e.previousScope==="dashboard")&&e.editingField?m.removeCalculatedField(e.sharedFields,e.editingField,{allowComparableFallback:!0}):e.sharedFields,o=m3({sortByFields:e.sortByFields,updatedField:t,editingField:e.editingField,previousScope:e.previousScope});return{nextActiveFields:n,nextSortByFields:o,nextStoredFields:r,nextSharedFields:s}}function wR(e){const t=p3(e.updatedField,"sheet"),n=h3(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard",mergeMatchedField:qj}),r=m.upsertCalculatedField(e.sheetFields,t,e.editingField,{allowComparableFallback:!0}),s=e.previousScope==="card"&&e.editingField?m.removeCalculatedField(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields,o=e.previousScope==="dashboard"&&e.editingField&&e.dashboardFields?m.removeCalculatedField(e.dashboardFields,e.editingField,{allowComparableFallback:!0}):e.dashboardFields,i=m3({sortByFields:e.sortByFields,updatedField:t,editingField:e.editingField,previousScope:e.previousScope});return{nextActiveFields:n,nextSortByFields:i,nextStoredFields:s,nextSheetFields:r,nextDashboardFields:o}}function vle(e){const t=p3(e.updatedField,"dashboard"),n=h3(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard",mergeMatchedField:qj}),r=m.upsertCalculatedField(e.sharedFields,t,e.editingField,{allowComparableFallback:!0}),s=e.previousScope==="card"&&e.editingField?m.removeCalculatedField(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields,o=e.previousScope==="sheet"&&e.editingField&&e.sheetFields?m.removeCalculatedField(e.sheetFields,e.editingField,{allowComparableFallback:!0}):e.sheetFields,i=m3({sortByFields:e.sortByFields,updatedField:t,editingField:e.editingField,previousScope:e.previousScope});return{nextActiveFields:n,nextSortByFields:i,nextStoredFields:s,nextSharedFields:r,nextSheetFields:o}}function m3(e){return Met(e.sortByFields||[],e.updatedField,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard"})}function af(e){const{nextSharedFields:t,currentSharedFields:n,isVisualEditing:r,selectedSheetId:s,updateFrame:o,updateSheetCalculatedFields:i,currentFrame:a,nextFramePatch:c,persistFrame:u,persistFrames:d}=e,f=c?{...c,calculatedFields:t}:{calculatedFields:t};(t!==n||c)&&o(f),s&&(r||(u&&(d!=null&&d.length)?d.forEach(h=>{u(s,{...h,calculatedFields:void 0})}):u&&a&&c&&u(s,{...a,...c,calculatedFields:void 0}),i&&i(s,t)))}const Aet=[];function rS({label:e,count:t,active:n,onClick:r,ariaLabel:s}){return l.jsxs("button",{type:"button",onClick:r,"aria-label":s,"aria-pressed":n,className:m.cn("-mb-px inline-flex items-center gap-1 border-b-2 px-0.5 pb-2 pt-1 text-[12px] transition-colors",n?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:[l.jsx("span",{children:e}),l.jsx("span",{className:m.cn("font-mono text-[10px] tabular-nums",n?"text-muted-foreground":"text-muted-foreground/70"),children:t})]})}const g3=v.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var qe,wt,Pe,St;const[s,o]=v.useState(""),[i,a]=v.useState("all"),c=v.useRef(null),[u,d]=v.useState(null),[f,h]=v.useState(!1),p=280,g=(pe,Oe)=>(Je,It)=>{if(!Je){d(Cn=>Cn&&Cn.field.id===pe.id?null:Cn);return}if(f){d(null);return}if(!It||!c.current)return;const nn=It.getBoundingClientRect(),Rt=c.current.getBoundingClientRect(),_r=Math.max(0,Rt.bottom-p);d({field:pe,fieldState:Oe,top:Math.min(nn.top,_r),left:Rt.right+12})},[b,x]=v.useState(!1),[y,S]=v.useState(null),[w,C]=v.useState("card"),[N,k]=v.useState("metric"),[_,E]=v.useState(null),[D,j]=v.useState(!1);m.useEditorStore(pe=>pe.isDevMode);const I=m.useEditorStore(pe=>pe.card.dataSource),T=m.useEditorStore(pe=>pe.card.config),F=m.useEditorStore(pe=>pe.card),P=m.useEditorStore(pe=>pe.frame),R=m.useEditorStore(pe=>pe.actions.updateCardConfig),B=m.useEditorStore(pe=>pe.actions.updateCard),z=m.useEditorStore(pe=>pe.actions.updateFrame),U=m.useDashboardStore(pe=>pe.isVisualEditing),Y=m.useDashboardStore(pe=>pe.selectedSheetId),O=m.useDashboardStore(pe=>pe.actions.updateSheetCalculatedFields),K=m.useDashboardStore(pe=>pe.actions.updateDashboardCalculatedFields),M=m.useDashboardStore(pe=>{var Oe;return pe.visualEditPendingDashboardCalculatedFields??((Oe=pe.dashboard)==null?void 0:Oe.calculatedFields)})??Aet,{userContext:G}=ta(),{autoJoinMetadata:L}=f_(F),{rawColumnGroups:$,scopedFields:V,filterableFields:H,dashboardFilterableFields:A,inlineFilterableFields:W,scopedCalculatedFields:X,sharedCalculatedFields:Z,inlineCalculatedFields:J,isLoading:re,error:fe}=Uae(),de=(I==null?void 0:I.mode)==="semanticDomain"?I.semanticDomainId:void 0,{data:Se}=JL(de),ue=v.useMemo(()=>[...(T==null?void 0:T.groupByColumns)||[],...(T==null?void 0:T.metricColumns)||[],...(T==null?void 0:T.detailColumns)||[]],[T==null?void 0:T.groupByColumns,T==null?void 0:T.metricColumns,T==null?void 0:T.detailColumns]);(wt=(qe=T==null?void 0:T.joinPlan)==null?void 0:qe.baseEntity)==null||wt.name,(St=(Pe=L==null?void 0:L.resolvedJoinPlan)==null?void 0:Pe.baseEntity)==null||St.name,Jae();const ve=t==="editor"?X:t==="filter"||t==="document-filter"?Z:J,xe=t==="editor"?ve.filter(pe=>m.getCalculatedFieldNamespace(pe)==="root"):ve,ke=xe.length>0,se=(G==null?void 0:G.type)==="organization",be=t==="editor"?H||V:t==="filter"||t==="document-filter"?A:W,Ce=$,ge=s.toLowerCase(),ee=(T==null?void 0:T.metricColumns)||[],te=(T==null?void 0:T.groupByColumns)||[],ce=(T==null?void 0:T.sortByColumns)||[],le=F.calculatedFields||[],Ee=pe=>pe.name.toLowerCase().includes(ge)||pe.label&&pe.label.toLowerCase().includes(ge)||pe.dataType.toLowerCase().includes(ge)||pe.description&&pe.description.toLowerCase().includes(ge)||pe.qualifiedEntityName&&pe.qualifiedEntityName.toLowerCase().includes(ge),ye=v.useCallback(pe=>(pe.label||pe.name).toLowerCase().trim(),[]),ne=v.useCallback((pe,Oe)=>ye(pe).localeCompare(ye(Oe),void 0,{numeric:!0,sensitivity:"base"}),[ye]),je=be.filter(Ee).sort(ne),Ue=v.useCallback(pe=>t==="editor"?fb(pe):ka(pe),[t]),Be=pe=>{if(Ue(pe))return"calculated";if(pe.dataType==="number"||pe.dataType==="integer"||pe.dataType==="float"||pe.dataType==="decimal"||pe.dataType==="currency")return"metrics";const Oe=m.getDataType(pe.dataType);return["date","string","boolean"].includes(Oe)?"dimensions":Oe==="number"?"metrics":"dimensions"},rt=pe=>{const Oe=pe.filter(Ee);return i==="all"?Oe:Oe.filter(Je=>Be(Je)===i)},Xe=i==="all"?je:je.filter(pe=>Be(pe)===i),et=ke?rt(xe).sort(ne):[],tt=v.useCallback(pe=>Ue(pe)&&(t!=="editor"||m.getCalculatedFieldNamespace(pe)==="root"),[t,Ue]),me=be.filter(pe=>!tt(pe)),Ve=rt(me).sort(ne).reduce((pe,Oe)=>{const Je=Oe.qualifiedEntityName||"Other Fields";return pe[Je]||(pe[Je]={label:m.toLabel(Oe.entityName),fields:[]}),pe[Je].fields.push(Oe),pe},{}),$e=v.useMemo(()=>Object.entries(Ve).map(([pe,Oe])=>{const Je=Ce.find(nn=>nn.entityName===pe)||{entityName:pe,label:Oe.label},It=pe===m.CALCULATED_FIELDS_GROUP_NAME?"Domain Calculated Fields":Je.label||Je.entityName;return{groupName:pe,groupLabel:It,fields:[...Oe.fields].sort(ne)}}).sort((pe,Oe)=>pe.groupLabel.localeCompare(Oe.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[Ve,Ce,ne]),Ae=pe=>pe.id||`${pe.entityName}-${pe.qualifiedEntityName}-${pe.name}-${pe.role||"field"}`,Re=v.useMemo(()=>{const pe=new Map;return be.forEach(Je=>{pe.set(Ae(Je),MO(Je,{joinabilityMap:(Se==null?void 0:Se.joinabilityMap)||null,selectedFields:ue,cardConfig:T,autoJoinMetadata:L,datasetAliases:Se==null?void 0:Se.datasets}))}),pe},[be,Se==null?void 0:Se.joinabilityMap,Se==null?void 0:Se.datasets,ue,T,L]),He=i==="calculated"&&se&&t==="editor"&&xe.length===0,Ge=et.length>0?[{key:"scope-calculated",label:"Calculated Fields",fields:et}]:He?[{key:"scope-calculated",label:"Calculated Fields",fields:[]}]:[],lt=[...Ge.map(pe=>pe.key),...$e.map(pe=>pe.groupName)],st=je.filter(pe=>Be(pe)==="dimensions").length,Fe=je.filter(pe=>Be(pe)==="metrics").length,Ke=je.filter(pe=>Be(pe)==="calculated").length,_t=je.length>0&&t!=="inline-filter"&&t!=="document-filter",Te=t==="inline-filter"||t==="document-filter"?"w-full":"w-[290px]";if(re)return l.jsx("div",{className:m.cn("flex h-full flex-col items-center justify-center py-8",Te),children:l.jsx(dd,{size:"md",color:"muted","aria-label":"Loading data"})});if(fe)return l.jsxs("div",{className:m.cn("flex h-full flex-col items-center justify-center py-8",Te),children:[l.jsx(ei,{className:"mb-4 h-12 w-12 text-red-300"}),l.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:fe.message||"Failed to load column data"})]});if(!I||!I.selectedEntities||I.selectedEntities.length===0)return l.jsxs("div",{className:m.cn("flex flex-col items-center justify-center py-8 text-center",Te),children:[l.jsx(ei,{className:"mb-4 h-12 w-12 text-gray-300"}),l.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),l.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-filter"||t==="document-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const Ze=t==="inline-filter"||t==="document-filter"?"pb-3":"pb-2",at=t==="inline-filter"||t==="document-filter"?"overflow-hidden":"",bt=pe=>Det(pe,{storedCalculatedFields:le,metricFields:ee,groupByFields:te}),ft=pe=>m.resolveLocalCalculatedFieldScope({field:pe,sheetFields:(P==null?void 0:P.calculatedFields)||[],dashboardFields:M}),Et=(pe,Oe)=>{B(F.id,{calculatedFields:m.removeCalculatedField(le,pe,Oe)})},Wt=pe=>{var Oe;return(Oe=P==null?void 0:P.calculatedFields)==null?void 0:Oe.find(Je=>m.matchesCalculatedField(Je,pe))},En=pe=>M.find(Oe=>m.matchesCalculatedField(Oe,pe,{allowComparableFallback:!0})),zn=(pe,Oe)=>{if(pe.role==="metric"){R(F.id,{metricColumns:m.removeCalculatedField(ee,pe,Oe)});return}pe.role==="groupby"&&R(F.id,{groupByColumns:m.removeCalculatedField(te,pe,Oe)})},xt=pe=>{K(m.removeCalculatedField(M,pe,{allowComparableFallback:!0}))},Dt=pe=>{if(!P)return;const Oe=m.removeCalculatedField(P.calculatedFields||[],pe);af({nextSharedFields:Oe,currentSharedFields:P.calculatedFields||[],isVisualEditing:U,selectedSheetId:Y,updateFrame:z,updateSheetCalculatedFields:O})},Lt=pe=>{if(!se)return;if(d(null),pe.fieldScope==="domain"){ut.error("Domain calculated fields are read-only in this explorer.");return}const Oe=ft(pe);if(Oe.scope==="sheet"){const It=Oe.matchedField||Wt(pe);if(!It)return;S(It),C("sheet"),k(It.role==="metric"?"metric":"dimension"),x(!0);return}if(Oe.scope==="dashboard"){const It=Oe.matchedField||En(pe);if(!It)return;S(It),C("dashboard"),k(It.role==="metric"?"metric":"dimension"),x(!0);return}const Je=bt(pe);Je&&(S(Je),C("card"),k(Je.role==="metric"?"metric":"dimension"),x(!0))},Ft=async pe=>{if(!se)return;if(pe.fieldScope==="domain"){ut.error("Domain calculated fields are read-only in this explorer.");return}const Oe=ft(pe),Je={allowComparableFallback:Oe.scope!=="card"};if(Oe.scope==="sheet"){Dt(Oe.matchedField||pe),zn(pe,Je);return}if(Oe.scope==="dashboard"){xt(Oe.matchedField||pe),zn(pe,Je);return}zn(pe,Je),Et(pe,Je)},pt=async()=>{if(_){j(!0);try{await Ft(_),E(null)}catch{}finally{j(!1)}}},ae=pe=>{if(!se)return null;const Oe=pe.fieldScope==="domain",Je=Oe;return l.jsxs(Ao,{onOpenChange:It=>{h(It),It&&d(null)},children:[l.jsx(Ro,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Calculated field actions",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(ja,{className:"h-3 w-3"})})}),l.jsx(fo,{align:"end",className:"w-36",children:Oe?l.jsx(jn,{disabled:!0,children:"Read-only"}):l.jsxs(l.Fragment,{children:[l.jsx(jn,{onClick:()=>Lt(pe),children:"Edit"}),l.jsx(jn,{className:"text-destructive focus:text-destructive",disabled:Je,onClick:()=>E(pe),children:"Delete"})]})})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{ref:c,className:m.cn("relative flex h-full w-full grow flex-col",Ze,at),children:[l.jsxs("div",{className:"flex-shrink-0 space-y-2 px-4 pt-2",children:[be.length>0&&l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[l.jsx(Ws,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("input",{type:"text",placeholder:"Search fields",value:s,onChange:pe=>o(pe.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),s&&l.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>o(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),_t&&l.jsxs("div",{className:"-mx-4 flex items-center gap-4 border-b border-border px-4",children:[l.jsx(rS,{label:"All",count:je.length,active:i==="all",onClick:()=>a("all")}),l.jsx(rS,{label:"Dim",count:st,active:i==="dimensions",onClick:()=>a(pe=>pe==="dimensions"?"all":"dimensions"),ariaLabel:"Dimensions"}),l.jsx(rS,{label:"Metric",count:Fe,active:i==="metrics",onClick:()=>a(pe=>pe==="metrics"?"all":"metrics"),ariaLabel:"Metrics"}),l.jsx(rS,{label:"Calc",count:Ke,active:i==="calculated",onClick:()=>a(pe=>pe==="calculated"?"all":"calculated"),ariaLabel:"Calculated"})]})]}),l.jsxs(zl,{className:"min-h-0 flex-1 [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:w-full",children:[l.jsxs(l3,{type:"multiple",defaultValue:lt,className:"space-y-2",children:[Ge.map(pe=>l.jsxs(D0,{value:pe.key,className:"border-none",children:[l.jsxs(I0,{className:"group flex w-full items-center gap-1.5 rounded-[4px] px-4 py-1.5 text-left hover:bg-muted hover:no-underline [&>svg]:order-first [&>svg]:h-3 [&>svg]:w-3 [&>svg]:-rotate-90 [&>svg]:text-muted-foreground/70 data-[state=open]:[&>svg]:rotate-90",children:[l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l.jsx("span",{className:"max-w-[180px] truncate text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:pe.label}),l.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:pe.fields.length})]}),t==="editor"&&se&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Add calculated field",title:"Add calculated field",onClick:Oe=>{Oe.stopPropagation(),S(null),C("card"),k("dimension"),x(!0)},onKeyDown:Oe=>{(Oe.key==="Enter"||Oe.key===" ")&&(Oe.preventDefault(),Oe.stopPropagation(),S(null),C("card"),k("dimension"),x(!0))},className:"inline-flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(dr,{className:"h-3 w-3"})})]}),l.jsx(T0,{className:"pb-1",children:l.jsxs("div",{children:[pe.fields.length===0&&He&&l.jsx("p",{className:"px-4 py-2 text-[11px] text-muted-foreground",children:"No calculated fields yet — click + to add."}),pe.fields.map(Oe=>{const Je=Re.get(Ae(Oe)),It=t==="editor"&&se&&ka(Oe);return l.jsx(W7,{field:Oe,context:t,fieldState:Je,onFieldSelect:n,inlineFilters:t==="inline-filter"||t==="document-filter"?r:void 0,actions:It?ae(Oe):void 0,onHover:g(Oe,Je)},Oe.id)})]})})]},pe.key)),$e.map(({groupName:pe,groupLabel:Oe,fields:Je})=>l.jsxs(D0,{value:pe,className:"border-none",children:[l.jsx(I0,{className:"group flex w-full items-center gap-1.5 rounded-[4px] px-4 py-1.5 text-left hover:bg-muted hover:no-underline [&>svg]:order-first [&>svg]:h-3 [&>svg]:w-3 [&>svg]:-rotate-90 [&>svg]:text-muted-foreground/70 data-[state=open]:[&>svg]:rotate-90",children:l.jsxs("div",{title:Oe,className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l.jsx("span",{className:"max-w-[180px] truncate text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:Oe}),l.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:Je.length})]})}),l.jsx(T0,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:Je.map(It=>{const nn=Re.get(Ae(It)),Rt=t==="editor"&&se&&ka(It);return l.jsx(W7,{field:It,context:t,fieldState:nn,onFieldSelect:n,inlineFilters:t==="inline-filter"||t==="document-filter"?r:void 0,actions:Rt?ae(It):void 0,onHover:g(It,nn)},It.id)})})})]},pe))]}),be.length===0&&l.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[l.jsx("p",{children:"No fields found for selected data source"}),l.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),be.length>0&&Xe.length===0&&!He&&l.jsx("div",{className:"py-4 text-center text-[11px] text-muted-foreground",children:"No fields found for this category"}),l.jsx(m.ScrollBar,{orientation:"vertical"})]})]}),u&&l.jsx("div",{style:{position:"fixed",top:u.top,left:u.left},className:"pointer-events-none z-50 w-[280px] overflow-hidden rounded-control border border-border bg-popover shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:l.jsx(hJe,{field:u.field,fieldState:u.fieldState})}),l.jsx(Lc,{open:!!_,onOpenChange:pe=>{pe||E(null)},children:l.jsxs(vl,{children:[l.jsxs(wl,{children:[l.jsx(Cl,{children:"Delete calculated field?"}),l.jsxs(Nl,{children:["This will remove"," ",l.jsx("span",{className:"font-medium text-foreground",children:(_==null?void 0:_.label)||(_==null?void 0:_.name)||"this calculated field"})," ",(_==null?void 0:_.fieldScope)==="domain"?"from the semantic domain.":"from this configuration."]})]}),l.jsxs(Sl,{children:[l.jsx(_l,{disabled:D,children:"Cancel"}),l.jsx(kl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:D,onClick:pe=>{pe.preventDefault(),pt()},children:D?"Deleting...":"Delete"})]})]})}),l.jsx(yle,{open:b,onOpenChange:pe=>{x(pe),pe||(S(null),C("card"))},availableFields:V,existingField:y??void 0,existingFieldScope:w,initialFieldType:N,onSave:pe=>{const Oe=y,Je=w==="dashboard"?M:(P==null?void 0:P.calculatedFields)||[];if(pe.role==="metric"){const{nextActiveFields:Cn,nextSortByFields:yr,nextStoredFields:Ts,nextSharedFields:ds}=vR({activeFields:ee,sortByFields:ce,storedFields:le,sharedFields:Je,updatedField:pe,editingField:Oe,previousScope:w});(Cn||yr)&&R(F.id,{...Cn?{metricColumns:Cn}:{},...yr?{sortByColumns:yr}:{}}),B(F.id,{calculatedFields:Ts}),w==="dashboard"&&ds!==Je?K(ds):P&&ds!==Je&&af({nextSharedFields:ds,currentSharedFields:Je,isVisualEditing:U,selectedSheetId:Y,updateFrame:z,updateSheetCalculatedFields:O});return}const{nextActiveFields:It,nextSortByFields:nn,nextStoredFields:Rt,nextSharedFields:_r}=vR({activeFields:te,sortByFields:ce,storedFields:le,sharedFields:Je,updatedField:pe,editingField:Oe,previousScope:w});(It||nn)&&R(F.id,{...It?{groupByColumns:It}:{},...nn?{sortByColumns:nn}:{}}),B(F.id,{calculatedFields:Rt}),w==="dashboard"&&_r!==Je?K(_r):P&&_r!==Je&&af({nextSharedFields:_r,currentSharedFields:Je,isVisualEditing:U,selectedSheetId:Y,updateFrame:z,updateSheetCalculatedFields:O})},onSaveToSheet:pe=>{const Oe=y,Je=(P==null?void 0:P.calculatedFields)||[];if(pe.role==="metric"){const{nextActiveFields:yr,nextSortByFields:Ts,nextStoredFields:ds,nextSheetFields:yo,nextDashboardFields:We}=wR({activeFields:ee,sortByFields:ce,storedFields:le,sheetFields:Je,dashboardFields:M,updatedField:pe,editingField:Oe,previousScope:w});P&&af({nextSharedFields:yo,currentSharedFields:Je,isVisualEditing:U,selectedSheetId:Y,updateFrame:z,updateSheetCalculatedFields:O}),We&&We!==M&&K(We),(yr||Ts)&&R(F.id,{...yr?{metricColumns:yr}:{},...Ts?{sortByColumns:Ts}:{}}),B(F.id,{calculatedFields:ds});return}const{nextActiveFields:It,nextSortByFields:nn,nextStoredFields:Rt,nextSheetFields:_r,nextDashboardFields:Cn}=wR({activeFields:te,sortByFields:ce,storedFields:le,sheetFields:Je,dashboardFields:M,updatedField:pe,editingField:Oe,previousScope:w});P&&af({nextSharedFields:_r,currentSharedFields:Je,isVisualEditing:U,selectedSheetId:Y,updateFrame:z,updateSheetCalculatedFields:O}),Cn&&Cn!==M&&K(Cn),(It||nn)&&R(F.id,{...It?{groupByColumns:It}:{},...nn?{sortByColumns:nn}:{}}),B(F.id,{calculatedFields:Rt})},onSaveToDashboard:pe=>{const Oe=y,Je=pe.role==="metric"?ee:te,It=(P==null?void 0:P.calculatedFields)||[],{nextActiveFields:nn,nextSortByFields:Rt,nextStoredFields:_r,nextSharedFields:Cn,nextSheetFields:yr}=vle({activeFields:Je,sortByFields:ce,storedFields:le,sharedFields:M,sheetFields:It,updatedField:pe,editingField:Oe,previousScope:w});K(Cn),P&&yr&&yr!==It&&af({nextSharedFields:yr,currentSharedFields:It,isVisualEditing:U,selectedSheetId:Y,updateFrame:z,updateSheetCalculatedFields:O}),(nn||Rt)&&R(F.id,{...nn?{[pe.role==="metric"?"metricColumns":"groupByColumns"]:nn}:{},...Rt?{sortByColumns:Rt}:{}}),B(F.id,{calculatedFields:_r})},cardId:F.id})]})}),wle=v.memo(function({context:t,className:n,inlineFilters:r,onFieldSelect:s}){return l.jsx("div",{"data-content":"filterable-fields-panel",className:m.cn("flex min-h-0 grow flex-col overflow-hidden",n),children:l.jsx(ow,{collisionDetection:nw,children:l.jsx(iw,{items:[],strategy:YL,children:l.jsx(g3,{context:t,inlineFilters:r,onFieldSelect:s})})})})}),Ret=/{{\s*([A-Za-z_][A-Za-z0-9_]*)(?:\.([A-Za-z_][A-Za-z0-9_]*))?\s*}}/g,Fet=new Set(["generatedAt","pageNumber","pageCount"]),b3="document",Pet=/^(\d{4})-(\d{2})-(\d{2})$/;function Oet(e,t){const n=[],r=[];let s=0;for(const o of e.matchAll(Ret)){const i=o[0],a=o.index??0;a>s&&n.push({type:"text",value:e.slice(s,a),sourceStart:s,sourceEnd:a});const c=zet({aliasOrKey:o[1],exportKey:o[2],inputs:t});c?n.push({type:"variable",ref:c,sourceStart:a,sourceEnd:a+i.length}):(n.push({type:"text",value:i,sourceStart:a,sourceEnd:a+i.length}),r.push(i)),s=a+i.length}return s<e.length&&n.push({type:"text",value:e.slice(s),sourceStart:s,sourceEnd:e.length}),{content:n,unresolvedTokens:r}}function Let(e){return[...e.flatMap(n=>y3(n).map(r=>({label:`${n.variableName}.${r}`,token:`{{${n.variableName}.${r}}}`,ref:{source:"input",inputId:n.id,export:r}}))),{label:nC("generatedAt",e),token:jT("generatedAt",e),ref:{source:"documentMeta",key:"generatedAt"}},{label:nC("pageNumber",e),token:jT("pageNumber",e),ref:{source:"documentMeta",key:"pageNumber"}},{label:nC("pageCount",e),token:jT("pageCount",e),ref:{source:"documentMeta",key:"pageCount"}}]}function x3(e,t){if(e.source==="documentMeta")return nC(e.key,t);const n=t.find(r=>r.id===e.inputId);return`${(n==null?void 0:n.variableName)||e.inputId}.${e.export}`}function $et({inputs:e,filterValuesByInputId:t,controlValuesByInputId:n,controlOptionsByInputId:r={},generatedAt:s,timezone:o,generatedAtFormat:i,pageNumber:a=1,pageCount:c=1}){const u={};for(const d of e)u[d.id]=d.kind==="filter"?Vet(d,t[d.id],o):Het(d,n[d.id],o,r[d.id]);return{inputs:e,resolvedInputsById:u,timezone:o,generatedAtFormat:i,meta:{generatedAt:s,pageNumber:a,pageCount:c}}}function Sle(e,t){return(e==null?void 0:e.map(n=>n.type==="text"?{type:"text",value:n.value,...n.format?{format:n.format}:{}}:{type:"variable",value:Bet(n.ref,t),...n.format?{format:n.format}:{}}))||[]}function zet({aliasOrKey:e,exportKey:t,inputs:n}){if(e===b3&&t&&Z7(t))return{source:"documentMeta",key:t};const r=n.find(s=>s.variableName===e);if(r){const s=t||Wet(r);return!Cle(s)||!new Set(y3(r)).has(s)?null:{source:"input",inputId:r.id,export:s}}return!t&&Z7(e)?{source:"documentMeta",key:e}:null}function Bet(e,t){var s;if(e.source==="documentMeta")return e.key==="generatedAt"?_le(t.meta.generatedAt,t.timezone,t.generatedAtFormat||m.DEFAULT_DOCUMENT_GENERATED_AT_FORMAT):String(t.meta[e.key]);const n=t.resolvedInputsById[e.inputId],r=(s=n==null?void 0:n.exports)==null?void 0:s[e.export];return r==null?"":String(r)}function Vet(e,t,n){const r=(t==null?void 0:t.values)||[];if(m.getDataType(e.filter.dataType)==="date"){const a=r[0]?tk(r[0],n):"",c=r[1]?tk(r[1],n):"",u=a&&c?`${a} - ${c}`:a||c;return{inputId:e.id,variableName:e.variableName,rawValue:r.length>1?r:r[0]??null,displayValue:u,filterValues:t?[t]:void 0,exports:{label:u||null,value:u||null,start:a||null,end:c||null,range:u||null}}}const i=r.map(Get).join(", ");return{inputId:e.id,variableName:e.variableName,rawValue:r.length>1?r:r[0]??null,displayValue:i,filterValues:t?[t]:void 0,exports:{label:i||null,value:i||null}}}function Het(e,t,n,r=[]){const s=Yet(t),i=s.map(c=>e.control.type==="date"?tk(c,n):qet(e.control,c,r)).join(", "),a=s.map(kle).join(", ");return{inputId:e.id,variableName:e.variableName,rawValue:t??null,displayValue:i,controlValue:t,exports:{label:i||null,value:a||null}}}function y3(e){const t=Uet(e),n=(e.exports||[]).filter(Cle);return Array.from(new Set([...t,...n]))}function Uet(e){return e.kind==="filter"?m.getDataType(e.filter.dataType)==="date"?["label","start","end","range"]:["label","value"]:["label","value"]}function Wet(e){const t=y3(e);return t.includes("label")?"label":t.includes("range")?"range":t[0]||"value"}function Cle(e){return e==="label"||e==="value"||e==="start"||e==="end"||e==="range"}function Z7(e){return Fet.has(e)}function Nle(e,t){return t.some(n=>n.variableName===e)}function jT(e,t){return Nle(e,t)?`{{${b3}.${e}}}`:`{{${e}}}`}function nC(e,t){return Nle(e,t)?`${b3}.${e}`:e}function qet(e,t,n=[]){var o;const r=kle(t),s=n.find(i=>i.value===r);return s?s.label:e.source.kind==="manual"&&((o=e.source.options.find(i=>i.value===r))==null?void 0:o.label)||r}function Yet(e){return e==null?[]:Array.isArray(e)?e:[e]}function Get(e){return e instanceof Date?tk(e):e==null?"":String(e)}function kle(e){return e instanceof Date?e.toISOString():e==null?"":String(e)}function tk(e,t){return e?_le(e,t,"MMM d, yyyy"):""}function _le(e,t,n){const r=Zet(n),s=Ket(e);if(s)return xn.format(s,r);const o=e instanceof Date?e:new Date(String(e));return Number.isNaN(o.getTime())?e==null?"":String(e):xn.formatInTimeZone(o,t||"UTC",r)}function Ket(e){if(typeof e!="string")return null;const t=Pet.exec(e.trim());if(!t)return null;const n=Number(t[1]),r=Number(t[2]),s=Number(t[3]),o=new Date(n,r-1,s);return o.getFullYear()!==n||o.getMonth()!==r-1||o.getDate()!==s?null:o}function Zet(e){return e.replace(/\[([^\]]+)\]/g,"'$1'").replace(/YYYY/g,"yyyy").replace(/YY/g,"yy").replace(/DD/g,"dd").replace(/D/g,"d").replace(/A/g,"a")}const lw={text:"Text",table:"Table",chart:"Chart",spacer:"Spacer",page_break:"Page break"},jle=["text","table","spacer","page_break"];function M0(e){return e==="table"?m.Table2:e==="text"?m.Type:e==="spacer"?Ime:e==="page_break"?Eme:vi}function Xet(e){const t=`doc_section_${m.v4()}`;return e==="text"?{id:t,type:"text",content:m.textContent("New text section")}:e==="table"?{id:t,type:"table",title:"Table",card:{id:`doc_card_${t}`,title:"Table",type:"table",preferences:{tablePrefs:{density:"compact",tableStyle:{headerStyle:"filled",stripedRows:!1,gridLines:"horizontal",wrapText:!1,totals:{enabled:!1}}}}},table:{totalsRow:!1,repeatHeaderOnPageBreak:!0,rowHeightPx:28}}:e==="spacer"?{id:t,type:"spacer",heightPx:24}:{id:t,type:"page_break"}}function ET(e,t){if(e.type==="text"){const n=m.textContentToString(e.content,t).trim();return n?n.split(`
1302
1302
  `)[0].slice(0,40):"Text"}return e.type==="table"?e.title||e.card.title||"Table":e.type==="spacer"?`Spacer (${e.heightPx}px)`:lw[e.type]}function Qet(e,t){if(e.type==="spacer")return"Spacer";if(e.type==="text"){const n=m.textContentToString(e.content,t).trim();return n?n.split(`
1303
1303
  `)[0].slice(0,28):"Text section"}return e.type==="table"?e.title||e.card.title||"Table":e.type==="page_break"?"Page break":lw[e.type]}function Jet(e){return e.type==="spacer"?`${e.heightPx} px`:e.type==="table"?"Table":null}const Yd=Xu,Gd=Ui,ett={spacious:40,comfortable:36,standard:32,compact:28,dense:24};function v3(e){var t;return JO((t=e.card.preferences)==null?void 0:t.tablePrefs)}function ttt(e){return[e.density,e.headerStyle,e.headerBackgroundColor,e.headerTextColor,e.headerWrapText,e.stripedRows,e.gridLines,e.wrapText,e.totalsStyle.backgroundColor,e.totalsStyle.textColor,e.totalsStyle.fontWeight,e.totalsStyle.borderTop,e.totalsStyle.borderTopStyle,e.totalsStyle.borderTopColor].join(":")}const ntt=ete;function SR(e){return ett[e]}function rtt(e){return e.table.rowHeightPx??SR(v3(e).density)}function stt(e){const t=new Set;return e.forEach(n=>{Object.keys(n).forEach(r=>t.add(r))}),Array.from(t)}function Ele(e){var s;if(e.type!=="table"||e.card.type!=="table")return"";const t=e.card,n=t.config,r=t.dataSource;return JSON.stringify({type:t.type,connectionId:t.connectionId||(r==null?void 0:r.connectionId)||"",sql:((s=t.sql)==null?void 0:s.trim())||"",datamodelId:t.datamodelId||(r==null?void 0:r.datamodelId)||"",semanticDomainId:(r==null?void 0:r.semanticDomainId)||"",selectedEntities:(r==null?void 0:r.selectedEntities)||null,lastSelectedDatabase:t.lastSelectedDatabase||"",lastSelectedSchema:t.lastSelectedSchema||"",lastSelectedTable:t.lastSelectedTable||"",detailColumns:sS(n==null?void 0:n.detailColumns),groupByColumns:sS(n==null?void 0:n.groupByColumns),metricColumns:sS(n==null?void 0:n.metricColumns),pivotByColumns:sS(n==null?void 0:n.pivotByColumns)})}function sS(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object")return String(t??"");const n=t;return{id:n.id,alias:n.alias,name:n.name,label:n.label,column:n.column,expression:n.expression,aggregate:n.aggregate,aggregation:n.aggregation,dataType:n.dataType,type:n.type}}):[]}function Ml(e){return e.kind==="filter"}function bl(e){return e.kind==="control"}function Dle(e,t){return e.reduce((n,r)=>{if(!Ml(r))return n;const s=m.buildFilterValueFromDefaults(r.filter,t);return s&&(n[r.id]=s),n},{})}function Ile(e){return e.reduce((t,n)=>{if(!bl(n))return t;const r=m.buildAuthoringPreviewControlValues({controls:[n.control]});return Object.prototype.hasOwnProperty.call(r,n.control.id)&&(t[n.id]=r[n.control.id]),t},{})}function ott(e){return e.map(t=>`${t.id}:${Mle(t)}`).join("|")}function Tle(e){return e.reduce((t,n)=>(t[n.id]=Mle(n),t),{})}function Mle(e){return bl(e)?JSON.stringify({kind:e.kind,controlId:e.control.id,type:e.control.type,source:e.control.source}):JSON.stringify({kind:e.kind,filterId:e.filter.id,connectionId:e.filter.connectionId,qualifiedTableName:e.filter.qualifiedTableName||null,table:e.filter.table||null,database:e.filter.database||null,sql:e.filter.sql,column:e.filter.column,dataType:e.filter.dataType,operation:e.filter.operation,type:e.filter.type||null,fieldMeta:e.filter.fieldMeta||null,semanticContext:e.filter.semanticContext||null,targetColumns:e.filter.targetColumns||null})}function itt(e,t,n,r,s){const o={};for(const i of t){if(!Ml(i))continue;const a=e[i.id],c=cw(i.id,r,s),u=A0(i,a),d=Object.prototype.hasOwnProperty.call(e,i.id);if(!c&&d&&!a){o[i.id]=void 0;continue}if(!c&&u){o[i.id]=u;continue}n[i.id]&&(o[i.id]=n[i.id])}return utt(e,o)?e:o}function att(e,t,n,r,s){const o={};for(const i of t){if(!bl(i))continue;if(!cw(i.id,r,s)&&Object.prototype.hasOwnProperty.call(e,i.id)){o[i.id]=e[i.id];continue}Object.prototype.hasOwnProperty.call(n,i.id)&&(o[i.id]=n[i.id])}return dtt(e,o)?e:o}function w3(e,t){const n={...t,filterId:e.filter.id};return m.isCompatibleFilterValue(e.filter,n)?ltt(e).has(t.name):!1}function A0(e,t){if(!(!t||!w3(e,t)))return t.filterId===e.filter.id?t:{...t,filterId:e.filter.id}}function ltt(e){return new Set([e.filter.column,...(e.filter.targetColumns||[]).map(t=>t.column)])}function ctt(e,t){const n=new Set(t.filter(s=>Ml(s)&&Yj(s.filter.operation)).map(s=>s.id)),r={};for(const[s,o]of Object.entries(e))n.has(s)&&(r[s]=o);return ftt(e,r)?e:r}function utt(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>e[s]===t[s])}function dtt(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>Object.is(e[s],t[s]))}function ftt(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>e[s]===t[s])}function Yj(e){return e==="in"||e==="not in"}function Ale(e){return e==="not in"?"exclude":"include"}function CR(e){return e==="exclude"?"not in":"in"}function htt(e,t,n,r){return t.map(s=>{if(!Ml(s))return;const o=e[s.id];if(!(!o||cw(s.id,n,r)||!w3(s,o)))return A0(s,o)}).filter(s=>!!s)}function ptt(e,t,n,r){return t.reduce((s,o)=>(!bl(o)||cw(o.id,n,r)||!Object.prototype.hasOwnProperty.call(e,o.id)||(s[o.control.id]=e[o.id]),s),{})}function Rle(e,t,n,r,s){return e.filter(o=>o.requiredAtExecution?cw(o.id,r,s)?!0:Ml(o)?!t[o.id]||!w3(o,t[o.id]):!mtt(n,o.id):!1).map(o=>o.label)}function mtt(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))return!1;const n=e[t];return n==null?!1:Array.isArray(n)?n.length>0:typeof n=="string"?n.trim().length>0:!0}function cw(e,t,n){const r=n[e];return!!r&&r!==t[e]}const gtt=["table","pivotTable"];function btt(e){return{id:`doc_editor_frame_${e.id}`,cards:[e.card],activeCardId:e.card.id}}function xtt(e,t){return e.cards.find(n=>n.id===t)||null}function ytt(e){return gtt.includes(e.type)}function vtt(){const e=m.useDashboardStore(j=>j.dashboard),t=m.useEditorStore(j=>j.selectedConnectionId),n=m.useEditorStore(j=>j.selectedDatabaseName),r=m.useEditorStore(j=>j.selectedSchemaName),s=m.useEditorStore(j=>j.selectedTableName),o=m.useEditorStore(j=>j.selectedDatamodelId),{clearSelectedVisual:i}=Ph(),{setIsDashboardEditing:a,setIsVisualEditing:c}=m.useDashboardActions(),{setFrame:u,setCard:d,setIsDevMode:f,initializeModeDrafts:h,setActiveTabCardId:p,updateDataSource:g,setQueryResultColumns:b,setFilterValues:x,setInlineFilterValuesMap:y,setApplyFilters:S,clearModeDrafts:w,setEditorContext:C}=m.useEditorActions(),N=m.useEditorStore(j=>j.actions.setSelectedConnectionId),k=m.useEditorStore(j=>j.actions.setSelectedDatamodelId),_=m.useEditorStore(j=>j.actions.setSelectedDatabaseName),E=m.useEditorStore(j=>j.actions.setSelectedSchemaName),D=m.useEditorStore(j=>j.actions.setSelectedTableName);return v.useCallback((j,I,T=[],F=[],P={},R=[])=>{const B=btt(I);i(),w(),C({type:"documentSection",sheetId:j,sectionId:I.id,cardId:I.card.id,documentFilterValues:wtt(T),documentControlDefinitions:Stt(F),documentControlValues:{...P},missingRequiredInputLabels:[...R]}),h_({frame:B,card:I.card,setFrame:u,setCard:d,setIsDevMode:f,initializeModeDrafts:h,setActiveTabCardId:p,updateDataSource:g,setQueryResultColumns:b,setSelectedConnectionId:N,setSelectedDatabaseName:_,setSelectedSchemaName:E,setSelectedTableName:D,setSelectedDatamodelId:k,setFilterValues:x,setInlineFilterValuesMap:y,setApplyFilters:S,setIsDashboardEditing:a,setIsVisualEditing:c,dashboard:e,selectedSheetId:j,selectedFrameId:null,currentSelections:{connectionId:t,databaseName:n,schemaName:r,tableName:s,datamodelId:o}})},[w,i,e,h,t,n,o,r,s,p,S,d,C,x,u,y,a,f,c,b,N,_,k,E,D,g])}function wtt(e){return e.map(t=>({...t,values:[...t.values]}))}function Stt(e){return e.map(t=>({...t,source:t.source.kind==="manual"?{...t.source,options:t.source.options.map(n=>({...n}))}:{...t.source}}))}function DT({inputs:e,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,onOptionsChange:s}){return l.jsx(l.Fragment,{children:e.filter(bl).map(o=>l.jsx(Ctt,{input:o,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,onOptionsChange:s},o.id))})}function Ctt({input:e,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,onOptionsChange:s}){const o=e.control,i=o.source.kind==="sql_query"?o.source:void 0,a=ob({controlId:o.id,source:i,enabled:!!i,controlDefinitionsOverride:n,controlValuesOverride:r,activeFiltersOverride:t}),c=v.useMemo(()=>i?[]:zL(o),[o,i]),u=i?a.options:c;return v.useEffect(()=>{s(e.id,u)},[e.id,s,u]),null}function NR({children:e,className:t,empty:n,wrap:r=!1}){const s=v.Children.toArray(e).filter(o=>o!=null);return s.length===0?n??null:l.jsx("div",{className:m.cn("flex items-center gap-2 pr-1",r?"min-w-0 flex-wrap gap-y-2":"min-w-max",t),children:s})}function IT({children:e,className:t}){return l.jsx("div",{className:m.cn("shrink-0",t),children:e})}const rC=({dataType:e})=>WN(e),Fle=["day","week","month","quarter","year"],Ntt=[...Fle,"hour","minute","second"],ktt=e=>/timestamp|datetime|time/i.test(e||""),S3=e=>ktt(e)?Ntt:Fle;function Ple(e){const{controlId:t,onCommit:n}=e,[r,s]=v.useState(t);return l.jsx(m.Input,{size:"xs",value:r,onChange:o=>s(o.target.value),onBlur:()=>{n(r),s(o=>o.trim().length===0?t:o)}})}function X7(e){const{control:t,onChange:n}=e,r=m.ensureManualSource(t),s=r.source.kind==="manual"?r.source.options:[],i=!!m.getPresetOptionsForControlType(t.type),a=h=>{n({...r,source:{kind:"manual",options:h}})},c=()=>{const h=s.length+1,p=`Option ${h}`;a([...s,{label:p,value:m.slugifyControlValue(p)||`option_${h}`}])},u=(h,p)=>{a(s.map((g,b)=>{if(b!==h)return g;const x=m.slugifyControlValue(g.label),y=m.slugifyControlValue(p)||g.value,S=g.value.trim().length===0||g.value===x;return{...g,label:p,value:S?y:g.value}}))},d=(h,p)=>{a(s.map((g,b)=>b===h?{...g,value:p}:g))},f=h=>{a(s.filter((p,g)=>g!==h))};return l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Options"}),!i&&l.jsxs(m.Button,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:c,children:[l.jsx(dr,{className:"mr-1 h-3 w-3"}),"Add option"]})]}),s.length===0?l.jsx("div",{className:"rounded-md border border-dashed p-2.5 text-xs text-muted-foreground",children:"No options yet."}):l.jsxs("div",{className:"rounded-md border",children:[l.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_32px] gap-2 border-b bg-muted/50 px-2.5 py-1.5",children:[l.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:"Label"}),l.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:"Value"}),l.jsx("span",{})]}),s.map((h,p)=>l.jsxs("div",{className:m.cn("grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_32px] items-center gap-2 px-2.5 py-1.5",p<s.length-1&&"border-b"),children:[l.jsx(m.Input,{size:"xs",value:h.label,placeholder:"Label",className:"h-7 text-xs",onChange:g=>u(p,g.target.value),disabled:i}),l.jsx(m.Input,{size:"xs",value:h.value,placeholder:"Value",className:"h-7 text-xs",onChange:g=>d(p,g.target.value),disabled:i}),l.jsx(m.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>f(p),disabled:i,children:l.jsx(yl,{className:"h-3.5 w-3.5"})})]},`${t.id}-option-${p}`))]})]})}function _tt(e){return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Choices (built in)"}),l.jsx("div",{className:"rounded-md border bg-muted/20 px-3 py-2 text-sm text-muted-foreground",children:e.options.map(t=>t.label).join(" · ")})]})}function jtt(e){return e?m.getDataType(e.dataType||"")==="date":!1}function Ett(e){return e!=null&&e.granularity?e.granularity:S3(e==null?void 0:e.dataType)[0]||"day"}function Dtt(e,t){var n;return e!=null&&e.dateFormat?e.dateFormat:((n=j0(t)[0])==null?void 0:n.value)||"YYYY-MM-DD"}function Itt(e){var N,k;const{control:t,choices:n,choiceLabel:r,emptyMessage:s,onChange:o}=e,i=m.ensureManualSource(t),a=i.source.kind==="manual"?i.source.options:[],c=new Map(a.map(_=>[_.value,_])),u=new Set(a.map(_=>_.value)),[d,f]=v.useState(""),[h,p]=v.useState(((N=a[0])==null?void 0:N.value)||null),g=_=>{o({...i,source:{kind:"manual",options:_}})},b=(_,E)=>{g(a.map(D=>D.value===_?E(D):D))},x=n.filter(({option:_})=>u.has(_.value)),y=h&&a.some(_=>_.value===h)?h:((k=a[0])==null?void 0:k.value)||null,S=x.find(({option:_})=>_.value===y)||x[0],w=n.filter(({option:_})=>{var D,j;if(u.has(_.value))return!1;const E=d.trim().toLowerCase();return E?_.label.toLowerCase().includes(E)||_.value.toLowerCase().includes(E)||((j=(D=_.presentation)==null?void 0:D.customFormat)==null?void 0:j.toLowerCase().includes(E)):!0}),C=(_,E)=>{var R,B,z;const D=c.get(_.value),j=E?m.getDataType(E.dataType||""):void 0,I=jtt(E),T=I?((R=D==null?void 0:D.presentation)==null?void 0:R.granularity)??Ett(E):void 0,F=I&&T?((B=D==null?void 0:D.presentation)==null?void 0:B.dateFormat)??Dtt(E,T):void 0,P=I&&T?j0(T):[];return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsxs("p",{className:"text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Editing selected ",r.slice(0,-1).toLowerCase()]}),l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[l.jsx("div",{className:"shrink-0",children:l.jsx(rC,{dataType:(E==null?void 0:E.dataType)||"string"})}),l.jsx("span",{className:"text-sm font-medium text-foreground/90",children:(D==null?void 0:D.label)??_.label}),j?l.jsx(Yr,{variant:"outline",className:"text-[11px]",children:j}):null,"aggregate"in(E||{})&&typeof(E==null?void 0:E.aggregate)=="string"?l.jsx(Yr,{variant:"secondary",className:"text-[11px]",children:E.aggregate}):null]}),E!=null&&E.qualifiedFieldName?l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:E.qualifiedFieldName}):null]}),l.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(m.Label,{className:"text-[11px] text-muted-foreground",children:"Shown as"}),l.jsx(m.Input,{size:"xs",value:(D==null?void 0:D.label)??_.label,onChange:U=>b(_.value,Y=>({...Y,label:U.target.value}))})]}),I&&T?l.jsxs("div",{className:"space-y-1",children:[l.jsx(m.Label,{className:"text-[11px] text-muted-foreground",children:"Granularity"}),l.jsxs(m.Select,{value:T,onValueChange:U=>{var K;const Y=U,O=((K=j0(Y)[0])==null?void 0:K.value)||"YYYY-MM-DD";b(_.value,q=>{var M,G;return{...q,presentation:{...q.presentation,granularity:Y,dateFormat:O,customFormat:((M=q.presentation)==null?void 0:M.dateFormat)==="custom"?(G=q.presentation)==null?void 0:G.customFormat:void 0}}})},children:[l.jsx(m.SelectTrigger,{size:"xs",children:l.jsx(m.SelectValue,{})}),l.jsx(m.SelectContent,{children:S3(E.dataType).map(U=>l.jsx(m.SelectItem,{value:U,children:U.charAt(0).toUpperCase()+U.slice(1)},U))})]})]}):null,I&&T?l.jsx("div",{className:"space-y-1 md:col-span-2",children:l.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(m.Label,{className:"text-[11px] text-muted-foreground",children:"Date format"}),l.jsxs(m.Select,{value:F,onValueChange:U=>b(_.value,Y=>{var O;return{...Y,presentation:{...Y.presentation,granularity:T,dateFormat:U,customFormat:U==="custom"?((O=Y.presentation)==null?void 0:O.customFormat)||"":void 0}}}),children:[l.jsx(m.SelectTrigger,{size:"xs",children:l.jsx(m.SelectValue,{})}),l.jsx(m.SelectContent,{children:P.map(U=>l.jsx(m.SelectItem,{value:U.value,children:U.label},U.value))})]})]}),F==="custom"?l.jsxs("div",{className:"space-y-1",children:[l.jsx(m.Label,{className:"text-[11px] text-muted-foreground",children:"Custom format"}),l.jsx(m.Input,{size:"xs",value:((z=D==null?void 0:D.presentation)==null?void 0:z.customFormat)||"",placeholder:"MMM YYYY",onChange:U=>b(_.value,Y=>({...Y,presentation:{...Y.presentation,granularity:T,dateFormat:"custom",customFormat:U.target.value}}))})]}):null]})}):null]})]})};return l.jsxs("div",{className:"grid gap-4 md:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]",children:[l.jsxs("div",{className:"flex min-h-0 flex-col gap-3 rounded-lg border bg-muted/10 p-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsxs(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Add ",r.toLowerCase()]}),l.jsxs("div",{className:"relative",children:[l.jsx(Ws,{className:"pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),l.jsx(m.Input,{size:"xs",value:d,name:`${t.id}-search-${r.toLowerCase()}`,placeholder:`Search ${r.toLowerCase()}…`,autoComplete:"off",onChange:_=>f(_.target.value),className:"pl-9 pr-9"}),d?l.jsx("button",{type:"button","aria-label":`Clear ${r.toLowerCase()} search`,className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>f(""),children:l.jsx(m.X,{className:"h-3.5 w-3.5"})}):null]})]}),n.length===0?l.jsx("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:s}):w.length===0?l.jsx("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:d.trim().length>0?"No matching fields found.":`All compatible ${r.toLowerCase()} are already selected.`}):l.jsx("div",{className:"h-[320px] overflow-y-auto pr-1",children:l.jsx("div",{className:"space-y-1",children:w.map(({option:_,target:E})=>{const D=E?m.getDataType(E.dataType||""):void 0;return l.jsxs("button",{type:"button",className:"group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all hover:bg-muted",onClick:()=>{g([...a,{..._}]),p(_.value),f("")},children:[l.jsx("div",{className:"shrink-0",children:l.jsx(rC,{dataType:(E==null?void 0:E.dataType)||"string"})}),l.jsxs("div",{className:"min-w-0 flex-1 overflow-hidden",children:[l.jsx("div",{className:"truncate text-sm text-foreground/85 group-hover/container:text-foreground",children:(E==null?void 0:E.label)||_.label}),E!=null&&E.qualifiedFieldName?l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:E.qualifiedFieldName}):null]}),l.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[D?l.jsx(Yr,{variant:"outline",className:"text-[11px]",children:D}):null,l.jsx(Yr,{variant:"secondary",className:"text-[11px]",children:"Add"})]})]},`${t.id}-available-${_.value}`)})})})]}),l.jsxs("div",{className:"flex min-h-0 flex-col gap-3 rounded-lg border bg-card p-3",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Selected ",r.toLowerCase()]}),l.jsx(Yr,{variant:"secondary",className:"text-[11px]",children:x.length})]}),x.length===0?l.jsx("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:"Choose at least one option from the catalog."}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"max-h-[220px] overflow-y-auto pr-1",children:l.jsx("div",{className:"space-y-1",children:x.map(({option:_,target:E})=>{const D=c.get(_.value),j=E?m.getDataType(E.dataType||""):void 0,I=(S==null?void 0:S.option.value)===_.value;return l.jsxs("div",{className:m.cn("flex items-center gap-2 rounded-lg border p-2 transition-colors",I?"border-foreground/20 bg-muted/40":"border-transparent hover:bg-muted/20"),children:[l.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-3 text-left",onClick:()=>p(_.value),children:[l.jsx("div",{className:"shrink-0",children:l.jsx(rC,{dataType:(E==null?void 0:E.dataType)||"string"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium text-foreground/90",children:(D==null?void 0:D.label)??_.label}),E!=null&&E.qualifiedFieldName?l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:E.qualifiedFieldName}):null]})]}),l.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[j?l.jsx(Yr,{variant:"outline",className:"text-[11px]",children:j}):null,l.jsx(m.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7","aria-label":`Remove ${(D==null?void 0:D.label)??_.label}`,onClick:()=>{var F;const T=a.filter(P=>P.value!==_.value);g(T),y===_.value&&p(((F=T[0])==null?void 0:F.value)||null)},children:l.jsx(m.X,{className:"h-3.5 w-3.5"})})]})]},`${t.id}-selected-${_.value}`)})})}),l.jsx("div",{className:"rounded-lg border bg-muted/5 p-3",children:S?C(S.option,S.target):l.jsx("div",{className:"text-xs text-muted-foreground",children:"Select a field to configure how it appears in the control."})})]})]})]})}function Ole(e){if(e.participants.length===0)return null;const t=new Set(e.selectedCardIds);return l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Cards using this shared control"}),l.jsx("div",{className:"space-y-2 rounded-md border p-3",children:e.participants.map(n=>l.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[l.jsx(Ln,{checked:t.has(n.cardId),onCheckedChange:r=>{if(r===!0){e.onChange([...e.selectedCardIds,n.cardId]);return}e.onChange(e.selectedCardIds.filter(s=>s!==n.cardId))}}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"font-medium",children:n.title}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:[n.choiceCount," ",e.type==="field_selector"?"compatible group-by fields":"compatible metrics"]})]})]},n.cardId))})]})}function Ttt(e){const t=e.value===!0?"true":"false";return l.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[l.jsx(m.Button,{type:"button",variant:t==="true"?"default":"outline",onClick:()=>e.onChange(!0),children:"On"}),l.jsx(m.Button,{type:"button",variant:t==="false"?"default":"outline",onClick:()=>e.onChange(!1),children:"Off"})]})}function Mtt(e){return e.scope==="dashboard"&&(e.type==="enum"||e.type==="multi_enum")}const Lle={kind:"sql_query",connectionId:"",sql:"",valueColumn:""};function Q7(e){return{kind:"manual",options:e.options.map(t=>({...t,...t.presentation?{presentation:{...t.presentation}}:{}}))}}function J7(e){return{...e}}function Att(e){return e.source.kind==="sql_query"?e.source:Lle}function $le(e){const t=C3(e);return JSON.stringify({controlId:e.controlId,source:zie(e.source),controlDefinitions:Bie(t.controlDefinitions),controlValues:$ie(t.controlValues,t.controlDefinitions),activeFilters:e.activeFiltersOverride??null})}function C3(e){const t=Oie(e.previewControlDefinitions),n={...e.previewControlValues||{}};delete n[e.controlId];const r=Lie(n,t);return{controlDefinitions:t,controlValues:r}}function Rtt(e){const[t,n]=v.useState(null),r=v.useRef(e);return v.useEffect(()=>{r.current!==e&&(r.current=e,n(null))},[e]),{requestedForCurrentKey:t===e,markCurrentKeyRequested:()=>n(e)}}function Ftt(e){var w;const{control:t,onChange:n,previewControlDefinitions:r,previewControlValues:s,activeFiltersOverride:o}=e,i=Att(t),{connections:a,isPending:c}=Xc(),u=t.id||"preview",d=i.connectionId.trim().length>0&&i.sql.trim().length>0&&i.valueColumn.trim().length>0,f=C3({controlId:u,previewControlDefinitions:r,previewControlValues:s}),h=$le({controlId:u,source:i,previewControlDefinitions:r,previewControlValues:s,activeFiltersOverride:o}),{requestedForCurrentKey:p,markCurrentKeyRequested:g}=Rtt(h),b=ob({controlId:u,source:d?i:void 0,enabled:p&&d,controlDefinitionsOverride:f.controlDefinitions,controlValuesOverride:f.controlValues,activeFiltersOverride:o}),x=C=>{const N={...i,...C,kind:"sql_query"};(!N.labelColumn||N.labelColumn.trim().length===0)&&delete N.labelColumn,n({...t,source:N})},y=m.getRequestErrorMessage(b.error,""),S=b.options;return v.useEffect(()=>{var k;if(i.connectionId||a.length!==1)return;const C=(k=a[0])==null?void 0:k.id;if(!C)return;const N={...i,kind:"sql_query",connectionId:C};(!N.labelColumn||N.labelColumn.trim().length===0)&&delete N.labelColumn,n({...t,source:N})},[a,t,i,n]),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Connection"}),l.jsxs(m.Select,{value:i.connectionId,onValueChange:C=>{x({connectionId:C})},disabled:c||a.length===0,children:[l.jsx(m.SelectTrigger,{size:"xs",children:l.jsx(m.SelectValue,{placeholder:c?"Loading connections…":a.length===0?"No connections available":"Select a connection"})}),l.jsx(m.SelectContent,{children:a.map(C=>l.jsx(m.SelectItem,{value:C.id,children:C.name},C.id))})]})]}),i.connectionId.trim().length===0?l.jsxs("div",{className:"flex min-h-[200px] flex-col items-center justify-center gap-1 rounded-control border border-border/60 bg-muted/20 px-4 py-8 text-center",children:[l.jsx("p",{className:"text-[13px] font-medium text-foreground",children:"Pick a connection above"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Then write your SQL query to source options."})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL"}),l.jsx("div",{className:"h-24 w-full overflow-hidden rounded-control border border-input",onKeyDown:C=>C.stopPropagation(),children:l.jsx(m.CodeEditor,{value:i.sql,onValueChange:C=>x({sql:C}),language:"sql-jinja",embedded:!0,hideLineNumbers:!0,dense:!0,ariaLabel:"Control options SQL query",placeholder:"SELECT id, name FROM segments WHERE account_id = [[param.tenantId]]"})})]}),l.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Value column"}),l.jsx(m.Input,{size:"xs",value:i.valueColumn,placeholder:"id",onChange:C=>{x({valueColumn:C.target.value})}})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label column (optional)"}),l.jsx(m.Input,{size:"xs",value:i.labelColumn||"",placeholder:"name",onChange:C=>{x({labelColumn:C.target.value})}})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(m.Button,{type:"button",variant:"outline",size:"xs",disabled:!d||b.isFetching,onClick:()=>{if(p){b.refetch();return}g()},children:b.isFetching?"Loading…":"Preview options"}),p&&!b.isFetching&&b.data?l.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[S.length," option",S.length===1?"":"s",(w=b.metadata)!=null&&w.truncated?" (truncated)":""]}):null]}),p&&b.isError?l.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Preview unavailable",y?` — ${y}`:""]}):null]})]})}function Ptt(e){const{control:t,onChange:n,controlLifecycle:r="edit"}=e,s=t.source.kind==="sql_query"?"sql_query":"manual",o=v.useRef(t.source.kind==="manual"?Q7(t.source):null),i=v.useRef(t.source.kind==="manual"?t.requiredAtExecution:null),a=v.useRef(t.source.kind==="sql_query"?J7(t.source):null);t.source.kind==="manual"?(o.current=Q7(t.source),i.current=t.requiredAtExecution):t.source.kind==="sql_query"&&(a.current=J7(t.source));const c=u=>{if(u!==s){if(u==="manual"){n({...t,source:o.current||{kind:"manual",options:[]},requiredAtExecution:i.current??t.requiredAtExecution});return}n({...t,source:a.current||Lle,requiredAtExecution:t.initialValueStrategy==="embed_required"?!0:r==="create"?!1:t.requiredAtExecution})}};return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Option source"}),l.jsxs(Ia,{value:s,onValueChange:u=>c(u),className:"flex flex-col gap-1.5",children:[l.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[l.jsx(js,{value:"manual",className:"mt-0.5"}),l.jsxs("span",{children:[l.jsx("span",{className:"font-medium text-foreground",children:"Manual"}),l.jsx("span",{className:"ml-1 text-muted-foreground",children:"— enter label/value rows"})]})]}),l.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[l.jsx(js,{value:"sql_query",className:"mt-0.5"}),l.jsxs("span",{children:[l.jsx("span",{className:"font-medium text-foreground",children:"SQL query"}),l.jsx("span",{className:"ml-1 text-muted-foreground",children:"— resolve options from a database query at runtime"})]})]})]})]})}function zle(e){const t=m.getPresetOptionsForControlType(e.control.type),n=e.control.source.kind==="sql_query"?e.control:m.ensureManualSource(e.control),r=e.control.type==="field_selector"?e.availableFieldChoices||[]:e.control.type==="metric_selector"?e.availableMetricChoices||[]:[];if(t)return l.jsx(_tt,{options:t});if(n.type==="field_selector"||n.type==="metric_selector"){const s=n.type==="field_selector"?"Fields":"Metrics",o=n.type==="field_selector"?"No valid group-by fields are available yet. Add fields to the card first.":"No valid metrics are available yet. Add metrics to the card first.";return l.jsx(Itt,{control:n,choices:r,choiceLabel:s,emptyMessage:o,onChange:e.onChange})}return m.needsManualOptions(n)?Mtt(n)?l.jsxs("div",{className:"space-y-3",children:[l.jsx(Ptt,{control:n,onChange:e.onChange,controlLifecycle:e.controlLifecycle}),n.source.kind==="sql_query"?l.jsx(Ftt,{control:n,onChange:e.onChange,previewControlDefinitions:e.previewControlDefinitions,previewControlValues:e.previewControlValues,activeFiltersOverride:e.activeFiltersOverride}):l.jsx(X7,{control:n,onChange:e.onChange})]}):l.jsx(X7,{control:n,onChange:e.onChange}):null}function Ble(e){const{control:t,value:n,onChange:r,allowNoDefault:s=!1,allowCardDefault:o=!1,hint:i}=e;if(t.source.kind==="sql_query")return l.jsx(Ltt,{control:t,value:n,onChange:r,allowNoDefault:s,allowCardDefault:o,hint:i,previewControlDefinitions:e.previewControlDefinitions,previewControlValues:e.previewControlValues,activeFiltersOverride:e.activeFiltersOverride});const a=m.ensureManualSource(t),c=m.getDefaultValueForType(t,n),d=m.getPresetOptionsForControlType(t.type)??(a.source.kind==="manual"?a.source.options:[]),f=t.type==="enum"||t.type==="field_selector"||t.type==="metric_selector"||t.type==="aggregation_selector"||t.type==="grain_selector";return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default"}),t.type==="boolean"?l.jsx(Ttt,{value:c,onChange:r}):f&&d.length>0?l.jsx(Vle,{controlType:t.type,options:d,value:c,onChange:r,allowNoDefault:s,allowCardDefault:o}):f?l.jsx(m.Input,{size:"xs",value:"",placeholder:"Add choices first",disabled:!0,readOnly:!0}):l.jsx(m.Input,{size:"xs",value:Array.isArray(c)?c.join(", "):String(c??""),placeholder:t.type==="multi_enum"?"value_one, value_two":"Default value",onChange:h=>r(m.parseControlDefaultValue(a,h.target.value))}),i?l.jsx("p",{className:"text-[11px] text-muted-foreground",children:i}):null]})}function Vle(e){const{controlType:t,options:n,value:r,onChange:s,allowNoDefault:o=!1,allowCardDefault:i=!1}=e,a=i&&m.supportsCardDefaultValue(t),c=r===void 0&&o?m.CONTROL_SELECT_UI_VALUES.noDefault:r===Cr.CONTROL_CARD_DEFAULT_VALUE&&a?m.CONTROL_SELECT_UI_VALUES.cardDefault:typeof r=="string"?m.findControlSelectOptionUiValue(n,r):void 0;return l.jsxs(m.Select,{value:c,onValueChange:u=>{if(u===m.CONTROL_SELECT_UI_VALUES.noDefault){s(void 0);return}if(u===m.CONTROL_SELECT_UI_VALUES.cardDefault){s(Cr.CONTROL_CARD_DEFAULT_VALUE);return}const d=m.getControlSelectOptionFromUiValue(n,u);d&&s(d.value)},children:[l.jsx(m.SelectTrigger,{size:"xs",children:l.jsx(m.SelectValue,{placeholder:"Choose a default"})}),l.jsxs(m.SelectContent,{children:[o?l.jsx(m.SelectItem,{value:m.CONTROL_SELECT_UI_VALUES.noDefault,children:"No default"}):null,a?l.jsx(m.SelectItem,{value:m.CONTROL_SELECT_UI_VALUES.cardDefault,children:"Card default"}):null,n.map((u,d)=>l.jsx(m.SelectItem,{value:m.getControlSelectOptionUiValue(d),children:u.label},u.value))]})]})}function Ott(e){var a;const{options:t,value:n,onChange:r,allowNoDefault:s=!1}=e,o=m.normalizeControlStringArrayValue(n),i=o.length===0?s?"No default":"Choose defaults":o.length===1?((a=t.find(c=>c.value===o[0]))==null?void 0:a.label)||o[0]:`${o.length} selected`;return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(m.Popover,{children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsx(m.Button,{type:"button",variant:"outline",className:"w-full justify-between",children:l.jsx("span",{className:"truncate",children:i})})}),l.jsx(m.PopoverContent,{align:"start",className:"w-64",children:l.jsx("div",{className:"space-y-2",children:t.map(c=>{const u=o.includes(c.value);return l.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[l.jsx(Ln,{checked:u,onCheckedChange:d=>{const f=d?[...o,c.value]:o.filter(h=>h!==c.value);r(f.length>0?f:void 0)}}),l.jsx("span",{children:c.label})]},c.value)})})})]}),s&&o.length>0?l.jsx(m.Button,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground",onClick:()=>r(void 0),children:"Clear"}):null]})}function Ltt(e){const{control:t,value:n,onChange:r,allowNoDefault:s=!1,allowCardDefault:o=!1,hint:i,previewControlDefinitions:a,previewControlValues:c,activeFiltersOverride:u}=e,d=t.source,f=t.id||"preview",h=d.connectionId.trim().length>0&&d.sql.trim().length>0&&d.valueColumn.trim().length>0,p=C3({controlId:f,previewControlDefinitions:a,previewControlValues:c});$le({controlId:f,source:d,previewControlDefinitions:a,previewControlValues:c,activeFiltersOverride:u});const g=ob({controlId:f,source:h?d:void 0,enabled:!1,controlDefinitionsOverride:p.controlDefinitions,controlValuesOverride:p.controlValues,activeFiltersOverride:u}),b=g.data!==void 0&&!g.isError,x=g.options.map(C=>({value:C.value,label:C.label})),y=t.type==="multi_enum"?m.normalizeControlStringArrayValue(n):m.getDefaultValueForType(t,n),S=(()=>{const C=[...x],N=new Set(C.map(_=>_.value)),k=_=>{typeof _!="string"||_.length===0||N.has(_)||(N.add(_),C.push({value:_,label:_}))};return Array.isArray(y)?y.forEach(k):k(y),C})(),w=b&&S.length>0;return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(m.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default"}),w&&t.type==="multi_enum"?l.jsx(Ott,{options:S,value:y,onChange:r,allowNoDefault:s}):w?l.jsx(Vle,{controlType:t.type,options:S,value:y,onChange:r,allowNoDefault:s,allowCardDefault:o}):l.jsx(m.Input,{size:"xs",value:"",placeholder:h?"Preview options above to pick a default (optional)":"Complete the SQL source to pick a default (optional)",disabled:!0,readOnly:!0}),i?l.jsx("p",{className:"text-[11px] text-muted-foreground",children:i}):null]})}function $tt(e){const{control:t,onChange:n}=e;return l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"space-y-1",children:l.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx(Ln,{checked:t.hidden===!0,onCheckedChange:r=>n({...t,hidden:r===!0})}),"Hide control UI from viewers"]})}),l.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx(Ln,{checked:t.locked===!0,onCheckedChange:r=>n({...t,locked:r===!0})}),"Locked"]})]})}function Hle(e){const t=C0(e);return e.scope==="dashboard"?t==="advanced"?"More controls":"dashboard toolbar":t==="advanced"?"More options":"card header"}function ztt(e){const t=new Map;for(const n of e.controls||[])t.set(n.id,0);for(const n of m.getDashboardCards(e)){const r=new Set(Xv(n));for(const s of r)t.has(s)&&t.set(s,(t.get(s)||0)+1)}return Object.fromEntries((e.controls||[]).map(n=>{if(n.hidden)return[n.id,{tone:"default",status:"Hidden from viewers",helper:"This control can still be used by connected cards, but it will not appear in the dashboard UI."}];const r=t.get(n.id)||0,s=Hle(n);return r===0?[n.id,{tone:"warning",status:"Not used by any cards yet",helper:`This control is already available in the ${s}. Next: open a card's Controls and either bind this control or reference [[param.${n.id}]] in SQL.`}]:[n.id,{tone:"success",status:`Used in ${r} ${r===1?"card":"cards"}`,helper:`Available in the ${s}. ${r===1?"That card":"Those cards"} will respond when the value changes.`}]}))}function Btt(e){const t=new Set(Xv(e.card));return Object.fromEntries(e.controls.map(n=>{var s;const r=Hle(n);return n.hidden?[n.id,{tone:"default",status:"Hidden from viewers",helper:"This control is available for runtime state but will not appear in this card UI."}]:t.has(n.id)?[n.id,{tone:"success",status:"Used by this card",helper:`Available in the ${r} for this card.`}]:[n.id,{tone:"warning",status:"Not used by this card yet",helper:(s=e.card)!=null&&s.sql?`Reference [[param.${n.id}]] in this card's SQL to make the card respond to it.`:"Choose what this control changes below to make this card respond to it."}]}))}function Vtt(e){let t=0,n=0,r=0;const s=[];for(const o of m.getDashboardCards(e.dashboard)){if(!new Set(Xv(o)).has(e.controlId))continue;t+=1,s.push(o.title||o.id),Yse({sql:o.sql,controlBindings:o.controlBindings}).some(u=>u.controlId===e.controlId)&&(n+=1),(o.controlBindings||[]).some(u=>u.target!=="sql_param"&&u.controlId===e.controlId)&&(r+=1)}return{totalCards:t,sqlCards:n,configCards:r,cardTitles:s}}function Ule(e){var n;const t=new Map;for(const r of m.getDashboardCards(e))for(const s of r.controlBindings||[])s.target!=="config_field_selector"&&s.target!=="config_metric_selector"||(t.has(s.controlId)||t.set(s.controlId,new Set),(n=t.get(s.controlId))==null||n.add(r.id));return Object.fromEntries(Array.from(t.entries()).map(([r,s])=>[r,Array.from(s)]))}function Htt(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).filter(r=>r.type!=="file"&&r.type!=="url"&&r.type!=="upload").map(r=>({cardId:e.id,target:r}))}function Utt(e){if(e.type==="model")return`model:${e.connectionId}:${e.id}`;if(e.type==="dataset"){const t=e;return`dataset:${t.connectionId}:${t.domainId}:${t.name}`}return`table:${e.connectionId}:${e.database||""}:${e.schema||""}:${e.name}`}function Wtt(e){const t=new Map;return e.flatMap(n=>Htt(n)).forEach(({cardId:n,target:r})=>{const s=Utt(r),o=t.get(s);if(!o){t.set(s,{key:s,cardIds:[n],target:r});return}o.cardIds.includes(n)||o.cardIds.push(n)}),Array.from(t.values())}function qtt(e){if(e.type==="dataset"){const t=e;return!!(t.connectionId&&t.domainId&&t.name)}if(e.type==="model"){const t=e;return!!(t.connectionId&&t.id)}return!!(e.connectionId&&e.name)}function Ytt(e){if(e.type==="model"){const t=e;return{connection_id:t.connectionId,datamodel_id:t.id,database_name:"",schema_name:"",table_name:""}}if(e.type==="dataset"){const t=e;return{connection_id:t.connectionId,domain_id:t.domainId,dataset_name:t.name}}return{connection_id:e.connectionId,datamodel_id:"",database_name:e.database,schema_name:e.schema,table_name:e.name}}function Gtt(e){const{target:t,column:n}=e,r=m.getQualifiedEntityName(t);return{id:`${t.name}-${n.column_name}`,name:n.column_name,qualifiedFieldName:n.qualifiedFieldName||n.column_name,dataType:n.data_type,label:n.label||n.column_name,description:n.description||"",qualifiedEntityName:r,entityId:t.id||t.id||t.name,entityName:t.name,entityType:t.type,role:n.role==="metric"?"metric":void 0,expression:n.expression,calculatedFormula:n.calculatedFormula,format:m.fromSemanticFormat(n.format)}}function Wle(e){const{tokenProps:t}=Ct(),n=m.useDashboardStore(c=>c.authToken),r=v.useMemo(()=>Wtt(e),[e]),s=hg({queries:r.map(({key:c,target:u})=>({queryKey:["dashboard-structural-columns",c],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",Ytt(u)),enabled:!!(n!=null&&n.accessToken)&&qtt(u)}))}),o=s.some(c=>c.isPending&&c.fetchStatus==="fetching"),i=v.useMemo(()=>{const c=new Map;return s.forEach((u,d)=>{const f=r[d],h=f==null?void 0:f.target;if(!f||!h||!u.data)return;const p=[...(u.data.columns||[]).map(g=>Gtt({target:h,column:g})),...u.data.calculatedFields||[]];f.cardIds.forEach(g=>{c.set(g,[...c.get(g)||[],...p])})}),c},[s,r]);return{participants:v.useMemo(()=>e.map(c=>{var b,x,y,S,w;const u=i.get(c.id)||[],d=((y=(x=(b=c.config)==null?void 0:b.metricColumns)==null?void 0:x[0])==null?void 0:y.aggregate)||"SUM",f=m.buildDashboardFieldSelectorChoicesFromFields(u),h=m.buildDashboardMetricSelectorChoicesFromFields(u,d),p=m.getFieldSelectorChoicesForCard(c),g=m.getMetricSelectorChoicesForCard(c);return{cardId:c.id,title:c.title||c.id,canBindStructuralControl:!!c.config,fieldChoices:f.choices.length>0?f.choices:p,metricChoices:h.choices.length>0?h.choices:g,fieldTargetMap:f.choices.length>0?f.targetMap:Object.fromEntries((((S=c.config)==null?void 0:S.groupByColumns)||[]).filter(C=>typeof C.id=="string").map(C=>[C.id,C])),metricTargetMap:h.choices.length>0?h.targetMap:Object.fromEntries((((w=c.config)==null?void 0:w.metricColumns)||[]).filter(C=>typeof C.id=="string").map(C=>[C.id,C]))}}),[e,i]),isLoading:o}}function qle({control:e,defaultValue:t,defaultPlacement:n,placementOptions:r,previewControlDefinitions:s,previewControlValues:o,availableFieldChoices:i=[],availableMetricChoices:a=[],structuralParticipantSelector:c,allowCardDefault:u=!1,allowControlIdEdit:d=!0,showPlacementSelect:f=!0,showViewerVisibilityToggle:h=!0,activeFiltersOverride:p,onChangeControl:g,onChangeDefaultValue:b,onCommitControlId:x}){const y="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",S=d&&!!x,w=f?S?"grid grid-cols-3 gap-2":"grid grid-cols-2 gap-2":S?"grid grid-cols-2 gap-2":"grid grid-cols-1 gap-2";return l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:w,children:[l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx(m.Label,{className:y,children:"Label"}),l.jsx(m.Input,{size:"xs",value:e.label,placeholder:"Control label",onChange:C=>g(N=>({...N,label:C.target.value}))})]}),S?l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx(m.Label,{className:y,children:"Variable name"}),l.jsx(Ple,{controlId:e.id,onCommit:x},e.id)]}):null,f?l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx(m.Label,{className:y,children:"Show in"}),l.jsxs(m.Select,{value:e.placement||n,onValueChange:C=>g(N=>({...N,placement:C})),children:[l.jsx(m.SelectTrigger,{size:"xs",children:l.jsx(m.SelectValue,{})}),l.jsx(m.SelectContent,{children:r.map(C=>l.jsx(m.SelectItem,{value:C.value,children:C.label},C.value))})]})]}):null]}),c,l.jsx(zle,{control:e,availableFieldChoices:i,availableMetricChoices:a,previewControlDefinitions:s,previewControlValues:o,activeFiltersOverride:p,controlLifecycle:"edit",onChange:C=>g(()=>C)}),e.initialValueStrategy==="saved_default"&&l.jsx(Ble,{control:e,value:t,allowNoDefault:!0,allowCardDefault:u,previewControlDefinitions:s,previewControlValues:o,activeFiltersOverride:p,onChange:b}),l.jsx("div",{className:"grid grid-cols-1 gap-2",children:l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx(m.Label,{className:y,children:"Initial value"}),l.jsxs(m.Select,{value:e.initialValueStrategy,onValueChange:C=>g(N=>({...N,initialValueStrategy:C})),children:[l.jsx(m.SelectTrigger,{size:"xs",children:l.jsx(m.SelectValue,{})}),l.jsx(m.SelectContent,{children:m.INITIAL_VALUE_STRATEGY_OPTIONS.map(C=>l.jsx(m.SelectItem,{value:C.value,children:C.label},C.value))})]})]})}),l.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx(Ln,{checked:e.showLabel??!0,onCheckedChange:C=>g(N=>({...N,showLabel:C===!0}))}),"Show label in toolbar"]}),h?l.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx(Ln,{checked:e.hidden===!0,onCheckedChange:C=>g(N=>({...N,hidden:C===!0}))}),"Hide control UI from viewers"]}):null]})}function Yle({open:e,onOpenChange:t,trigger:n,title:r,subtitle:s,description:o,body:i,footer:a,onClose:c,useDialog:u=!1,deleteDialogOpen:d,onDeleteDialogOpenChange:f,deleteDescription:h,deleteDetails:p,onConfirmDelete:g}){const b=Zc("interactive"),x=l.jsx(Ktt,{title:r,subtitle:s,onClose:c,titleAsDialogTitle:u});return l.jsxs(l.Fragment,{children:[u?l.jsxs(Oo,{open:e,onOpenChange:t,children:[l.jsx(oG,{asChild:!0,children:n}),l.jsxs(mo,{showCloseButton:!1,className:"flex max-h-[88vh] flex-col overflow-hidden rounded-control border border-border/60 p-0 shadow-sm sm:max-w-[600px] sm:rounded-control",style:b.controlStyle,onInteractOutside:y=>y.preventDefault(),children:[l.jsx(si,{className:"sr-only",children:o}),x,l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i}),l.jsx("div",{className:"shrink-0 border-t border-border/60 px-4 py-2.5",children:a})]})]}):l.jsxs(m.Popover,{open:e,onOpenChange:t,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:n}),l.jsxs(m.PopoverContent,{align:"start",className:"m-2 flex h-[440px] max-h-[85vh] w-[480px] max-w-[95vw] flex-col overflow-hidden rounded-control border border-border/60 p-0 shadow-sm",style:b.controlStyle,onMouseDown:y=>y.stopPropagation(),children:[x,l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i}),l.jsx("div",{className:"shrink-0 border-t border-border/60 px-4 py-2.5",children:a})]})]}),l.jsx(Lc,{open:d,onOpenChange:f,children:l.jsxs(vl,{style:b.controlStyle,children:[l.jsxs(wl,{children:[l.jsx(Cl,{children:"Delete control?"}),l.jsx(Nl,{children:h}),p]}),l.jsxs(Sl,{children:[l.jsx(_l,{children:"Cancel"}),l.jsx(kl,{onClick:g,children:"Delete control"})]})]})})]})}function Ktt({title:e,subtitle:t,onClose:n,titleAsDialogTitle:r}){const s="truncate text-[13px] font-medium text-foreground",o=r?l.jsx(go,{className:s,title:e,children:e}):l.jsx("span",{className:s,title:e,children:e});return l.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(m.SlidersHorizontal,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o,l.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:t})]}),l.jsx("button",{type:"button",onClick:n,"aria-label":"Close",className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3.5 w-3.5"})})]})}function Ztt({control:e}){const t=m.useDashboardStore(H=>H.dashboard),{setDashboardControlsModel:n}=m.useDashboardActions(),[r,s]=v.useState(!1),[o,i]=v.useState(!1),a=m.getPlacementOptionsForScope("dashboard"),c=m.getDefaultPlacement("dashboard"),{participants:u}=Wle(m.getDashboardCards(t)),d=Ule(t),f=v.useMemo(()=>d[e.id]||[],[d,e.id]),h=m.isStructuralSelectorControlType(e.type)?m.getEligibleParticipantsForStructuralControl(u,e.type):[],p=m.resolveAuthoringControlDefaultValue({control:e,defaultValues:t.defaultControlValues||{}}),g=v.useCallback(H=>({...H,source:H.source.kind==="manual"?{kind:"manual",options:H.source.options.map(A=>({...A,presentation:A.presentation?{...A.presentation}:void 0}))}:{...H.source}}),[]),b=v.useCallback(()=>({control:g(e),selectedCardIds:[...f],defaultValue:p}),[g,e,p,f]),[x,y]=v.useState(b),S=v.useRef(p),w=x.control,C=x.selectedCardIds,N=m.isStructuralSelectorControlType(w.type)?m.getCompatibleStructuralChoiceCatalog({controlType:w.type,participants:u,selectedCardIds:C}):{choices:[],fieldTargetMap:{},metricTargetMap:{}},k=w.type==="field_selector"?N.choices.map(H=>({option:H,target:N.fieldTargetMap[H.value]})):Array.from(new Map(u.flatMap(H=>H.fieldChoices.map(A=>{var W;return[A.value,{option:A,target:(W=H.fieldTargetMap)==null?void 0:W[A.value]}]}))).values()),_=w.type==="metric_selector"?N.choices.map(H=>({option:H,target:N.metricTargetMap[H.value]})):Array.from(new Map(u.flatMap(H=>H.metricChoices.map(A=>{var W;return[A.value,{option:A,target:(W=H.metricTargetMap)==null?void 0:W[A.value]}]}))).values()),E=v.useMemo(()=>(t.controls||[]).map(H=>H.id===e.id?w:H),[e.id,t.controls,w]),D=v.useMemo(()=>m.buildAuthoringPreviewControlValues({controls:E,defaultValues:t.defaultControlValues||{},overrides:[{controlId:e.id,value:void 0},{controlId:w.id,value:x.defaultValue}]}),[e.id,t.defaultControlValues,x.defaultValue,w.id,E]),j=v.useMemo(()=>Vtt({dashboard:t,controlId:e.id}),[t,e.id]),I=H=>{y(A=>{const W=H(A.control);A.control.source.kind==="manual"&&W.source.kind==="sql_query"&&(S.current=A.defaultValue);const X=A.defaultValue===void 0&&A.control.source.kind==="sql_query"&&W.source.kind==="manual"?S.current:A.defaultValue,Z=m.getNextEditedControlDefaultValue({previousControl:A.control,nextControl:W,currentDefaultValue:X});return W.source.kind==="manual"&&(S.current=Z),{...A,control:W,defaultValue:Z}})},T=H=>{if(!m.isStructuralSelectorControlType(w.type))return;const A=m.getCompatibleStructuralChoiceCatalog({controlType:w.type,participants:u,selectedCardIds:H}),W=m.reconcileStructuralControlChoices({control:w,choices:A.choices});y(X=>({...X,selectedCardIds:H,control:W,defaultValue:m.getNextEditedControlDefaultValue({previousControl:X.control,nextControl:W,currentDefaultValue:X.defaultValue})}))},F=H=>{if(!H.trim())return;const A=J0(H);A!==e.id&&tie(t,{source:"dashboardControl",controlId:e.id}).includes(A)||y(W=>W.control.id===A?W:{...W,control:{...W.control,id:A}})},P=()=>{S.current=p,y(b()),s(!1)},R=()=>{const H={...t.defaultControlValues||{}};delete H[e.id];let A=x.control,W;if(m.isStructuralSelectorControlType(A.type)){const J=m.getCompatibleStructuralChoiceCatalog({controlType:A.type,participants:u,selectedCardIds:x.selectedCardIds});A=m.reconcileStructuralControlChoices({control:A,choices:J.choices}),W=Object.fromEntries(f.filter(re=>!x.selectedCardIds.includes(re)).map(re=>[re,void 0])),x.selectedCardIds.length>0&&A.source.kind==="manual"&&A.source.options.length>0&&Object.assign(W,m.buildStructuralControlBindingsForParticipants({control:A,participants:u,selectedCardIds:x.selectedCardIds}))}!m.isStructuralSelectorControlType(A.type)&&m.isStructuralSelectorControlType(e.type)&&(W=Object.fromEntries(f.map(J=>[J,void 0]))),A.initialValueStrategy==="saved_default"&&x.defaultValue!==void 0&&(H[A.id]=x.defaultValue),A={...A,defaultValue:H[A.id]},A=m.syncSqlQueryControlExecutionRequirement(A,H[A.id]);const X=(t.controls||[]).map(J=>J.id===e.id?A:J),Z={renamed:A.id!==e.id?{oldId:e.id,newId:A.id}:void 0,cardBindingsById:W,affectedBindingControlIds:m.isStructuralSelectorControlType(A.type)?[A.id]:m.isStructuralSelectorControlType(e.type)?[e.id]:void 0};n(X,H,Z),s(!1)},B=()=>{const H=(t.controls||[]).filter(W=>W.id!==e.id),A={...t.defaultControlValues||{}};delete A[e.id],n(H,A,{removedControlId:e.id}),i(!1),s(!1)},z=j.totalCards===0?`Delete "${e.label}"?`:`This control is used by ${j.totalCards} ${j.totalCards===1?"card":"cards"}. Deleting it will remove bindings and replace SQL references with NULL on affected cards.`,U=j.cardTitles.slice(0,3).join(", "),Y=j.cardTitles.length>3,O=m.isStructuralSelectorControlType(e.type),K=H=>{if(H){y(b()),s(!0);return}P()},q=l.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Control settings",onClick:H=>H.stopPropagation(),children:l.jsx(bg,{className:"h-3 w-3"})}),M=l.jsx(qle,{control:w,defaultValue:x.defaultValue,defaultPlacement:c,placementOptions:a,previewControlDefinitions:E,previewControlValues:D,availableFieldChoices:k,availableMetricChoices:_,allowCardDefault:!0,structuralParticipantSelector:m.isStructuralSelectorControlType(w.type)?l.jsx(Ole,{type:w.type,participants:h.map(H=>({cardId:H.cardId,title:H.title,choiceCount:w.type==="field_selector"?H.fieldChoices.length:H.metricChoices.length})),selectedCardIds:C,onChange:T}):null,onChangeControl:I,onChangeDefaultValue:H=>{w.source.kind==="manual"&&(S.current=H),y(A=>({...A,defaultValue:H}))},onCommitControlId:F}),G=l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsxs(m.Button,{type:"button",variant:"ghost",size:"xs",className:"text-destructive hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive",onClick:()=>i(!0),children:[l.jsx(m.X,{className:"h-3.5 w-3.5"}),"Delete"]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(m.Button,{type:"button",variant:"outline",size:"xs",onClick:P,children:"Cancel"}),l.jsx(m.Button,{type:"button",size:"xs",onClick:R,children:"Accept"})]})]}),L=w.label||"Control",$=m.getFriendlyTypeOption(w.type).label,V=j.totalCards>0?l.jsxs("div",{className:"space-y-1 text-sm text-muted-foreground",children:[l.jsxs("p",{children:["Affected cards: ",U,Y?` +${j.cardTitles.length-3} more`:""]}),j.sqlCards>0?l.jsxs("p",{children:["SQL references on ",j.sqlCards," ",j.sqlCards===1?"card":"cards"," will be replaced with `NULL`."]}):null,j.configCards>0?l.jsxs("p",{children:["Config bindings on ",j.configCards," ",j.configCards===1?"card":"cards"," will be removed."]}):null]}):null;return l.jsx(Yle,{open:r,onOpenChange:K,trigger:q,title:L,subtitle:$,description:"Update how this control appears and behaves in the dashboard toolbar.",body:M,footer:G,onClose:P,useDialog:O,deleteDialogOpen:o,onDeleteDialogOpenChange:i,deleteDescription:z,deleteDetails:V,onConfirmDelete:B})}const Xtt=24,Qtt=/^\d{4}-\d{2}-\d{2}$/;function oS(e,t=Xtt){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Jtt(e,t,n,r){if(t==null||t==="")return null;if(e.type==="date")try{if(typeof t=="string"&&Qtt.test(t)){const[o,i,a]=t.split("-").map(Number);return xn.format(new Date(o,i-1,a),"MMM d, yyyy")}const s=t instanceof Date?t:new Date(t);return Number.isNaN(s.getTime())?null:xn.formatInTimeZone(s,n,"MMM d, yyyy")}catch{return null}return e.type==="multi_enum"&&Array.isArray(t)?t.length===0?null:t.length===1?oS(String(TT(e,t[0],r)??t[0])):`${t.length} selected`:e.type==="enum"||Pie(e)?oS(String(TT(e,t,r)??t)):e.type==="boolean"?t?"On":"Off":oS(String(t))}function TT(e,t,n){const r=String(t);if(n!=null&&n.has(r))return n.get(r)??null;const s=e.source;if(!s)return null;if(s.kind==="manual"&&Array.isArray(s.options)){const a=s.options.find(c=>c.value===t);return(a==null?void 0:a.label)??null}const i=ent(e,t).find(a=>a.value===t);return i?i.label:null}function ent(e,t){const n=zL(e);return!(t===Cr.CONTROL_CARD_DEFAULT_VALUE||e.defaultValue===Cr.CONTROL_CARD_DEFAULT_VALUE)||n.some(s=>s.value===cR.value)?n:[cR,...n]}function tnt(e){return e.type==="date"?Mm:m.SlidersHorizontal}function nnt(e){return e.type==="date"?360:e.type==="multi_enum"?300:e.type==="number"?240:280}function Gle({control:e,value:t,isEditing:n=!1,dragListeners:r,onChange:s,onUpdateControl:o,disabled:i=!1,controlDefinitionsOverride:a,controlValuesOverride:c,activeFiltersOverride:u,actions:d}){var D,j,I;const f=Zc("interactive"),[h,p]=v.useState(!1),{tokenProps:g}=Ct(),b=((j=(D=g==null?void 0:g.params)==null?void 0:D.calendarContext)==null?void 0:j.tz)||((I=g==null?void 0:g.params)==null?void 0:I.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,x=snt(e,t),y=ob({controlId:e.id,source:x,enabled:x!==void 0,controlDefinitionsOverride:a,controlValuesOverride:c,activeFiltersOverride:u}),S=v.useMemo(()=>{if(y.options.length!==0)return new Map(y.options.map(T=>[T.value,T.label]))},[y.options]),w=Jtt(e,t,b,S),C=w!==null,N=e.showLabel??!0,k=i||e.locked===!0,_=ont(e,t,k),E=tnt(e);return l.jsxs("div",{className:"group/chip flex shrink-0 items-center gap-2",children:[n&&r&&l.jsx("span",{role:"button",tabIndex:-1,"aria-label":"Drag to reorder",className:"inline-flex h-7 cursor-grab items-center justify-center px-0.5 text-muted-foreground/50 transition-colors hover:text-muted-foreground active:cursor-grabbing",...r,children:l.jsx(Yc,{className:"size-3"})}),l.jsxs(m.Popover,{open:h,onOpenChange:p,children:[l.jsxs("div",{className:m.cn("inline-flex h-7 items-stretch overflow-hidden rounded-control border border-border text-[12px] transition-colors",C?f.hasAppearance?"bg-accent/80 hover:bg-accent":"bg-muted/80 hover:bg-muted":f.hasAppearance?"bg-muted/40 hover:bg-accent/50":"bg-muted/40 hover:bg-muted/70"),style:f.chipStyle,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":C?`${e.label}: ${w}`:e.label,className:"inline-flex items-center gap-1.5 px-2 focus:outline-none",children:[l.jsx(E,{className:m.cn("h-3 w-3 shrink-0",C?"text-muted-foreground":"text-muted-foreground/70")}),N&&l.jsx("span",{className:"whitespace-nowrap text-muted-foreground",children:e.label}),C&&l.jsxs(l.Fragment,{children:[N&&l.jsx("span",{className:"text-border","aria-hidden":"true",children:"·"}),l.jsx("span",{className:"max-w-[160px] truncate whitespace-nowrap font-medium text-foreground",children:w})]}),l.jsx(m.ChevronDown,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"})]})}),C&&_&&l.jsxs(l.Fragment,{children:[l.jsx("span",{"aria-hidden":"true",className:"w-px bg-border"}),l.jsx("button",{type:"button",onClick:T=>{T.preventDefault(),T.stopPropagation(),s(void 0)},"aria-label":`Clear ${e.label}`,className:"inline-flex w-6 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]})]}),l.jsx(m.PopoverContent,{align:"start",sideOffset:4,style:{width:nnt(e),...f.contentStyle},className:m.cn(eH(e)||tH(e)?"p-1":"p-3"),onMouseDown:T=>T.stopPropagation(),onClick:T=>T.stopPropagation(),children:eH(e)?l.jsx(nH,{control:e,value:t,disabled:k,multi:!1,popoverOpen:h,controlDefinitionsOverride:a,controlValuesOverride:c,activeFiltersOverride:u,onChange:T=>{s(T),p(!1)}}):tH(e)?l.jsx(nH,{control:e,value:t,disabled:k,multi:!0,popoverOpen:h,controlDefinitionsOverride:a,controlValuesOverride:c,activeFiltersOverride:u,onChange:s}):l.jsx(uR,{control:e,value:t,onChange:s,showLabel:!1,disabled:k,controlDefinitionsOverride:a,controlValuesOverride:c,activeFiltersOverride:u})})]}),n&&l.jsx("div",{className:m.cn("flex shrink-0 items-center transition-opacity",h?"opacity-100":"opacity-0 group-hover/chip:opacity-100 focus-within:opacity-100"),children:d!==void 0?d:l.jsx(Ztt,{control:e})})]})}function eH(e){return e.type==="enum"&&(e.source.kind==="manual"||e.source.kind==="sql_query")}function tH(e){return e.type==="multi_enum"&&(e.source.kind==="manual"||e.source.kind==="sql_query")}function rnt(e){return e.source.kind==="manual"?e.source.options:[]}function nH({control:e,value:t,disabled:n,multi:r,popoverOpen:s,controlDefinitionsOverride:o,controlValuesOverride:i,activeFiltersOverride:a,onChange:c}){const u=e.source.kind==="sql_query",d=u?e.source:void 0,f=ob({controlId:e.id,source:d,enabled:u&&s,controlDefinitionsOverride:o,controlValuesOverride:i,activeFiltersOverride:a}),h=v.useMemo(()=>{if(!u)return rnt(e);const p=f.options.map(y=>({value:y.value,label:y.label})),g=new Set(p.map(y=>y.value)),b=[],x=y=>{typeof y!="string"||y.length===0||g.has(y)||(g.add(y),b.push({value:y,label:y}))};if(Array.isArray(t))for(const y of t)x(y);else x(t);return[...p,...b]},[e,u,f.options,t]);return u&&f.isLoading&&h.length===0?l.jsx("p",{className:"px-2 py-2 text-[12px] text-muted-foreground",children:"Loading options…"}):u&&f.isError&&h.length===0?l.jsx("p",{className:"px-2 py-2 text-[12px] text-destructive",children:"Failed to load options"}):r?l.jsx(ant,{control:e,options:h,value:t,disabled:n,onChange:c}):l.jsx(int,{control:e,options:h,value:t,disabled:n,onChange:c})}function snt(e,t){if(e.source.kind==="sql_query"&&!(e.type!=="enum"&&e.type!=="multi_enum")&&Kle(t)&&!(Array.isArray(t)&&t.length!==1))return e.source}function Kle(e){return e!=null&&e!==""&&(!Array.isArray(e)||e.length>0)}function ont(e,t,n){return!n&&!e.requiredAtExecution&&Kle(t)}function int({control:e,options:t,value:n,disabled:r,onChange:s}){return t.length===0?l.jsx("p",{className:"px-2 py-2 text-[12px] text-muted-foreground",children:"No options"}):l.jsx("div",{role:"radiogroup",className:"flex flex-col gap-0.5",children:t.map(o=>{const i=n===o.value;return l.jsxs("button",{type:"button",role:"radio","aria-checked":i,disabled:r,onClick:()=>{r||s(o.value)},className:m.cn("flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left text-[13px] transition-colors",r?"cursor-not-allowed opacity-50":i?"bg-muted text-foreground hover:bg-foreground/[0.08]":"text-foreground hover:bg-muted"),children:[l.jsx("span",{"aria-hidden":"true",className:m.cn("inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center text-foreground",i?"opacity-100":"opacity-0"),children:l.jsx(m.Check,{className:"h-3 w-3",strokeWidth:3})}),l.jsx("span",{className:"truncate",children:o.label})]},String(o.value))})})}function ant({control:e,options:t,value:n,disabled:r,onChange:s}){const o=Array.isArray(n)?n:n!=null?[n]:[],i=new Set(o.map(c=>String(c)));if(t.length===0)return l.jsx("p",{className:"px-2 py-2 text-[12px] text-muted-foreground",children:"No options"});const a=c=>{if(r)return;const u=String(c),d=i.has(u);if(d&&o.length===1&&e.requiredAtExecution)return;const f=d?o.filter(h=>String(h)!==u):[...o,c];if(f.length===0&&!e.requiredAtExecution){s(void 0);return}s(f)};return l.jsx("div",{role:"listbox","aria-multiselectable":!0,className:"flex flex-col gap-0.5",children:t.map(c=>{const u=i.has(String(c.value)),d=r||u&&o.length===1&&e.requiredAtExecution;return l.jsxs("button",{type:"button",role:"option","aria-selected":u,disabled:d,onClick:()=>a(c.value),className:m.cn("flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left text-[13px] transition-colors",d?"cursor-not-allowed opacity-50":u?"bg-muted text-foreground hover:bg-foreground/[0.08]":"text-foreground hover:bg-muted"),children:[l.jsx("span",{"aria-hidden":"true",className:m.cn("inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] border border-input bg-background text-primary",u&&"border-primary bg-primary text-primary-foreground",d&&"opacity-60"),children:u?l.jsx(m.Check,{className:"h-3 w-3",strokeWidth:3}):null}),l.jsx("span",{className:"truncate",children:c.label})]},String(c.value))})})}function lnt({control:e,controls:t,reservedVariableNames:n=[],activeFiltersOverride:r,onUpdateControl:s,onRemoveControl:o}){const[i,a]=v.useState(!1),[c,u]=v.useState(!1),d=m.getPlacementOptionsForScope("dashboard"),f=m.getDefaultPlacement("dashboard"),h=v.useMemo(()=>unt(t),[t]),p=m.resolveAuthoringControlDefaultValue({control:e,defaultValues:h}),g=v.useCallback(z=>({...z,source:z.source.kind==="manual"?{kind:"manual",options:z.source.options.map(U=>({...U,presentation:U.presentation?{...U.presentation}:void 0}))}:{...z.source}}),[]),b=v.useCallback(()=>({control:g(e),defaultValue:p}),[g,e,p]),[x,y]=v.useState(b),S=v.useRef(p),w=x.control,C=v.useMemo(()=>t.map(z=>z.id===e.id?w:z),[e.id,t,w]),N=v.useMemo(()=>m.buildAuthoringPreviewControlValues({controls:C,defaultValues:h,overrides:[{controlId:e.id,value:void 0},{controlId:w.id,value:x.defaultValue}]}),[e.id,h,x.defaultValue,w.id,C]),k=z=>{y(U=>{const Y=z(U.control);U.control.source.kind==="manual"&&Y.source.kind==="sql_query"&&(S.current=U.defaultValue);const O=U.defaultValue===void 0&&U.control.source.kind==="sql_query"&&Y.source.kind==="manual"?S.current:U.defaultValue,K=m.getNextEditedControlDefaultValue({previousControl:U.control,nextControl:Y,currentDefaultValue:O});return Y.source.kind==="manual"&&(S.current=K),{...U,control:Y,defaultValue:K}})},_=z=>{if(!z.trim())return;const U=J0(z);U!==e.id&&(n.includes(U)||t.some(Y=>Y.id===U&&Y.id!==e.id))||y(Y=>Y.control.id===U?Y:{...Y,control:{...Y.control,id:U}})},E=()=>{S.current=p,y(b()),a(!1)},D=()=>{if(!s){E();return}const z=w.initialValueStrategy==="saved_default"?x.defaultValue:void 0,U=m.syncSqlQueryControlExecutionRequirement({...w,defaultValue:z});s(cnt(U)),a(!1)},j=z=>{if(z){S.current=p,y(b()),a(!0);return}E()},I=()=>{o==null||o(),u(!1),a(!1)},T=w.label||"Control",F=m.getFriendlyTypeOption(w.type).label,P=l.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Control settings",onClick:z=>z.stopPropagation(),children:l.jsx(bg,{className:"h-3 w-3"})}),R=l.jsx(qle,{control:w,defaultValue:x.defaultValue,defaultPlacement:f,placementOptions:d,previewControlDefinitions:C,previewControlValues:N,allowControlIdEdit:!0,showPlacementSelect:!1,showViewerVisibilityToggle:!1,activeFiltersOverride:r,onChangeControl:k,onChangeDefaultValue:z=>{w.source.kind==="manual"&&(S.current=z),y(U=>({...U,defaultValue:z}))},onCommitControlId:_}),B=l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsxs(m.Button,{type:"button",variant:"ghost",size:"xs",className:"text-destructive hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive",onClick:()=>u(!0),children:[l.jsx(m.X,{className:"h-3.5 w-3.5"}),"Delete"]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(m.Button,{type:"button",variant:"outline",size:"xs",onClick:E,children:"Cancel"}),l.jsx(m.Button,{type:"button",size:"xs",onClick:D,children:"Accept"})]})]});return l.jsx(Yle,{open:i,onOpenChange:j,trigger:P,title:T,subtitle:F,description:"Update how this control appears and behaves in the document toolbar.",body:R,footer:B,onClose:E,deleteDialogOpen:c,onDeleteDialogOpenChange:u,deleteDescription:`Delete "${e.label}" from this document sheet?`,onConfirmDelete:I})}function cnt(e){const t={...e};return delete t.placement,delete t.hidden,t}function unt(e){const t={};for(const n of e)n.defaultValue!==void 0&&(t[n.id]=n.defaultValue);return t}function Zle({className:e,inputs:t,filterValuesByInputId:n,filterModesByInputId:r,documentFilterValues:s,documentControlValues:o,onSetFilterValue:i,onSetFilterMode:a,onUpdateFilterInput:c,onUpdateControlInput:u,onRemoveFilterValue:d,onRemoveInput:f,controlValuesByInputId:h,onSetControlValue:p,actions:g,isEditing:b=!1}){const x=v.useMemo(()=>t.filter(bl).map(C=>C.control),[t]),y=m.useDashboardStore(C=>{var N;return((N=C.dashboard.filterLayout)==null?void 0:N.toolbarWrap)??!1}),S=l.jsx("span",{className:"block shrink-0 text-[12px] text-muted-foreground",children:"None yet"}),w=t.map(C=>l.jsx(IT,{children:l.jsx(dnt,{input:C,filterValuesByInputId:n,filterModesByInputId:r,documentFilterValues:s,documentControlValues:o,documentControlDefinitions:x,onSetFilterValue:i,onSetFilterMode:a,onUpdateFilterInput:c,onUpdateControlInput:u,onRemoveFilterValue:d,onRemoveInput:f,reservedVariableNames:t.filter(N=>N.id!==C.id).map(N=>N.variableName),controlValuesByInputId:h,onSetControlValue:p,isEditing:b})},C.id));return l.jsx("div",{className:m.cn("sticky top-0 z-30 shrink-0 gap-3 border-b bg-background/95 px-3 py-1.5 shadow-[0_1px_0_rgba(0,0,0,0.04)] backdrop-blur supports-[backdrop-filter]:bg-background/90",y?"flex min-h-10 items-start overflow-visible":"grid h-10 grid-cols-[minmax(0,1fr)_auto] items-center overflow-hidden",e),children:y?l.jsxs(NR,{wrap:!0,className:"w-full gap-3 pr-0",children:[w.length>0?w:l.jsx(IT,{children:S}),g?l.jsx(IT,{children:g}):null]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"min-w-0 overflow-x-auto overflow-y-hidden",children:l.jsx(NR,{empty:S,children:w})}),g?l.jsx("div",{className:"shrink-0 justify-self-end",children:g}):null]})})}function dnt({input:e,filterValuesByInputId:t,filterModesByInputId:n,documentFilterValues:r,documentControlValues:s,documentControlDefinitions:o,onSetFilterValue:i,onSetFilterMode:a,onUpdateFilterInput:c,onUpdateControlInput:u,onRemoveFilterValue:d,onRemoveInput:f,reservedVariableNames:h,controlValuesByInputId:p,onSetControlValue:g,isEditing:b}){if(e.kind==="control"){const _=Object.prototype.hasOwnProperty.call(p,e.id)?p[e.id]:s[e.control.id];return l.jsx(Gle,{control:e.control,value:_,isEditing:b,onChange:E=>g(e.id,E),onUpdateControl:E=>u==null?void 0:u(e.id,E),controlDefinitionsOverride:o,controlValuesOverride:s,activeFiltersOverride:r,actions:b?l.jsx(lnt,{control:e.control,controls:o,reservedVariableNames:h,activeFiltersOverride:r,onUpdateControl:E=>u==null?void 0:u(e.id,E),onRemoveControl:()=>f==null?void 0:f(e.id)}):null})}const x=e,y=A0(x,t[x.id]),S=y?[y]:[],w=n[x.id]||Ale(x.filter.operation),C=Yj(x.filter.operation)?{...x.filter,operation:CR(w)}:x.filter,N={filters:[],activeFilterValues:r,selectedSheetId:null,dashboardControls:o,controlValues:s};function k(_,E){const D={...x.filter,..._,operation:x.filter.operation};c==null||c(x.id,D,E)}return l.jsx(bL,{filter:C,isEditing:b,settingsVariant:"document",filterQueryContext:N,inputVariableName:x.variableName,reservedInputVariableNames:h,onUpdateFilter:k,onRemoveFilter:()=>f==null?void 0:f(x.id),storageOptions:{storageTarget:"card",cardId:`document-input-${x.id}`,inlineFilterValues:S,setInlineFilterValue:_=>i(x.id,_),removeInlineFilterValue:()=>d(x.id),setInlineFilterMode:(_,E)=>a(x.id,E),filterQueryContext:N}})}function fnt({sections:e,inputs:t,selectedSectionId:n,onSelectSection:r,onDeleteSection:s,onReorderSection:o,onInsertSection:i}){const[a,c]=v.useState(null),[u,d]=v.useState(!1);return l.jsxs("aside",{"data-testid":"document-outline",className:"flex w-64 shrink-0 flex-col border-r bg-background",children:[l.jsxs("div",{className:"flex h-10 items-center justify-between border-b px-3",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Sections"}),l.jsxs("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground",children:["· ",e.length]})]}),i?l.jsxs(m.Popover,{open:u,onOpenChange:d,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add section",className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(dr,{className:"h-3 w-3"}),"Add"]})}),l.jsx(m.PopoverContent,{align:"end",side:"bottom",sideOffset:6,className:"w-48 p-1",children:jle.map(f=>{const h=M0(f);return l.jsxs("button",{type:"button",onClick:()=>{i(f),d(!1)},className:"flex w-full items-center gap-2 rounded-[4px] px-2 py-1.5 text-left text-[12px] text-foreground transition-colors hover:bg-muted",children:[l.jsx(h,{className:"h-3.5 w-3.5 text-muted-foreground"}),lw[f]]},f)})})]}):null]}),l.jsx("div",{className:"flex-1 overflow-y-auto py-1",children:e.length===0?l.jsx("p",{className:"px-3 py-3 text-[12px] text-muted-foreground",children:"No sections yet"}):e.map(f=>{const h=M0(f.type),p=f.id===n,g=Qet(f,t),b=Jet(f);return l.jsxs("div",{"data-testid":`document-outline-section-${f.id}`,"data-selected":p?"true":void 0,draggable:!0,onDragStart:x=>{c(f.id),x.dataTransfer.effectAllowed="move",x.dataTransfer.setData("application/x-semaphor-document-section",f.id)},onDragOver:x=>{!a||a===f.id||(x.preventDefault(),x.dataTransfer.dropEffect="move")},onDrop:x=>{x.preventDefault();const y=x.dataTransfer.getData("application/x-semaphor-document-section")||a;if(y&&y!==f.id){const S=x.currentTarget.getBoundingClientRect(),w=x.clientY<S.top+S.height/2?"before":"after";o(y,f.id,w)}c(null)},onDragEnd:()=>c(null),className:m.cn("group mx-1 flex w-[calc(100%-8px)] items-start rounded transition-colors",p?"bg-muted":"hover:bg-muted/70",a===f.id&&"opacity-40"),children:[l.jsxs("button",{type:"button",onClick:()=>r(f.id),className:"flex min-w-0 flex-1 items-start gap-2 rounded-l px-2 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l.jsx(Yc,{className:"mt-0.5 h-3 w-3 shrink-0 cursor-grab text-muted-foreground/50"}),l.jsx(h,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:m.cn("truncate text-[13px] leading-tight",p?"font-medium text-foreground":"text-foreground/90"),children:g}),b?l.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:b}):null]})]}),l.jsx("div",{className:"flex shrink-0 items-center pr-1 pt-2 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 group-data-[selected=true]:opacity-100",children:l.jsx(m.Button,{type:"button",variant:"ghost",size:"icon",className:"h-5 w-5 text-muted-foreground hover:text-destructive","aria-label":`Delete ${g}`,onClick:x=>{x.stopPropagation(),s(f.id)},children:l.jsx(m.X,{className:"h-3 w-3"})})})]},f.id)})})]})}const MT=[];function hnt({card:e,queryOptions:t,surfaceMode:n,previewRowLimit:r,onPreviewRowLimitChange:s}){const{authToken:o,tokenProps:i}=Ct(),a=m.useDashboardStore(fe=>fe.authToken),u=Bm(e)?n==="print"?"export-full-with-cap":"preview-window":void 0,d=u?u==="preview-window"&&r||Bw(u):void 0,f=v.useMemo(()=>{if(u!=="preview-window")return"";const{paginationConfig:fe,...de}=e;return JSON.stringify({card:de,queryOptions:t,surfaceMode:n})},[e,u,t,n]),h=v.useRef(null),p=v.useMemo(()=>u&&d?{...e,paginationConfig:{page:1,pageSize:d}}:e,[e,d,u]),g=v.useMemo(()=>({...t,...u?{documentTableDataPolicy:u}:{}}),[u,t]),b=$c(p,g),x=!!u&&b.isFetching&&(b.isPlaceholderData||b.dataUpdatedAt===0),y=x?void 0:b.data,S=v.useMemo(()=>Array.isArray(y==null?void 0:y.records)?y.records:MT,[y==null?void 0:y.records]),w=h.current,C=u==="preview-window"&&b.isFetching&&!b.error&&!y&&(w==null?void 0:w.identity)===f,N=C?w.records:S,k=C?w.data:y,_=C?w.pagination:x?void 0:b.pagination,E=C?w.comparisonMetadata:x?void 0:b.comparisonMetadata,D=C?w.queryRequestPayload:x?void 0:b.queryRequestPayload,j=C?w.dataUpdatedAt:b.dataUpdatedAt;v.useEffect(()=>{u!=="preview-window"||x||S.length===0||!y||(h.current={identity:f,data:y,pagination:b.pagination,comparisonMetadata:b.comparisonMetadata,queryRequestPayload:b.queryRequestPayload,records:S,dataUpdatedAt:b.dataUpdatedAt})},[b.comparisonMetadata,b.data,b.dataUpdatedAt,b.pagination,b.queryRequestPayload,y,x,u,f,S]);const I=typeof(_==null?void 0:_.totalCount)=="number"?_.totalCount:void 0,T=!u||typeof(_==null?void 0:_.totalCount)=="number",F=u==="export-full-with-cap"&&I!==void 0&&I>tD,P=v.useMemo(()=>JSON.stringify(b.queryKey),[b.queryKey]),R=u&&d&&I!==void 0&&!F&&u==="export-full-with-cap"?Math.max(1,Math.ceil(I/d)):1,B=u&&d&&T&&R>1?Array.from({length:R-1},(fe,de)=>de+2):[],z=D,U=(o==null?void 0:o.accessToken)||(a==null?void 0:a.accessToken)||"",Y=hg({queries:B.map(fe=>({queryKey:["documentTableRows",P,j,fe,d,i.apiServiceUrl],enabled:!!(u&&d&&z&&U&&T&&!F),queryFn:async()=>{const de={...z||{},pagination:{page:fe,pageSize:d}};return delete de.tableTotalsRequest,m.postRequest(`${i.apiServiceUrl}/v1/query`,U,de)}}))}),O=Y.map(fe=>{var Se;const de=Array.isArray((Se=fe.data)==null?void 0:Se.records)?fe.data.records.length:0;return`${fe.dataUpdatedAt}:${de}`}).join("|"),K=v.useMemo(()=>Y.length===0?MT:Y.flatMap(fe=>{var de;return Array.isArray((de=fe.data)==null?void 0:de.records)?fe.data.records:MT}),[Y.length,O]),q=v.useMemo(()=>u?K.length===0?N:[...N,...K]:N,[K,N,u]),M=Y.map(fe=>{var de,Se;return fe.error?{error:m.getRequestErrorMessage(fe.error,"Query failed",{preserveSyntheticMessage:!0}),sql:m.getRequestErrorSql(fe.error)||""}:(de=fe.data)!=null&&de.error?{error:m.getRequestErrorMessage(fe.data,"Query failed"),sql:m.getRequestErrorSql(fe.data)||(typeof((Se=fe.data)==null?void 0:Se.errorSql)=="string"?fe.data.errorSql:"")}:void 0}).find(Boolean),G=x&&!C?"":b.errorMessage,L=u&&D&&!b.isLoading&&!b.isPending&&!G&&!T?"Document table queries require backend pagination metadata.":"",$=F&&I!==void 0?`This table has ${I.toLocaleString()} rows. Paginated report export currently supports up to ${tD.toLocaleString()} rows. Add filters or reduce the result set before exporting.`:"",V=G||(M==null?void 0:M.error)||L||$,H=b.errorSql||(M==null?void 0:M.sql)||"",A=[u??"single-query",j,O,q.length,I??"unknown",V].join(":"),W=Y.some(fe=>fe.isFetching),X=Y.some(fe=>fe.isLoading||fe.isPending),Z=u==="export-full-with-cap"&&!V&&R>1&&K.length+N.length<Math.min(I??0,tD),J=u==="preview-window"&&I!==void 0&&q.length<I,re=v.useCallback(()=>{u!=="preview-window"||!s||!d||s(Math.min(d+Bw("preview-window"),I??d+Bw("preview-window")))},[s,d,u,I]);return{data:k&&{...k,records:q},records:q,pagination:_,comparisonMetadata:E,queryRequestPayload:D,errorMessage:V,errorSql:H,isLoading:!C&&b.isLoading||X||Z,isPending:!C&&b.isPending||X||Z,isFetching:b.isFetching||W,isPreviewWindowIncomplete:J,loadedRowCount:q.length,totalRowCount:I,rowDataVersion:A,loadMorePreviewRows:J&&s?re:void 0}}function pnt(e){return Sg(e)}function mnt(e){var s,o,i,a;if(!pnt(e)||!mv(e))return[];const t=(o=(s=e.preferences)==null?void 0:s.tablePrefs)==null?void 0:o.columnSettingsMap,n=(a=(i=e.preferences)==null?void 0:i.tablePrefs)==null?void 0:a.columnVisibility;let r=!1;return IP(e).flatMap(c=>UNe(c,n)?c.role!=="metric"&&!r?(r=!0,[H4(c,t)]):c.role==="metric"?[H4(c,t)]:[]:[])}function Xle(e){return qNe(e)}function gnt(e){return AZ(e)}function bnt(e){return!!(e!=null&&e.columns.some(t=>t.behavior!=="label"))}function xnt(e){return YNe(e)}const ynt={mode:"table-print"},vnt={suppressSortControls:!0,renderPlainWrapper:!0,disableDashboardInteractions:!0};function wnt(e){return e.interactionConfig?{...e,interactionConfig:void 0}:e}function Snt(e){return Array.from(e.querySelectorAll("tbody tr, tfoot tr"))}function Cnt({sectionElement:e,tableSurfaceElement:t,firstRowElement:n,lastRowElement:r,measurementScale:s}){const o=Number.isFinite(s)&&s>0?s:1,i=e.getBoundingClientRect(),a=t==null?void 0:t.getBoundingClientRect(),c=n.getBoundingClientRect(),u=r.getBoundingClientRect(),d=r.closest("table"),f=d?d.getBoundingClientRect().bottom:u.bottom,h=Math.max(0,(c.top-i.top)/o),p=Math.max(0,(Math.max(f,u.bottom)-u.bottom)/o),g=t?Nnt({sectionRect:i,tableSurfaceElement:t,tableSurfaceRect:a,measurementScale:o}):void 0;return{chromeHeightPx:Math.ceil(h+p),trailingChromePx:Math.ceil(p),...g!==void 0?{renderedMinHeightPx:g}:{}}}function Nnt({sectionRect:e,tableSurfaceElement:t,tableSurfaceRect:n,measurementScale:r}){const s=window.getComputedStyle(t),o=Number.parseFloat(s.minHeight||"0")||0;if(o<=0||!n)return;const i=Math.max(0,(n.top-e.top)/r);return Math.ceil(i+o)}function rH(e){return e==null?void 0:e.closest('[data-testid="document-page"]')}function Qle(e){return e==null?void 0:e.querySelector('[data-document-region="footer"]')}function knt(e){const t=Number.parseFloat(e.style.height||"")||Number.parseFloat(e.style.minHeight||"");if(t>0)return t;const n=window.getComputedStyle(e),r=Number.parseFloat(n.height||"")||Number.parseFloat(n.minHeight||"");return r>0?r:e.clientHeight}function _nt(e,t){return e?Math.abs(e.rowHeightPx-t.rowHeightPx)>1||Math.abs((e.averageRowHeightPx??e.rowHeightPx)-(t.averageRowHeightPx??t.rowHeightPx))>1||jnt(e.rowHeightsPx,t.rowHeightsPx)||Math.abs(e.chromeHeightPx-t.chromeHeightPx)>1||Math.abs((e.renderedMinHeightPx??0)-(t.renderedMinHeightPx??0))>1||e.rowsPerPage!==t.rowsPerPage:!0}function jnt(e,t){return!e&&!t?!1:!e||!t||e.length!==t.length?!0:e.some((n,r)=>{const s=t[r];return n===void 0||s===void 0?n!==s:Math.abs(n-s)>1})}const sH=40,Gj=18,Ent=120;function Rc({section:e,totalRowCount:t=0,layoutMeasurement:n}){var g;const r=Tnt(e),s=r!=="unsupported",o=!!(e.card.connectionId||(g=e.card.dataSource)!=null&&g.connectionId),i=Mnt(e,r),a=r==="table"?Ant(e):[],c=a.length>0?1:0,u=Math.max(0,t),d=Dnt(e),f=n==null?void 0:n.rowHeightPx,h=n==null?void 0:n.averageRowHeightPx,p=n==null?void 0:n.rowHeightsPx;return{sectionId:e.id,kind:r,isSupported:s,hasConnection:o,hasRunnableQuery:i,isRunnable:s&&o&&i,totalRowCount:u,bodyRowCount:Math.max(0,u-c),trailingRowCount:c,visibleTotalsColumnIds:a,fallbackRowHeightPx:d,measuredRowHeightPx:f,measuredAverageRowHeightPx:h,measuredRowHeightsPx:p,effectiveRowHeightPx:Jle({fallbackRowHeightPx:d,measuredRowHeightPx:f,measuredRowHeightsPx:p,totalRowCount:u}),chromeHeightPx:n==null?void 0:n.chromeHeightPx,renderedMinHeightPx:n==null?void 0:n.renderedMinHeightPx,measuredRowsPerPage:n==null?void 0:n.rowsPerPage,renderContract:vnt}}function Dnt(e){return Math.max(sH,e.table.rowHeightPx??sH)}function Jle({fallbackRowHeightPx:e,measuredRowHeightPx:t,measuredRowHeightsPx:n,totalRowCount:r}){return n&&r!==void 0&&!Int(n,r)?e:t!==void 0?Math.max(Gj,t):e}function Int(e,t){if(e.length<t)return!1;for(let n=0;n<t;n+=1)if(e[n]===void 0)return!1;return!0}function Tnt(e){return e.card.type==="table"||e.card.type==="pivotTable"?e.card.type:"unsupported"}function Mnt(e,t){var n;return t==="unsupported"?!1:t==="pivotTable"?m.hasValidCardConfig(e.card.config):!!((n=e.card.sql)!=null&&n.trim()||m.hasValidCardConfig(e.card.config))}function Ant(e){return e.table.totalsRow?mnt(Xle(e.card)):[]}function Kj({totalRowCount:e,fallbackRowHeightPx:t,layoutMeasurement:n}){const r=Math.max(0,e),s=Math.max(Gj,t),o=n==null?void 0:n.rowHeightsPx;if(!o||o.length===0){if((n==null?void 0:n.rowHeightPx)!==void 0){const d=nk(n.rowHeightPx)??s;return{kind:"uniform",totalRowCount:r,fallbackRowHeightPx:s,measuredRowHeightPx:d,measuredAverageRowHeightPx:n.averageRowHeightPx}}return{kind:"unmeasured",totalRowCount:r,fallbackRowHeightPx:s}}const i=Array.from({length:r},(d,f)=>nk(o[f])),a=i.filter(d=>d!==void 0);if(a.length===0)return{kind:"unmeasured",totalRowCount:r,fallbackRowHeightPx:s};const c=Math.max(...a),u=n.averageRowHeightPx??Math.ceil(a.reduce((d,f)=>d+f,0)/a.length);return $nt(i)?{kind:"complete",totalRowCount:r,fallbackRowHeightPx:s,measuredRowHeightPx:c,measuredAverageRowHeightPx:u,rowHeightsPx:i}:{kind:"sparse",totalRowCount:r,fallbackRowHeightPx:s,measuredRowHeightPx:c,measuredAverageRowHeightPx:u,rowHeightsPx:i}}function Rnt(e,t){const{rowHeightsPx:n,rowRangeStartIndex:r,rowRangeEndIndex:s,totalRowCount:o}=t;if(!n||r===void 0||s===void 0||o===void 0)return RT(e,AT(t));const i=Math.max(0,o),a=Math.min(Math.max(0,r),i),c=Math.min(Math.max(a,s),i),u=c-a,d=AT({...t,rowRangeStartIndex:a,rowRangeEndIndex:c,totalRowCount:i});if(u===i||u!==n.length)return RT(e,d);const f=(e==null?void 0:e.totalRowCount)===i||(e==null?void 0:e.totalRowCount)===void 0,h=Array.from({length:i},(p,g)=>{var b;return f?(b=e==null?void 0:e.rowHeightsPx)==null?void 0:b[g]:void 0});return n.forEach((p,g)=>{h[a+g]=nk(p)}),RT(e,AT({...d,rowHeightsPx:h}))}function ece(e,t){return e.kind!=="unmeasured"&&e.kind!=="uniform"&&e.rowHeightsPx[t]!==void 0?e.rowHeightsPx[t]:e.kind==="uniform"?e.measuredRowHeightPx:e.fallbackRowHeightPx}function N3({rowMeasurementState:e,startIndex:t,endIndex:n}){let r=0;const s=Math.max(0,t),o=Math.min(Math.max(s,n),e.totalRowCount);for(let i=s;i<o;i+=1)r+=ece(e,i);return r}function Fnt({rowMeasurementState:e,startIndex:t,endIndex:n,chromeHeightPx:r,renderedMinHeightPx:s}){const o=N3({rowMeasurementState:e,startIndex:t,endIndex:n});return Math.max(r+o,nce(s)??0)}function Pnt({rowMeasurementState:e,startIndex:t,endIndex:n,chromeHeightPx:r}){return r+N3({rowMeasurementState:e,startIndex:t,endIndex:n})}function tce({rowMeasurementState:e,startIndex:t,availableHeightPx:n}){if(!Number.isFinite(n)||n<=0)return 0;let r=0,s=Math.max(0,t);for(;s<e.totalRowCount;){const o=ece(e,s);if(o<=0||r+o>n)break;r+=o,s+=1}return s-Math.max(0,t)}function Ont(e){return e.kind==="complete"||e.kind==="uniform"?e.measuredRowHeightPx:e.fallbackRowHeightPx}function Lnt({tableSlice:e}){return!e||e.pageIndex===0}function AT(e){var o;const t=(o=e.rowHeightsPx)==null?void 0:o.map(i=>nk(i)),n=(t??[]).filter(i=>i!==void 0),r=n.length>0?Math.max(...n):Math.max(Gj,e.rowHeightPx),s=n.length>0?Math.ceil(n.reduce((i,a)=>i+a,0)/n.length):e.averageRowHeightPx;return{...e,rowHeightPx:r,averageRowHeightPx:s,rowHeightsPx:t,renderedMinHeightPx:nce(e.renderedMinHeightPx),canUpdateLayoutChrome:e.canUpdateLayoutChrome}}function RT(e,t){return!e||t.canUpdateLayoutChrome===void 0||t.canUpdateLayoutChrome?t:{...t,chromeHeightPx:e.chromeHeightPx,renderedMinHeightPx:e.renderedMinHeightPx,rowsPerPage:e.rowsPerPage}}function nce(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.ceil(e)}function nk(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.max(Gj,Math.ceil(e))}function $nt(e){return e.every(t=>t!==void 0)}const znt={colorScheme:"light","--semaphor-background":"0 0% 100%","--semaphor-foreground":"240 5.9% 10%","--semaphor-card":"0 0% 100%","--semaphor-card-foreground":"240 5.9% 10%","--semaphor-muted":"0 0% 98%","--semaphor-muted-foreground":"240 3.8% 46.1%","--semaphor-accent":"240 4.8% 95.9%","--semaphor-accent-foreground":"240 5.9% 10%","--semaphor-border":"240 5.9% 90%","--background":"0 0% 100%","--foreground":"240 5.9% 10%","--muted":"0 0% 98%","--muted-foreground":"240 3.8% 46.1%","--border":"240 5.9% 90%"},Bnt=[],Vnt={spacious:"[&_tbody_td]:!py-3 [&_tfoot_td]:!py-3 [&_tbody_td>div]:!leading-6",comfortable:"[&_tbody_td]:!py-2 [&_tfoot_td]:!py-2 [&_tbody_td>div]:!leading-5",standard:"[&_tbody_td]:!py-1.5 [&_tfoot_td]:!py-1.5 [&_tbody_td>div]:!leading-5",compact:"[&_tbody_td]:!py-1 [&_tfoot_td]:!py-1 [&_tbody_td>div]:!leading-5",dense:"[&_tbody_td]:!py-1 [&_tfoot_td]:!py-1 [&_tbody_td]:!text-[11px] [&_tfoot_td]:!text-[11px] [&_tbody_td>div]:!leading-4"};function Hnt(e){const t=["full","outer"].includes(e.gridLines),n=t||e.gridLines==="top",r=t||e.gridLines==="right",s=t||e.gridLines==="bottom",o=t||e.gridLines==="left",i=["full","inner","horizontal"].includes(e.gridLines),a=["full","inner","vertical"].includes(e.gridLines);return m.cn("relative min-h-[var(--document-table-min-surface-height)] overflow-hidden rounded-none bg-white text-zinc-950",n?"border-t border-t-zinc-200":"border-t-0",r?"border-r border-r-zinc-200":"border-r-0",s?"border-b border-b-zinc-200":"border-b-0",o?"border-l border-l-zinc-200":"border-l-0","[&_.data-table-scroll-container]:!rounded-none [&_.data-table-scroll-container]:!border-0 [&_.data-table-scroll-container]:!bg-white","[&_table]:!bg-white","[&_tbody_td>div]:!text-[var(--document-table-cell-color)] [&_tbody_td]:!text-[var(--document-table-cell-color)]","[&_tbody_tr:hover]:!bg-white [&_tbody_tr]:h-[var(--document-table-row-height)] [&_tbody_tr]:!bg-white","[&_tfoot_td]:!bg-[var(--document-table-totals-bg)] [&_tfoot_td]:!text-[var(--document-table-totals-color)] [&_tfoot_td]:!font-[var(--document-table-totals-font-weight)]","[&_thead]:!bg-[var(--document-table-header-bg)] [&_thead_tr]:!bg-[var(--document-table-header-bg)]","[&_th]:!bg-[var(--document-table-header-bg)] [&_th]:!text-[var(--document-table-header-color)]",Vnt[e.density],e.stripedRows&&"[&_tbody_tr:nth-child(even)]:!bg-zinc-50 [&_tbody_tr:nth-child(even):hover]:!bg-zinc-50","[&_table]:!border-0",i?"[&_tbody_tr]:!border-zinc-200 [&_th]:!border-b [&_th]:!border-zinc-200":"[&_tbody_tr]:!border-transparent [&_th]:!border-b-0",e.totalsStyle.borderTop?["[&_tfoot_td]:![border-top-color:var(--document-table-totals-border-color)]","[&_tfoot_td]:!border-[var(--document-table-totals-border-color)]",e.totalsStyle.borderTopStyle==="double"?"[&_tfoot_td]:!border-t-[3px] [&_tfoot_td]:!border-double":"[&_tfoot_td]:!border-t",e.totalsStyle.borderTopStyle==="dashed"&&"[&_tfoot_td]:!border-dashed",e.totalsStyle.borderTopStyle==="dotted"&&"[&_tfoot_td]:!border-dotted",e.totalsStyle.borderTopStyle==="solid"&&"[&_tfoot_td]:!border-solid"]:"[&_tfoot_td]:!border-t-0",a?"[&_td]:!border-r [&_td]:!border-zinc-200 [&_td:last-child]:!border-r-0 [&_th]:!border-r [&_th]:!border-zinc-200 [&_th:last-child]:!border-r-0 [&_tfoot_td]:!border-r [&_tfoot_td]:!border-zinc-200 [&_tfoot_td:last-child]:!border-r-0":"[&_td]:!border-r-0 [&_th]:!border-r-0 [&_tfoot_td]:!border-r-0")}function Unt({section:e,documentFilterValues:t=[],documentControlDefinitions:n=[],documentControlValues:r={},documentDashboardInputValues:s,missingRequiredInputLabels:o=[],isEditing:i=!0,surfaceMode:a="preview",tableSlice:c,initialRowsPerPageLimit:u,previewRowLimit:d,showInlineEditAction:f=!0,onEditTableSection:h,onTableRowCountChange:p,onTableResultColumnsChange:g,onTableLayoutMeasure:b,onTableLayoutInvalidate:x,onUpdateTableSection:y,onPreviewRowLimitChange:S,measurementScale:w=1}){const C=Rc({section:e});return C.isRunnable?o.length>0?l.jsx(lf,{section:e,icon:l.jsx(ba,{className:"h-4 w-4 text-amber-500"}),title:"Required inputs missing",message:`Set ${o.join(", ")} to run this table.`,exportState:"blocked",isEditing:i,showInlineEditAction:f,onEditTableSection:h}):l.jsx(kj,{displayPreferences:ynt,children:l.jsx(Gnt,{section:e,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,documentDashboardInputValues:s,isEditing:i,surfaceMode:a,tableSlice:c,initialRowsPerPageLimit:u,previewRowLimit:d,showInlineEditAction:f,onEditTableSection:h,onTableRowCountChange:p,onTableResultColumnsChange:g,onTableLayoutMeasure:b,onTableLayoutInvalidate:x,onUpdateTableSection:y,onPreviewRowLimitChange:S,measurementScale:w})}):l.jsx(ert,{section:e,isEditing:i,reason:C.isSupported?void 0:"Unsupported table type",showInlineEditAction:f,onEditTableSection:h})}const rce=v.memo(Unt,Wnt);rce.displayName="DocumentTableSectionRenderer";function Wnt(e,t){return e.section===t.section&&e.documentFilterValues===t.documentFilterValues&&e.documentControlDefinitions===t.documentControlDefinitions&&e.documentControlValues===t.documentControlValues&&e.documentDashboardInputValues===t.documentDashboardInputValues&&qnt(e.missingRequiredInputLabels,t.missingRequiredInputLabels)&&e.isEditing===t.isEditing&&e.surfaceMode===t.surfaceMode&&e.initialRowsPerPageLimit===t.initialRowsPerPageLimit&&e.previewRowLimit===t.previewRowLimit&&e.showInlineEditAction===t.showInlineEditAction&&e.measurementScale===t.measurementScale&&Ynt(e.tableSlice,t.tableSlice)&&e.onEditTableSection===t.onEditTableSection&&e.onTableRowCountChange===t.onTableRowCountChange&&e.onTableResultColumnsChange===t.onTableResultColumnsChange&&e.onTableLayoutMeasure===t.onTableLayoutMeasure&&e.onTableLayoutInvalidate===t.onTableLayoutInvalidate&&e.onUpdateTableSection===t.onUpdateTableSection&&e.onPreviewRowLimitChange===t.onPreviewRowLimitChange}function qnt(e,t){if(e===t)return!0;const n=e||[],r=t||[];return n.length===r.length&&n.every((s,o)=>s===r[o])}function Ynt(e,t){return e===t?!0:!e||!t?!1:e.startIndex===t.startIndex&&e.endIndex===t.endIndex&&e.pageIndex===t.pageIndex&&e.pageCount===t.pageCount&&e.totalRows===t.totalRows&&e.rowsPerPage===t.rowsPerPage}function Gnt({section:e,documentFilterValues:t=[],documentControlDefinitions:n=[],documentControlValues:r={},documentDashboardInputValues:s,isEditing:o=!0,surfaceMode:i="preview",tableSlice:a,initialRowsPerPageLimit:c,previewRowLimit:u,showInlineEditAction:d=!0,onEditTableSection:f,onTableRowCountChange:h,onTableResultColumnsChange:p,onTableLayoutMeasure:g,onTableLayoutInvalidate:b,onUpdateTableSection:x,onPreviewRowLimitChange:y,measurementScale:S=1}){var ke,se,be,Ce,ge,ee,te,ce,le;const w=v.useMemo(()=>e.card.type==="table"&&e.table.totalsRow?Xle(e.card):e.card,[e.card,e.table.totalsRow]),C=v.useMemo(()=>wnt(w),[w]),N=v.useMemo(()=>v3(e),[e]),k=v.useMemo(()=>e.card.type==="table"&&e.table.totalsRow?gnt(w):void 0,[w,e.card.type,e.table.totalsRow]),_=bnt(k),E=v.useMemo(()=>{const Ee=t.length>0,ye=n.length>0||Object.keys(r).length>0;return{runtimeContext:"documentSection",documentSectionId:e.id,...k?{tableTotalsRequest:k}:{},...Ee?{documentFilterValues:t}:{},...ye?{documentControlDefinitions:n,documentControlValues:r}:{},...s?{documentDashboardInputValues:s}:{}}},[t,n,r,s,e.id,k]),D=hnt({card:w,queryOptions:E,surfaceMode:i,previewRowLimit:u,onPreviewRowLimitChange:y}),j=D.records||Bnt,I=v.useMemo(()=>stt(j),[j]),T=v.useMemo(()=>Ele(e),[e]),F=w.type==="table"?Rc({section:e}).trailingRowCount:0,P=v.useMemo(()=>Rc({section:e,totalRowCount:w.type==="table"?j.length+F:0}),[w.type,F,j.length,e]),R=w.type==="table"&&j.length>0&&P.trailingRowCount>0,B=D.errorMessage?0:P.totalRowCount,z=R&&(a?a.endIndex>j.length:!c||P.totalRowCount<=c),U=R&&z,Y=v.useMemo(()=>w.type==="table"&&!U?xnt(C):C,[w.type,C,U]),O=v.useCallback(Ee=>{x==null||x(e.id,ye=>{var Ue;const ne=(Ue=ye.card.preferences)==null?void 0:Ue.tablePrefs,je=typeof Ee=="function"?Ee((ne==null?void 0:ne.columnSizing)||{}):Ee;return{...ye,card:{...ye.card,preferences:{...ye.card.preferences,tablePrefs:{...ne,columnSizing:je}}}}})},[x,e.id]);let K=j;w.type==="table"&&a?K=j.slice(Math.min(a.startIndex,j.length),Math.min(a.endIndex,j.length)):w.type==="table"&&c&&(K=j.slice(0,c));const q=(D.isLoading||D.isPending||D.isFetching)&&j.length===0,M=i!=="print"&&D.isFetching&&j.length>0,G=i==="print"&&D.isLoading&&j.length>0;v.useEffect(()=>{w.type==="table"&&(h==null||h(e.id,B))},[w.type,h,e.id,B]),v.useEffect(()=>{w.type==="table"&&(p==null||p(e.id,I,T))},[w.type,p,T,I,e.id]);const L=v.useMemo(()=>{var Ee,ye,ne,je;return w.type!=="pivotTable"||D.errorMessage||!j.length?null:{records:j,columnSubtotalMeta:(Ee=D.data)==null?void 0:Ee.columnSubtotalMeta,subtotalColumns:((ye=D.data)==null?void 0:ye.subtotalColumns)||[],pivotSchema:((ne=D.data)==null?void 0:ne.pivotSchema)||[],groupByColumns:(je=D.data)==null?void 0:je.groupByColumns}},[w.type,j,(ke=D.data)==null?void 0:ke.columnSubtotalMeta,(se=D.data)==null?void 0:se.subtotalColumns,(be=D.data)==null?void 0:be.pivotSchema,(Ce=D.data)==null?void 0:Ce.groupByColumns,D.errorMessage]),$=Gh(w,L),V=v.useMemo(()=>{if(w.type!=="pivotTable"||!$)return 0;const Ee=ZP($.data);return Rc({section:e,totalRowCount:Ee.tableData.length+Ee.grandTotalRows.length}).totalRowCount},[w.type,$,e]);v.useEffect(()=>{w.type==="pivotTable"&&(h==null||h(e.id,V))},[w.type,h,$,V,e.id]);const H=rtt(e),A=ttt(N),W=v.useRef(null),X=v.useRef(null),Z=v.useRef({rowDataVersion:D.rowDataVersion,errorMessage:D.errorMessage}),[J,re]=v.useState(!1),[fe,de]=v.useState(0),Se=Xnt({tableSlice:a,initialRowsPerPageLimit:c,totalRowCount:w.type==="pivotTable"?V:B}),ue=a?`${a.pageIndex}:${a.startIndex}:${a.endIndex}:${a.totalRows}`:"unsliced";if(v.useEffect(()=>{const Ee=Z.current;Z.current={rowDataVersion:D.rowDataVersion,errorMessage:D.errorMessage},!(Ee.rowDataVersion===D.rowDataVersion&&Ee.errorMessage===D.errorMessage)&&(b==null||b(e.id),de(ye=>ye+1))},[b,D.errorMessage,D.rowDataVersion,e.id]),Knt({sectionId:e.id,sectionRef:W,tableSurfaceRef:X,enabled:!J,measureKey:`${j.length}:${K.length}:${q?"loading":"ready"}:${A}:${ue}:${fe}`,measurementScale:S,fallbackRowHeightPx:H,fallbackRowCount:Math.max(0,Se.endIndex-Se.startIndex),rowRangeStartIndex:Se.startIndex,rowRangeEndIndex:Se.endIndex,totalRowCount:Se.totalRowCount,canUpdateLayoutChrome:Lnt({tableSlice:a}),onTableLayoutMeasure:g}),D.errorMessage)return l.jsx(lf,{section:e,icon:l.jsx(ba,{className:"h-4 w-4 text-amber-500"}),title:"Table query failed",message:D.errorMessage,exportState:"error",isEditing:o,showInlineEditAction:d,onEditTableSection:f});if(q)return l.jsx(trt,{section:e,isEditing:o,showInlineEditAction:d,onEditTableSection:f});if(G)return l.jsx(lf,{section:e,icon:l.jsx(m.LoaderCircle,{className:"h-4 w-4 animate-spin text-zinc-400"}),title:"Preparing report table",message:"Rows are being acquired for the final document export.",exportState:"loading",isEditing:o,showInlineEditAction:d,onEditTableSection:f});if(U&&_&&!((ge=D.data)!=null&&ge.tableTotalsByColumnId)&&D.isFetching)return l.jsx(lf,{section:e,icon:l.jsx(m.LoaderCircle,{className:"h-4 w-4 animate-spin text-zinc-400"}),title:"Computing table totals",message:"Grand totals are being computed for this document table.",exportState:"loading",isEditing:o,showInlineEditAction:d,onEditTableSection:f});if(U&&_&&!((ee=D.data)!=null&&ee.tableTotalsByColumnId))return l.jsx(lf,{section:e,icon:l.jsx(ba,{className:"h-4 w-4 text-amber-500"}),title:"Table totals unavailable",message:"Grand totals could not be computed for this document table.",exportState:"error",isEditing:o,showInlineEditAction:d,onEditTableSection:f});if(j.length===0)return l.jsx(lf,{section:e,icon:l.jsx(m.Table2,{className:"h-4 w-4 text-zinc-300"}),title:e.title||w.title||"Table",message:"No records to display",exportState:"empty",isEditing:o,showInlineEditAction:d,onEditTableSection:f});let ve;if(w.type==="pivotTable"){if(!$)return l.jsx(lf,{section:e,icon:l.jsx(ba,{className:"h-4 w-4 text-amber-500"}),title:"Pivot table configuration unavailable",message:"Edit the table to confirm its rows, columns, and metrics.",exportState:"error",isEditing:o,showInlineEditAction:d,onEditTableSection:f});ve=l.jsx(rb,{card:C,data:Jnt($.data,a,c),options:$.options,suppressSortControls:P.renderContract.suppressSortControls,renderPlainWrapper:P.renderContract.renderPlainWrapper})}else ve=l.jsx(ud,{card:Y,data:K,formattingFullRows:j,totalsData:U?j:void 0,totalsByColumnId:U?(te=D.data)==null?void 0:te.tableTotalsByColumnId:void 0,comparisonMetadata:D.comparisonMetadata,paginationMetadata:D.pagination,isLoading:q,columnSizing:(le=(ce=Y.preferences)==null?void 0:ce.tablePrefs)==null?void 0:le.columnSizing,onColumnSizingChange:o&&i!=="print"?O:void 0,onColumnResizeStateChange:re,showColumnResizeHandles:o&&i!=="print",suppressSortControls:P.renderContract.suppressSortControls,suppressCellHoverCards:P.renderContract.disableDashboardInteractions});const xe=i!=="print"&&D.isPreviewWindowIncomplete&&(!a||a.endIndex>=j.length);return l.jsxs("div",{className:"relative",children:[l.jsxs("div",{ref:W,className:"pt-3",children:[l.jsx(nrt,{section:e}),l.jsxs("div",{ref:X,"data-document-table-section":"true",className:Hnt(N),style:{...znt,"--document-table-row-height":`${H}px`,"--document-table-min-surface-height":`${a?0:Ent}px`,"--document-table-header-bg":N.headerBackgroundColor,"--document-table-header-color":N.headerTextColor,"--document-table-totals-bg":N.totalsStyle.backgroundColor,"--document-table-totals-color":N.totalsStyle.textColor,"--document-table-totals-border-color":N.totalsStyle.borderTopColor,"--document-table-totals-font-weight":String(ntt(N.totalsStyle.fontWeight)),"--document-table-cell-color":"#18181b"},children:[M?l.jsx(rrt,{}):null,ve]})]}),xe?l.jsx(srt,{loadedRowCount:D.loadedRowCount,totalRowCount:D.totalRowCount,isFetching:D.isFetching,onLoadMore:D.loadMorePreviewRows}):null]})}function Knt({sectionId:e,sectionRef:t,tableSurfaceRef:n,enabled:r,measureKey:s,measurementScale:o,fallbackRowHeightPx:i,fallbackRowCount:a,rowRangeStartIndex:c,rowRangeEndIndex:u,totalRowCount:d,canUpdateLayoutChrome:f,onTableLayoutMeasure:h}){const p=v.useRef(null);v.useEffect(()=>{if(!r||!h)return;p.current=null;let g=null;const b=()=>{const j=t.current,I=n.current;if(!j||!I)return;const T=Number.isFinite(o)&&o>0?o:1,F=H=>H/T,P=Snt(I),R=P.length>0?P.map(H=>{const A=F(H.getBoundingClientRect().height);return A>0?A:i}).filter(H=>H>0):Array.from({length:a},()=>i);if(R.length===0)return;const B=R.map(H=>Math.ceil(H)),z=Math.ceil(Math.max(...R)),U=R.reduce((H,A)=>H+A,0),Y=Math.ceil(U/R.length),O=Math.ceil(F(j.getBoundingClientRect().height)),K=rH(j),q=P[0],M=P[P.length-1],G=q&&M?Cnt({sectionElement:j,tableSurfaceElement:I,firstRowElement:q,lastRowElement:M,measurementScale:T}):void 0;let L;if(K&&q&&M){const H=K.getBoundingClientRect(),A=Qnt(K,T,H),W=q.getBoundingClientRect(),X=F(W.top-H.top),Z=(G==null?void 0:G.trailingChromePx)??0,J=A-X-Z;L=Math.max(1,Znt(R,J))}const $=(G==null?void 0:G.chromeHeightPx)??Math.max(0,Math.ceil(O-U)),V={rowHeightPx:z,averageRowHeightPx:Y,rowHeightsPx:B,rowRangeStartIndex:c,rowRangeEndIndex:u,totalRowCount:d,chromeHeightPx:$,renderedMinHeightPx:G==null?void 0:G.renderedMinHeightPx,canUpdateLayoutChrome:f,rowsPerPage:L};_nt(p.current,V)&&(p.current=V,h(e,V))},x=()=>{g!==null&&window.cancelAnimationFrame(g),g=window.requestAnimationFrame(()=>{g=null,b()})};if(x(),typeof ResizeObserver>"u")return()=>{g!==null&&window.cancelAnimationFrame(g)};const y=new ResizeObserver(x),S=typeof MutationObserver>"u"?null:new MutationObserver(x),w=new Set,C=j=>{!j||w.has(j)||(y.observe(j),w.add(j))},N=j=>{!j||!S||S.observe(j,{attributes:!0,characterData:!0,childList:!0,subtree:!0})},k=t.current,_=n.current,E=rH(k),D=Qle(E);return C(k),C(_),C(E),C(D),N(E),()=>{g!==null&&window.cancelAnimationFrame(g),y.disconnect(),S==null||S.disconnect()}},[r,o,s,h,e,t,n,i,a,c,u,d,f])}function Znt(e,t){if(!Number.isFinite(t)||t<=0)return 0;let n=0,r=0;for(const s of e){if(n+s>t)break;n+=s,r+=1}return r}function Xnt({tableSlice:e,initialRowsPerPageLimit:t,totalRowCount:n}){const r=Math.max(0,n),s=Math.min((e==null?void 0:e.startIndex)??0,r),o=Math.min((e==null?void 0:e.endIndex)??t??r,r);return{startIndex:s,endIndex:Math.max(s,o),totalRowCount:r}}function Qnt(e,t,n){const r=Qle(e);if(r)return(r.getBoundingClientRect().top-n.top)/t;const s=window.getComputedStyle(e),o=Number.parseFloat(s.paddingBottom||"0")||0;return knt(e)-o}function Jnt(e,t,n){var f,h,p,g,b,x;const r=(t==null?void 0:t.startIndex)??0,s=(t==null?void 0:t.endIndex)??(n||void 0);if(s===void 0)return e;const o=((f=e.rowData)==null?void 0:f.length)??((h=e.rowHeaders)==null?void 0:h.length)??0,i=((p=e.grandTotalRows)==null?void 0:p.length)??0,a=Math.min(r,o),c=Math.min(s,o),u=Math.max(0,r-o),d=Math.max(0,Math.min(s-o,i));return{...e,rowData:(g=e.rowData)==null?void 0:g.slice(a,c),rowHeaders:((b=e.rowHeaders)==null?void 0:b.slice(a,c))??[],grandTotalRows:((x=e.grandTotalRows)==null?void 0:x.slice(u,d))??[]}}function ert({section:e,isEditing:t,reason:n,showInlineEditAction:r,onEditTableSection:s}){return l.jsx("div",{className:"pt-3",children:l.jsxs("div",{className:"rounded border border-dashed border-zinc-200 px-4 py-8 text-center","data-document-render-error":"true",children:[l.jsx(m.Table2,{className:"mx-auto mb-2 h-5 w-5 text-zinc-300"}),l.jsx("p",{className:"text-[12px] font-medium text-zinc-600",children:e.title||e.card.title||"Table"}),n?l.jsx("p",{className:"mt-1 text-[11px] text-zinc-400",children:n}):null,r?l.jsx(k3,{section:e,isEditing:t,className:"mt-3",onEditTableSection:s}):null]})})}function trt({section:e,isEditing:t,showInlineEditAction:n,onEditTableSection:r}){return l.jsx("div",{className:"pt-3","data-document-render-loading":"true",children:l.jsxs("div",{className:"relative h-[220px] overflow-hidden rounded",children:[l.jsx($L,{columns:5,rows:8}),n?l.jsx("div",{className:"absolute right-2 top-2 z-20",children:l.jsx(k3,{section:e,isEditing:t,onEditTableSection:r})}):null]})})}function lf({section:e,icon:t,title:n,message:r,exportState:s,isEditing:o,showInlineEditAction:i,onEditTableSection:a}){const c=s==="blocked"||s==="error",u=s==="loading";return l.jsx("div",{className:"pt-3",children:l.jsx("div",{className:"rounded border border-zinc-200 bg-zinc-50 px-4 py-5","data-document-render-error":c?"true":void 0,"data-document-render-loading":u?"true":void 0,children:l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsx("div",{className:"mt-0.5 shrink-0",children:t}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"text-[12px] font-medium text-zinc-700",children:n}),l.jsx("p",{className:"mt-1 break-words text-[11px] text-zinc-500",children:r})]}),i?l.jsx(k3,{section:e,isEditing:o,onEditTableSection:a}):null]})})})}function nrt({section:e}){const t=e.title||e.card.title;return t?l.jsx("div",{className:"mb-2 min-w-0",children:t?l.jsx("p",{className:"whitespace-normal break-words text-[12px] font-semibold leading-4 text-zinc-800",children:t}):null}):null}function rrt(){return l.jsxs("div",{role:"status","aria-live":"polite",className:"pointer-events-none absolute right-2 top-2 z-10 inline-flex items-center gap-1.5 rounded-full border border-zinc-200 bg-white/95 px-2 py-1 text-[10px] font-medium text-zinc-500 shadow-sm",children:[l.jsx(m.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Updating..."]})}function srt({loadedRowCount:e,totalRowCount:t,isFetching:n,onLoadMore:r}){const s=t===void 0?"unknown":t.toLocaleString();return l.jsxs("div",{className:"absolute left-0 top-full z-20 mt-2 flex max-w-full items-center gap-2 rounded border border-zinc-200 bg-white px-2 py-1 text-[11px] text-zinc-500 shadow-sm print:hidden",children:[l.jsxs("span",{className:"whitespace-nowrap",children:["Previewing ",e.toLocaleString()," of ",s," rows"]}),r?l.jsx(m.Button,{type:"button",variant:"outline",size:"sm",className:"h-6 rounded px-2 text-[11px]",disabled:n,onClick:r,children:n?"Loading...":"Load more pages"}):null]})}function k3({section:e,isEditing:t,className:n,onEditTableSection:r}){return t?l.jsxs(m.Button,{type:"button",variant:"outline",size:"sm",className:n?`h-8 gap-2 ${n}`:"h-8 gap-2",onClick:s=>{s.stopPropagation(),r==null||r(e)},children:[l.jsx(m.Table2,{className:"h-3.5 w-3.5"}),"Edit table"]}):null}const ort={a4:{width:595,height:842},letter:{width:612,height:792}},irt=96/72;function sce(e){return art(e)}function art(e){return lrt(e,{pointToPixelScale:irt})}function lrt(e,{pointToPixelScale:t}){const n=ort[e.size],r=e.orientation==="landscape"?n.height:n.width,s=e.orientation==="landscape"?n.width:n.height,o=e.margins,i=o.unit==="mm"?72/25.4:72,a=u=>Math.round(u*i*t),c={top:a(o.top),right:a(o.right),bottom:a(o.bottom),left:a(o.left)};return{width:Math.round(r*t),height:Math.round(s*t),padding:`${c.top}px ${c.right}px ${c.bottom}px ${c.left}px`,paddingPx:c}}const crt=16,dg=78,urt=0,drt=0,frt=72,hrt=40;function prt(e,t={}){var p;const n=t.tablePaginationBySectionId??{},r=t.pageMetricsMode??"preview",s=t.document?ice(t.document):Number.POSITIVE_INFINITY,o=[];let i=[],a=0,c=0,u;const d=(g,b=i,x=a,y=`document-page-${o.length+1}-${x}`,S=u)=>{o.push({id:y,startInsertIndex:x,sections:b,breakAfterSection:g,layoutError:S})},f=g=>{const b=o[o.length-1];return!b||b.breakAfterSection||b.sections.length===0?!1:(b.breakAfterSection=g,!0)};e.forEach((g,b)=>{if(g.type==="page_break"){i.length>0?d(g):f(g)||d(g),i=[],c=0,a=b+1;return}if(g.type==="table"){const S=n[g.id],w=(S==null?void 0:S.rowCount)??0,C=(S==null?void 0:S.rowsPerPage)??0,N=!!t.document,k=N&&C>0?brt(g,S,s-c):C;if(C>0&&(w>C||N&&i.length>0&&k>0&&w>k)&&S){!N&&i.length>0&&(d(),i=[],c=0,u=void 0,a=b),N&&i.length>0&&k<=0&&(d(),i=[],c=0,u=void 0,a=b);const E=_3(g,S),D=mrt({rowCount:w,rowsPerPage:C,footerRowCount:(S==null?void 0:S.footerRowCount)??0,firstRowsPerPage:N&&i.length>0?k:C,rowMeasurementState:E,capFirstRowsPerPage:N&&i.length>0&&S.measuredRowsPerPage!==void 0,firstRowsAvailableHeightPx:N&&i.length>0?sC(S,s-c):sC(S,s),fullRowsAvailableHeightPx:sC(S,s)});D.forEach((j,I)=>{const T=I===D.length-1,F={section:g,sectionIndex:b,tableSlice:{startIndex:j.startIndex,endIndex:j.endIndex,pageIndex:I,pageCount:D.length,totalRows:w,rowsPerPage:C}},P=xrt(g,S,j.startIndex,j.endIndex);if(N&&I===0&&i.length>0){i.push(F),c+=P,T||(d(),i=[],c=0,u=void 0,a=b+1);return}if(T&&N){i=[F],c=P,u=void 0,a=b;return}d(void 0,[F],b,`document-page-table-${g.id}-${I+1}`,void 0)});return}}const x=t.document?vrt({section:g,document:t.document,tablePagination:n[g.id],pageMetricsMode:r,textRenderContext:t.textRenderContext}):0;if(Number.isFinite(s)&&x>s){i.length>0&&(d(),i=[],c=0,u=void 0,a=b),d(void 0,[{section:g,sectionIndex:b}],b,`document-page-overflow-${g.id}`,`Section "${g.id}" exceeds the available page body height.`),i=[],c=0,u=void 0,a=b+1;return}i.length>0&&c+x>s&&(d(),i=[],c=0,u=void 0,a=b),i.push({section:g,sectionIndex:b}),c+=x}),(o.length===0||i.length>0||((p=e[e.length-1])==null?void 0:p.type)==="page_break")&&d();const h=o.length;return o.map((g,b)=>({...g,pageNumber:b+1,pageCount:h}))}function mrt({rowCount:e,rowsPerPage:t,footerRowCount:n=0,firstRowsPerPage:r,rowMeasurementState:s,capFirstRowsPerPage:o=!1,firstRowsAvailableHeightPx:i,fullRowsAvailableHeightPx:a}){const c=[];let u=0,d=Math.max(1,r);const f=Math.max(0,n),h=Math.max(0,e-f);for(;u<e;){const p=c.length===0?i:a,b=(s.kind==="sparse"||s.kind==="complete")&&Number.isFinite(p)?tce({rowMeasurementState:s,startIndex:u,availableHeightPx:p??0}):void 0,x=b!==void 0?Math.max(1,c.length===0&&o?Math.min(b,d):b):Math.max(1,d);let y;if(f===0||u>=h)y=Math.min(u+x,e);else{const S=h-u;if(S+f<=x&&N3({rowMeasurementState:s,startIndex:u,endIndex:e})<=(p??Number.POSITIVE_INFINITY))y=e;else{let w=Math.min(x,S);w===S&&f>0&&S>1&&(w-=1),y=u+Math.max(1,w)}}c.push({startIndex:u,endIndex:y}),u=y,d=t}return c}function grt({document:e,tableRowCountsBySectionId:t,tableLayoutMeasurementsBySectionId:n,shouldPaginateTables:r,pageMetricsMode:s="preview"}){if(!r)return{};const o={};for(const i of e.sections){if(!wy(i))continue;const a=t[i.id]??0;if(a<=0)continue;const c=n==null?void 0:n[i.id],u=Rc({section:i,totalRowCount:a,layoutMeasurement:c}),d=Kj({totalRowCount:u.totalRowCount,fallbackRowHeightPx:u.fallbackRowHeightPx,layoutMeasurement:c});o[i.id]={rowCount:u.totalRowCount,rowsPerPage:oce(e,u,s),footerRowCount:u.trailingRowCount,fallbackRowHeightPx:u.fallbackRowHeightPx,rowMeasurementState:d,rowHeightPx:u.measuredRowHeightPx,averageRowHeightPx:u.measuredAverageRowHeightPx,rowHeightsPx:u.measuredRowHeightsPx,chromeHeightPx:u.chromeHeightPx,renderedMinHeightPx:u.renderedMinHeightPx,measuredRowsPerPage:u.measuredRowsPerPage}}return o}function wy(e){return e.type!=="table"?!1:Rc({section:e}).isRunnable}function oce(e,t,n="preview"){const s=ice(e)-(t.chromeHeightPx??dg),o=Math.floor(s/t.effectiveRowHeightPx);return Math.max(1,o)}function brt(e,t,n){if(!Number.isFinite(n))return(t==null?void 0:t.rowsPerPage)??0;const r=sC(t,n),s=t&&_3(e,t),i=(s&&s.kind!=="unmeasured"?tce({rowMeasurementState:s,startIndex:0,availableHeightPx:r}):void 0)??Math.max(0,Math.floor(r/rk(e,t)));return(t==null?void 0:t.measuredRowsPerPage)!==void 0?Math.max(0,Math.min(i,t.measuredRowsPerPage)):i}function xrt(e,t,n,r){return Pnt({rowMeasurementState:t?_3(e,t):Kj({totalRowCount:r,fallbackRowHeightPx:rk(e,t)}),startIndex:n,endIndex:r,chromeHeightPx:(t==null?void 0:t.chromeHeightPx)??dg})}function sC(e,t){return t-((e==null?void 0:e.chromeHeightPx)??dg)}function rk(e,t){if(t!=null&&t.rowMeasurementState)return Ont(t.rowMeasurementState);const n=(t==null?void 0:t.fallbackRowHeightPx)??Rc({section:e}).fallbackRowHeightPx;return Jle({fallbackRowHeightPx:n,measuredRowHeightPx:t==null?void 0:t.rowHeightPx,measuredRowHeightsPx:t==null?void 0:t.rowHeightsPx,totalRowCount:t==null?void 0:t.rowCount})}function _3(e,t){return t.rowMeasurementState?t.rowMeasurementState:Kj({totalRowCount:t.rowCount,fallbackRowHeightPx:rk(e,t),layoutMeasurement:t.rowHeightPx!==void 0||t.rowHeightsPx?{rowHeightPx:t.rowHeightPx??rk(e,t),averageRowHeightPx:t.averageRowHeightPx,rowHeightsPx:t.rowHeightsPx,chromeHeightPx:t.chromeHeightPx??dg,renderedMinHeightPx:t.renderedMinHeightPx,rowsPerPage:t.rowsPerPage}:void 0})}function ice(e,t){const n=ace(e),r=oH(e.header,frt),s=oH(e.footer,hrt);return n.height-n.paddingPx.top-n.paddingPx.bottom-r-s-crt}function yrt(e,t){const n=ace(e);return n.width-n.paddingPx.left-n.paddingPx.right}function vrt({section:e,document:t,tablePagination:n,pageMetricsMode:r,textRenderContext:s}){if(e.type==="spacer")return Math.max(8,e.heightPx);if(e.type==="text")return wrt(e,t,r,s);if(e.type==="table"){const o=Rc({section:e,totalRowCount:(n==null?void 0:n.rowCount)??3,layoutMeasurement:n!=null&&n.rowHeightPx?{rowHeightPx:n.rowHeightPx,averageRowHeightPx:n.averageRowHeightPx,rowHeightsPx:n.rowHeightsPx,chromeHeightPx:n.chromeHeightPx??dg,renderedMinHeightPx:n.renderedMinHeightPx,rowsPerPage:n.rowsPerPage}:void 0}),i=(n==null?void 0:n.rowCount)??3;return Fnt({rowMeasurementState:(n==null?void 0:n.rowMeasurementState)??Kj({totalRowCount:i,fallbackRowHeightPx:o.effectiveRowHeightPx}),startIndex:0,endIndex:i,chromeHeightPx:(n==null?void 0:n.chromeHeightPx)??dg,renderedMinHeightPx:n==null?void 0:n.renderedMinHeightPx})}return 0}function wrt(e,t,n,r){var c,u;const s=((c=e.style)==null?void 0:c.fontSize)??13,o=Math.ceil(s*((u=e.style)!=null&&u.fontSize?1.45:1.55)),i=Math.max(120,yrt(t)-urt),a=Srt({content:e.content,bodyWidthPx:i,fontSize:s,textRenderContext:r});return drt+a*o}function Srt({content:e,bodyWidthPx:t,fontSize:n,textRenderContext:r}){const s=n*.54,o=r?Sle(e,r):Crt(e),i=Nrt(o,s);return i.length===0?1:i.reduce((a,c)=>a+Math.max(1,Math.ceil(c/t)),0)}function Crt(e){return e.map(t=>({type:t.type,value:t.type==="text"?t.value:"0".repeat(120),format:t.format}))}function Nrt(e,t){const n=[0];for(const r of e){const s=krt(r);r.value.split(`
@@ -1422,4 +1422,4 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
1422
1422
 
1423
1423
  `)},flush(e){e.enqueue(`data: [DONE]
1424
1424
 
1425
- `)}})}});var Axt=_bt(()=>sfe(ea([Or({type:yn("text-start"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("text-delta"),id:Ut(),delta:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("text-end"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("error"),errorText:Ut()}),Or({type:yn("tool-input-start"),toolCallId:Ut(),toolName:Ut(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),Or({type:yn("tool-input-delta"),toolCallId:Ut(),inputTextDelta:Ut()}),Or({type:yn("tool-input-available"),toolCallId:Ut(),toolName:Ut(),input:Qa(),providerExecuted:Uo().optional(),providerMetadata:Jr.optional(),dynamic:Uo().optional()}),Or({type:yn("tool-input-error"),toolCallId:Ut(),toolName:Ut(),input:Qa(),providerExecuted:Uo().optional(),providerMetadata:Jr.optional(),dynamic:Uo().optional(),errorText:Ut()}),Or({type:yn("tool-output-available"),toolCallId:Ut(),output:Qa(),providerExecuted:Uo().optional(),dynamic:Uo().optional(),preliminary:Uo().optional()}),Or({type:yn("tool-output-error"),toolCallId:Ut(),errorText:Ut(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),Or({type:yn("reasoning-start"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("reasoning-delta"),id:Ut(),delta:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("reasoning-end"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("source-url"),sourceId:Ut(),url:Ut(),title:Ut().optional(),providerMetadata:Jr.optional()}),Or({type:yn("source-document"),sourceId:Ut(),mediaType:Ut(),title:Ut(),filename:Ut().optional(),providerMetadata:Jr.optional()}),Or({type:yn("file"),url:Ut(),mediaType:Ut(),providerMetadata:Jr.optional()}),Or({type:Jde(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Ut().optional(),data:Qa(),transient:Uo().optional()}),Or({type:yn("start-step")}),Or({type:yn("finish-step")}),Or({type:yn("start"),messageId:Ut().optional(),messageMetadata:Qa().optional()}),Or({type:yn("finish"),finishReason:Zde(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Qa().optional()}),Or({type:yn("abort")}),Or({type:yn("message-metadata"),messageMetadata:Qa()})])));function Rxt(e){return e.type.startsWith("data-")}function ffe(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=ffe(o,s):n[r]=s}return n}function Fxt(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function hfe(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await bk({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await bk({text:Fxt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function aC(e){return e.type.startsWith("tool-")}function Pxt(e){return e.type==="dynamic-tool"}function qR(e){return aC(e)||Pxt(e)}function XU(e){return e.type.split("-").slice(1).join("-")}function Oxt({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Lxt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,p,g;function b(C){const k=u.message.parts.filter(aC).find(_=>_.toolCallId===C);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function x(C){const k=u.message.parts.filter(_=>_.type==="dynamic-tool").find(_=>_.toolCallId===C);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function y(C){var N;const k=u.message.parts.find(D=>aC(D)&&D.toolCallId===C.toolCallId),_=C,E=k;k!=null?(k.state=C.state,E.input=_.input,E.output=_.output,E.errorText=_.errorText,E.rawInput=_.rawInput,E.preliminary=_.preliminary,E.providerExecuted=(N=_.providerExecuted)!=null?N:k.providerExecuted,_.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=_.providerMetadata)):u.message.parts.push({type:`tool-${C.toolName}`,toolCallId:C.toolCallId,state:C.state,input:_.input,output:_.output,rawInput:_.rawInput,errorText:_.errorText,providerExecuted:_.providerExecuted,preliminary:_.preliminary,..._.providerMetadata!=null?{callProviderMetadata:_.providerMetadata}:{}})}function S(C){var N,k;const _=u.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===C.toolCallId),E=C,D=_;_!=null?(_.state=C.state,D.toolName=C.toolName,D.input=E.input,D.output=E.output,D.errorText=E.errorText,D.rawInput=(N=E.rawInput)!=null?N:D.rawInput,D.preliminary=E.preliminary,D.providerExecuted=(k=E.providerExecuted)!=null?k:_.providerExecuted,E.providerMetadata!=null&&_.state==="input-available"&&(_.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function w(C){if(C!=null){const N=u.message.metadata!=null?ffe(u.message.metadata,C):C;t!=null&&await qU({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const C={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=C,u.message.parts.push(C),d();break}case"text-delta":{const C=u.activeTextParts[a.id];C.text+=a.delta,C.providerMetadata=(f=a.providerMetadata)!=null?f:C.providerMetadata,d();break}case"text-end":{const C=u.activeTextParts[a.id];C.state="done",C.providerMetadata=(h=a.providerMetadata)!=null?h:C.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const C={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=C,u.message.parts.push(C),d();break}case"reasoning-delta":{const C=u.activeReasoningParts[a.id];C.text+=a.delta,C.providerMetadata=(p=a.providerMetadata)!=null?p:C.providerMetadata,d();break}case"reasoning-end":{const C=u.activeReasoningParts[a.id];C.providerMetadata=(g=a.providerMetadata)!=null?g:C.providerMetadata,C.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const C=u.message.parts.filter(aC);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const C=u.partialToolCalls[a.toolCallId];C.text+=a.inputTextDelta;const{value:N}=await hfe(C.text);C.dynamic?S({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}):y({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const C=x(a.toolCallId);S({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-available",input:C.input,output:a.output,preliminary:a.preliminary})}else{const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:XU(C),state:"output-available",input:C.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const C=x(a.toolCallId);S({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-error",input:C.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:XU(C),state:"output-error",input:C.input,rawInput:C.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await w(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await w(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await w(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(Rxt(a)){(n==null?void 0:n[a.type])!=null&&await qU({value:a.data,schema:n[a.type]});const C=a;if(C.transient){i==null||i(C);break}const N=C.id!=null?u.message.parts.find(k=>C.type===k.type&&C.id===k.id):void 0;N!=null?N.data=C.data:u.message.parts.push(C),i==null||i(C),d()}}c.enqueue(a)})}}))}async function $xt({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}xw({prefix:"aitxt",size:24});xw({prefix:"aiobj",size:24});var zxt=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};xw({prefix:"aiobj",size:24});var Bxt={};Cxt(Bxt,{object:()=>Hxt,text:()=>Vxt});var Vxt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Hxt=({schema:e})=>{const t=wxt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await hfe(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await bk({text:n});if(!s.success)throw new KU({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await a$({value:s.value,schema:t});if(!o.success)throw new KU({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function Uxt(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var Wxt=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Ip(this.body),c=await Ip(this.headers),u=await Ip(this.credentials),d={...cf(c),...cf(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,p=(f==null?void 0:f.headers)!==void 0?cf(f.headers):d,g=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},b=(s=f==null?void 0:f.credentials)!=null?s:u,y=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:UU({"Content-Type":"application/json",...p},`ai-sdk/${ZU}`,HU()),body:JSON.stringify(g),credentials:b,signal:e});if(!y.ok)throw new Error((i=await y.text())!=null?i:"Failed to fetch the chat response.");if(!y.body)throw new Error("The response body is empty.");return this.processResponseStream(y.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Ip(this.body),a=await Ip(this.headers),c=await Ip(this.credentials),u={...cf(a),...cf(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:c,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?cf(d.headers):u,p=(r=d==null?void 0:d.credentials)!=null?r:c,b=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:UU(h,`ai-sdk/${ZU}`,HU()),credentials:p});if(b.status===204)return null;if(!b.ok)throw new Error((o=await b.text())!=null?o:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}},c$=class extends Wxt{constructor(e={}){super(e)}processResponseStream(e){return Dbt({stream:e,schema:Axt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},qxt=class{constructor({generateId:e=ybt,id:t=e(),transport:n=new c$,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new zxt,this.sendMessage=async(f,h)=>{var p,g,b,x;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let y;if("text"in f||"files"in f?y={parts:[...Array.isArray(f.files)?f.files:await Uxt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:y=f,f.messageId!=null){const S=this.state.messages.findIndex(w=>w.id===f.messageId);if(S===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[S].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,S+1),this.state.replaceMessage(S,{...y,id:f.messageId,role:(g=y.role)!=null?g:"user",metadata:f.metadata})}else this.state.pushMessage({...y,id:(b=y.id)!=null?b:this.generateId(),role:(x=y.role)!=null?x:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(g=>g.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:p,output:g,errorText:b})=>this.jobExecutor.run(async()=>{var x,y;const S=this.state.messages,w=S[S.length-1];this.state.replaceMessage(S.length-1,{...w,parts:w.parts.map(C=>qR(C)&&C.toolCallId===p?{...C,state:f,output:g,errorText:b}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>qR(C)&&C.toolCallId===p?{...C,state:f,output:g,errorText:b}:C)),this.status!=="streaming"&&this.status!=="submitted"&&((x=this.sendAutomaticallyWhen)!=null&&x.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(y=this.lastMessage)==null?void 0:y.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=c,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const p={state:Oxt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=p;let g;if(e==="resume-stream"){const x=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(x==null){this.setStatus({status:"ready"});return}g=x}else g=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:p.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const b=x=>this.jobExecutor.run(()=>x({state:p.state,write:()=>{var y;this.setStatus({status:"streaming"}),p.state.message.id===((y=this.lastMessage)==null?void 0:y.id)?this.state.replaceMessage(this.state.messages.length-1,p.state.message):this.state.pushMessage(p.state.message)}}));await $xt({stream:Lxt({stream:g,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:b,onError:x=>{throw x}}),onError:x=>{throw x}}),this.setStatus({status:"ready"})}catch(p){if(d||p.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,p instanceof TypeError&&(p.message.toLowerCase().includes("fetch")||p.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&p instanceof Error&&this.onError(p),this.setStatus({status:"error",error:p})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(p){console.error(p)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function pfe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(qR).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function Yxt(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var Gxt=Yxt;const Kxt=m.getDefaultExportFromCjs(Gxt);var mfe=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},jr=(e,t,n)=>(mfe(e,t,"read from private field"),n?n.call(e):t.get(e)),qa=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},gu=(e,t,n,r)=>(mfe(e,t,"write to private field"),t.set(e,n),n);function Zxt(e,t){return t!=null?Kxt(e,t):e}var Ai,lC,cC,Hx,Ux,Wx,Up,YR,GR,Xxt=class{constructor(e=[]){qa(this,Ai,void 0),qa(this,lC,"ready"),qa(this,cC,void 0),qa(this,Hx,new Set),qa(this,Ux,new Set),qa(this,Wx,new Set),this.pushMessage=t=>{gu(this,Ai,jr(this,Ai).concat(t)),jr(this,Up).call(this)},this.popMessage=()=>{gu(this,Ai,jr(this,Ai).slice(0,-1)),jr(this,Up).call(this)},this.replaceMessage=(t,n)=>{gu(this,Ai,[...jr(this,Ai).slice(0,t),this.snapshot(n),...jr(this,Ai).slice(t+1)]),jr(this,Up).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?Zxt(t,n):t;return jr(this,Hx).add(r),()=>{jr(this,Hx).delete(r)}},this["~registerStatusCallback"]=t=>(jr(this,Ux).add(t),()=>{jr(this,Ux).delete(t)}),this["~registerErrorCallback"]=t=>(jr(this,Wx).add(t),()=>{jr(this,Wx).delete(t)}),qa(this,Up,()=>{jr(this,Hx).forEach(t=>t())}),qa(this,YR,()=>{jr(this,Ux).forEach(t=>t())}),qa(this,GR,()=>{jr(this,Wx).forEach(t=>t())}),gu(this,Ai,e)}get status(){return jr(this,lC)}set status(e){gu(this,lC,e),jr(this,YR).call(this)}get error(){return jr(this,cC)}set error(e){gu(this,cC,e),jr(this,GR).call(this)}get messages(){return jr(this,Ai)}set messages(e){gu(this,Ai,[...e]),jr(this,Up).call(this)}};Ai=new WeakMap;lC=new WeakMap;cC=new WeakMap;Hx=new WeakMap;Ux=new WeakMap;Wx=new WeakMap;Up=new WeakMap;YR=new WeakMap;GR=new WeakMap;var Wp,QU=class extends qxt{constructor({messages:e,...t}){const n=new Xxt(e);super({...t,state:n}),qa(this,Wp,void 0),this["~registerMessagesCallback"]=(r,s)=>jr(this,Wp)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>jr(this,Wp)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>jr(this,Wp)["~registerErrorCallback"](r),gu(this,Wp,n)}};Wp=new WeakMap;function gfe({experimental_throttle:e,resume:t=!1,...n}={}){const r=v.useRef("chat"in n?n.chat:new QU(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new QU(n));const o="id"in n?n.id:null,i=v.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=v.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=v.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=v.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=v.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return v.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function Qxt(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function Jxt(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function eyt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function tyt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function bfe(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:tyt(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function xfe(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function uE(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function yfe(e,t,n){const r=uE(e,t);if(!r)return[];const s=o=>{var i;return{sourceCard:o,visibleCard:((i=n==null?void 0:n[o.id])==null?void 0:i.visibleCard)||o,...n!=null&&n[o.id]?{replacedCard:n[o.id]}:{}}};return(r.frames||[]).map(o=>_j(o)).filter(o=>o!==void 0).map(s)}function vfe(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).map(r=>({name:r.name,type:r.type,connectionId:r.connectionId,...r.label?{label:r.label}:{}}))}function nyt(e){return{id:(e==null?void 0:e.id)||"",name:(e==null?void 0:e.name)||"",label:(e==null?void 0:e.label)||(e==null?void 0:e.name)||"",...e!=null&&e.dataType?{dataType:e.dataType}:{},...e!=null&&e.aggregate?{aggregate:e.aggregate}:{},...e!=null&&e.granularity?{granularity:e.granularity}:{},...e!=null&&e.direction?{direction:e.direction}:{}}}function nm(e){return(e||[]).map(nyt)}function wfe(e){return nm([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function u$(e){const t={operation:e.operation};return"value"in e&&e.value!==void 0&&(t.value=e.value),"values"in e&&Array.isArray(e.values)&&(t.values=e.values),t}function ryt(e,t,n){const r=new Map((e||[]).map(s=>[s.id,s]));return(t||[]).map(s=>{const o=r.get(s.filterId);return{filterId:s.filterId,label:(o==null?void 0:o.title)||s.label||s.name||s.filterId,...o!=null&&o.type?{type:o.type}:{},...o!=null&&o.column||s.name?{column:(o==null?void 0:o.column)||s.name}:{},...o!=null&&o.dataType?{dataType:o.dataType}:{},origin:n,...u$(s)}})}function syt(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...u$(t)}))}function Sfe(e,t){var n,r,s,o,i,a,c;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(s=e.field)!=null&&s.qualifiedFieldName||(o=e.field)!=null&&o.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(c=e.field)!=null&&c.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function l2(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((s,o)=>Sfe(s,`${t}:${r}:${o}`)))}function oyt(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function iyt(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function ayt(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(iyt).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...u$(r)})),n=e.filter(oyt).map((r,s)=>Sfe(r,`replaced-insight:${s}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function lyt({card:e,interactionStates:t,currentDashboardId:n}){var c;if(!t)return[];const r=m.getClickFiltersForCardFromStates(e.id,t),s=t[m.DRILL_CONTEXT_CARD_ID],i=(s==null?void 0:s.targetDashboardId)===n&&(s==null?void 0:s.contextMode)!=="none"?(s==null?void 0:s.appliedClickFilters)||[]:[],a=((c=t[e.id])==null?void 0:c.breadcrumbs)??[];return[...r.flatMap((u,d)=>l2(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>l2(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>l2(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function Cfe(e){return e?{logicalOperator:e.logicalOperator,negate:e.negate,conditions:(e.conditions||[]).map(t=>{var n,r;return{field:((n=t.field)==null?void 0:n.label)||((r=t.field)==null?void 0:r.name)||"",operator:t.operator,value:t.value}}),groups:(e.groups||[]).map(t=>Cfe(t)).filter(Boolean)}:null}function Nfe(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==tF.trim()}function cyt(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":Nfe(e)?"custom-python":"config"}function kfe({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:s,runtimeFilterValues:o,interactionStates:i,inlineFilterValuesMap:a}){const c=uE(r,s.selectedSheetId),u=(c==null?void 0:c.id)||s.selectedSheetId,{finalConfig:d}=fv({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=dv({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u}),h=ayt(n==null?void 0:n.filters),p=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:p?h.dashboardFilterValues:ryt(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:syt(a==null?void 0:a[t.id]),interactionFilterValues:p?h.interactionFilterValues:lyt({card:t,interactionStates:i,currentDashboardId:r.id})}}function uyt({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o,replacedCard:i,renderOrder:a}){const{finalConfig:c}=kfe({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o});return{cardId:e.id,...e.id!==t.id?{visibleCardId:t.id}:{},...i!=null&&i.insightId?{replacementInsightId:i.insightId}:{},title:t.title||"Untitled Card",type:t.type,renderOrder:a,metrics:nm(c.metricColumns),dimensions:wfe(c),selectedEntities:vfe(t)}}function dyt({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function JU({dashboard:e,selectedSheetId:t,activeFilters:n}){var s;const r=((s=uE(e,t??null))==null?void 0:s.id)||t||null;return{selectedSheetId:r,activeFilters:Ly(e.filters,n,r)}}function fyt({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:s}){const o=uE(e,t.selectedSheetId),i=(o==null?void 0:o.id)||t.selectedSheetId,a=yfe(e,t.selectedSheetId,s),c=Nd(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(o==null?void 0:o.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>uyt({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:c.map(u=>{var d,f;return{filterId:u.id,label:u.title,...u.type?{type:u.type}:{},scope:(d=u.applyToCardIds)!=null&&d.length||(f=u.excludeCardIds)!=null&&f.length?"card":"sheet"}}),activeFilterIds:dyt({activeFilters:t.activeFilters})}}function hyt({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:s,inlineFilterValuesMap:o,replacedCards:i}){var w,C;const c=yfe(e,t.selectedSheetId,i).find(({sourceCard:N,visibleCard:k})=>N.id===n||k.id===n);if(!c)return{found:!1,cardId:n,selectedEntities:[],metrics:[],dimensions:[],comparison:null,cardFilters:null,effectiveDashboardFilters:[],activeInlineFilters:[],activeInteractionFilters:[],sortingOrGroupingSummary:{groupBy:[],pivotBy:[],sortBy:[]},notes:["Card not found in the current selected sheet."]};const{sourceCard:u,visibleCard:d,replacedCard:f}=c,{finalConfig:h,dashboardFilterValues:p,inlineFilterValues:g,interactionFilterValues:b}=kfe({sourceCard:u,card:d,replacedCard:f,interactionStates:s,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:o}),{comparisonType:x,targetValue:y}=_Ye(h,d.type),S=cyt(d);return{found:!0,cardId:u.id,...u.id!==d.id?{visibleCardId:d.id}:{},...f!=null&&f.insightId?{replacementInsightId:f.insightId}:{},title:d.title,type:d.type,queryMode:S,...(w=d.sql)!=null&&w.trim()?{sql:d.sql.trim()}:{},...Nfe(d)?{python:(C=d.python)==null?void 0:C.trim()}:{},selectedEntities:vfe(d),metrics:nm(h.metricColumns),dimensions:wfe(h),comparison:x!=="none"?{type:x,...y!==void 0?{targetValue:y}:{}}:null,cardFilters:Cfe(h.filters),effectiveDashboardFilters:p,activeInlineFilters:g,activeInteractionFilters:b,sortingOrGroupingSummary:{groupBy:nm(h.groupByColumns),pivotBy:nm(h.pivotByColumns),sortBy:nm(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...S==="custom-sql"?["This card runs custom SQL."]:S==="custom-python"?["This card runs custom Python."]:[]]}}function qp(){return crypto.randomUUID()}function _fe(){return crypto.randomUUID()}function KR(e){return typeof(e==null?void 0:e.then)=="function"}async function pyt({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const s=Object.entries(e);if(s.length===0||!n)return{};const o=await Promise.all(s.map(async([i,a])=>{const c=["resource-by-id",Xr.VISUAL,a.insightId];let u=r.getQueryData(c);if(!u)try{u=await r.fetchQuery({queryKey:c,queryFn:()=>m.getRequest(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=Yie(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(o.filter(i=>i!==null))}function myt({dynamicVisualMode:e="auto"}={}){var R;const{compiledAppearance:t}=m.useAppearance(),n=v.useMemo(()=>PL(t),[t]),r=v.useRef(n);v.useEffect(()=>{r.current=n},[n]);const{authToken:s,tokenProps:o}=Ct(),i=ns(),a=m.useDashboardStore(B=>B.dashboard.aiScopeTables),c=(R=Q0().data)==null?void 0:R.assistantProfileId,u=v.useRef(null),d=v.useRef(qp()),f=v.useRef(!1),h=v.useRef(!1),p=v.useRef(e);p.current=e;function g(){const B=m.useAIInteractionStore.getState(),z=m.useDashboardStore.getState(),U=Jie({overrides:B.dashboardEntitySelectionOverrides,dashboardId:z.dashboard.id,draftScopeKey:z.dashboardAssistantDraftScopeKey});return m.appendQualifiedEntityNameToAIContext(BKe({currentAIContext:B.currentAIContext,manualSelectedEntities:U.selectedEntities,hasManualOverride:U.hasManualOverride,dashboardAIContext:z.dashboard.aiContext,derivedSelectedSheetEntities:Qie(z.dashboard,z.selectedSheetId)}))}function b(){const B=m.useDashboardStore.getState();return{aiContext:g(),dashboardViewState:JU({dashboard:B.dashboard,selectedSheetId:B.selectedSheetId,activeFilters:B.filterValues})}}const{sendMessage:x,messages:y,setMessages:S,regenerate:w,status:C,addToolResult:N,error:k,stop:_,clearError:E}=gfe({transport:new c$({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${s==null?void 0:s.accessToken}`}),body:()=>{const B=m.useAIInteractionStore.getState();u.current||(u.current=b());const{aiContext:z,dashboardViewState:U}=u.current;return{assistantId:"dashboard-assistant",assistantProfileId:c,conversationId:d.current,assistantRequestId:_fe(),aiContext:z,dashboardViewState:U,dynamicVisualMode:p.current,dynamicVisualTheme:r.current,reasoningEffort:B.reasoningEffort,showReasoning:B.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:B,body:z})=>({body:{...z,messages:m.cleanupIncompleteMessages(B)}})}),onToolCall:T,sendAutomaticallyWhen:pfe,onFinish({message:B,isAbort:z,isDisconnect:U,isError:Y}){var O;h.current=!1,B!=null&&B.id&&((O=u.current)!=null&&O.aiContext)&&m.useAIInteractionStore.getState().actions.setAssistantMessageContext(B.id,u.current.aiContext),console.log(z?"[Dashboard Assistant] Stream aborted by user":U?"[Dashboard Assistant] Stream disconnected (network error)":Y?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]))},onError(B){var z;if(h.current=!1,B.name==="AbortError"||(z=B.message)!=null&&z.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]));return}console.error("[Dashboard Assistant] Stream error:",B),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]))}}),D=v.useCallback((...B)=>{h.current=!0;try{const z=x(...B);return KR(z)?z.catch(U=>{throw h.current=!1,U}):z}catch(z){throw h.current=!1,z}},[x]),j=v.useCallback((...B)=>{h.current=!0;try{const z=w(...B);return KR(z)?z.catch(U=>{throw h.current=!1,U}):z}catch(z){throw h.current=!1,z}},[w]),I=B=>{let z=!1;S(U=>{const Y=typeof B=="function"?B(U):B;if(Y.length===0){if(h.current)return f.current=!0,z=!0,U;f.current=!1,d.current=qp()}return Y}),z&&_()};async function T({toolCall:B}){var M,G;if(B.toolName==="getCurrentTableScope"){N({tool:B.toolName,toolCallId:B.toolCallId,output:{tables:bfe(a||[])}});return}const z=m.useDashboardStore.getState().dashboard,U=m.useDashboardStore.getState().inlineFilterValuesMap,Y=m.useInteractionStore.getState(),O=Y.interactionStates,K=await pyt({replacedCards:Y.replacedCards,apiServiceUrl:o.apiServiceUrl,accessToken:(s==null?void 0:s.accessToken)||"",queryClient:i}),q=JU({dashboard:z,selectedSheetId:m.useDashboardStore.getState().selectedSheetId,activeFilters:m.useDashboardStore.getState().filterValues});if(B.toolName==="getDashboardSynopsis"){N({tool:B.toolName,toolCallId:B.toolCallId,output:fyt({dashboard:z,viewState:q,interactionStates:O,inlineFilterValuesMap:U,replacedCards:K})});return}if(B.toolName==="getCardContext"){const L=((M=B.input)==null?void 0:M.cardId)||((G=B.args)==null?void 0:G.cardId)||"";N({tool:B.toolName,toolCallId:B.toolCallId,output:hyt({dashboard:z,viewState:q,cardId:L,runtimeFilterValues:m.useDashboardStore.getState().filterValues,interactionStates:O,inlineFilterValuesMap:U,replacedCards:K})})}}const F=!["ready","error"].includes(C),P=xfe(k);return{sendMessage:D,regenerate:j,isLoading:F,messages:y,setMessages:I,status:C,stop:_,errorMessage:P,clearError:E}}function jfe(){var u;const{authToken:e,tokenProps:t}=Ct(),n=(u=Q0().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=On({queryKey:["assistant-profile",n],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Efe({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(pq,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(m.Button,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function gyt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=v.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=ic-n;if(c.length>u){ut.error(`You can only attach ${ic} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=que(c);if(f.forEach(({file:h,error:p})=>{ut.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>Z3(p)));e(h)}catch(h){console.error("Failed to process files:",h),ut.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=ic}),l.jsx(m.Button,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=ic,title:n>=ic?`Maximum ${ic} files allowed`:"Attach files",children:l.jsx(Nq,{className:"h-4 w-4 text-muted-foreground"})})]})}function byt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=v.useState(!1),a=v.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=v.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,g=f.clientY;(p<h.left||p>=h.right||g<h.top||g>=h.bottom)&&i(!1)},[]),u=v.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=v.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=ic-r;if(h.length>p){ut.error(`You can only attach ${ic} files per message. You have ${p} slot(s) remaining.`);return}const{valid:g,errors:b}=que(h);if(b.forEach(({file:x,error:y})=>{ut.error(`${x.name}: ${y}`)}),g.length>0)try{const x=await Promise.all(g.map(y=>Z3(y)));t(x),ut.success(`${x.length} file(s) attached successfully`)}catch(x){console.error("Failed to process files:",x),ut.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:m.cn("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-control border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(m.Upload,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[ic-r," slot(s) available"]})]})})]})}function xyt(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function yyt({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!xyt(e,t,n):r}function Dfe(e){const{tokenProps:t}=Ct(),n=m.useDashboardStore(c=>c.authToken)||e;m.useEditorStore(c=>c.selectedConnectionId),m.useEditorStore(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=On({queryKey:["semantic-domains"],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function vyt({domainAccess:e,search:t,scopeDomainId:n,selectedEntities:r,onSelectionChange:s}){const{semanticDomains:o,isSemanticDomainsLoading:i}=Dfe(),a=v.useMemo(()=>Syt(o,e),[o,e]),c=v.useMemo(()=>n?a.filter(d=>d.id===n):a,[a,n]);if(i&&c.length===0)return l.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading semantic domains…"});if(c.length===0)return null;const u=!!n;return l.jsxs("div",{children:[l.jsx(Ife,{label:"Semantic Domains"}),c.map(d=>l.jsx(wyt,{domain:d,search:t,forceExpanded:u,selectedEntities:r,onSelectionChange:s},d.id))]})}function wyt({domain:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:s}){const[o,i]=v.useState(!1),a=o||t.length>0||!!n,{datasets:c,isPending:u}=nNe(a?e.id:void 0),d=v.useMemo(()=>{if(!t)return c;const x=t.trim().toLowerCase();return c.filter(y=>`${y.label??""} ${y.name??""} ${y.description??""}`.toLowerCase().includes(x))},[c,t]),f=t.length>0&&d.length>0,h=o||f||!!n,p=c.length,g=v.useMemo(()=>d.filter(x=>r.some(y=>zr(y,c2(x)))).length,[d,r]),b=x=>{const y=c2(x),S=r.some(w=>zr(w,y));s(S?r.filter(w=>!zr(w,y)):[...r,y])};return t.length>0&&!f&&!u?null:l.jsxs("div",{children:[l.jsxs("button",{type:"button",onClick:()=>i(x=>!x),className:"flex w-full items-center gap-1.5 rounded-[4px] px-3 py-1.5 text-left transition-colors hover:bg-muted/50",children:[l.jsx(Mr,{className:m.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",h&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:e.label||e.name}),p>0&&l.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["· ",p," dataset",p===1?"":"s"," · curated"]}),l.jsx("span",{className:"ml-auto font-mono text-[10px] tabular-nums text-muted-foreground",children:g>0?g:""})]}),h&&l.jsx("ul",{className:"space-y-px pb-1",children:u&&c.length===0?l.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"Loading datasets…"}):d.length===0?l.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"No datasets in this domain."}):d.map(x=>{const y=c2(x),S=r.some(w=>zr(w,y));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-start gap-2 rounded-[4px] px-9 py-1.5 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:S,onCheckedChange:()=>b(x),className:"mt-[3px] h-3.5 w-3.5 shrink-0"}),l.jsx(ei,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground",children:x.label||x.name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:x.type==="virtual"?"virtual":"dataset"})]}),x.description&&l.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.4] text-muted-foreground",children:x.description})]})]})},x.id)})})]})}function Ife({label:e}){return l.jsx("div",{className:"px-3 pb-1.5 pt-2.5",children:l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e})})}function Syt(e,t){if(!t||t.mode==="all")return e;const n=new Set(t.domainIds??[]);return t.mode==="include"?e.filter(r=>n.has(r.id)):t.mode==="exclude"?e.filter(r=>!n.has(r.id)):[]}function c2(e){return{id:e.id,datasetType:e.type,name:e.name||e.table,label:e.label,domainId:e.domainId,description:e.description,database:e.database,schema:e.schema,table:e.table,type:"dataset",connectionId:e.connectionId,connectionType:e.connectionType,dialect:e.dialect,datamodelId:e.datamodelId,sql:e.sql}}function Cyt({search:e,scopeConnectionId:t,selectedEntities:n,onSelectionChange:r}){const{connections:s,isConnectionsLoading:o}=Xc(),i=v.useMemo(()=>t?s.filter(c=>c.id===t):s,[s,t]);if(o&&i.length===0)return l.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading connections…"});if(i.length===0)return null;const a=!!t;return l.jsxs("div",{children:[l.jsx(Ife,{label:"Direct Sources"}),i.map(c=>l.jsx(Nyt,{connection:c,search:e,forceExpanded:a,selectedEntities:n,onSelectionChange:r},c.id))]})}function Nyt({connection:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:s}){var g;const[o,i]=v.useState(!1),a=o||t.length>0||!!n,c=((g=e.capabilities)==null?void 0:g.path)??[],u=c.includes("database"),d=c.includes("schema"),f=e.type==="upload",h=e.type==="url",p=v.useMemo(()=>r.filter(b=>b.connectionId===e.id).length,[r,e.id]);return l.jsxs("div",{className:"border-b border-border/60 last:border-b-0",children:[l.jsxs("button",{type:"button",onClick:()=>i(b=>!b),className:"flex w-full items-center gap-2 px-4 py-1.5 text-left transition-colors hover:bg-muted/40",children:[l.jsx(Mr,{className:m.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate text-[13px] font-medium text-foreground/90",children:e.name}),l.jsxs("span",{className:"truncate text-[11px] text-muted-foreground",children:["· ",e.type]}),l.jsx("span",{className:"ml-auto shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground",children:p>0?p:""})]}),a&&l.jsxs(l.Fragment,{children:[f?l.jsx(kyt,{connection:e,selectedEntities:r,onSelectionChange:s}):h?l.jsx(_yt,{connection:e,selectedEntities:r,onSelectionChange:s}):u?l.jsx(jyt,{connection:e,requiresSchema:d,search:t,selectedEntities:r,onSelectionChange:s}):d?l.jsx(Tfe,{connection:e,databaseName:"",search:t,selectedEntities:r,onSelectionChange:s}):l.jsx(d$,{connection:e,databaseName:"",schemaName:"",search:t,selectedEntities:r,onSelectionChange:s}),!f&&!h&&l.jsx(Eyt,{connection:e,search:t,selectedEntities:r,onSelectionChange:s})]})]})}function kyt({connection:e,selectedEntities:t,onSelectionChange:n}){const r=`upload-source-${e.id}`,s=t.filter(a=>a.connectionId===e.id&&(a.type==="upload"||a.type==="file")),o=a=>{if(!(a!=null&&a.length))return;const c=Array.from(a).map(u=>({id:`file-${Date.now()}-${Math.random()}`,name:u.name,type:"upload",connectionId:e.id,connectionType:e.type,label:u.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:u.name,file:u}));n([...t,...c])},i=a=>{n(t.filter(c=>!("id"in c&&c.id===a&&c.connectionId===e.id&&(c.type==="upload"||c.type==="file"))))};return l.jsxs("div",{className:"space-y-2 px-8 py-2",children:[l.jsxs("div",{className:"rounded-[6px] border border-dashed border-border bg-muted/20 p-4 text-center",children:[l.jsx(m.Upload,{className:"mx-auto mb-2 h-5 w-5 text-muted-foreground"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Add CSV, JSON, or Excel files."}),l.jsx("input",{id:r,type:"file",multiple:!0,className:"hidden",onChange:a=>o(a.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(m.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2 h-7 text-[12px]",onClick:()=>{var a;return(a=document.getElementById(r))==null?void 0:a.click()},children:"Select files"})]}),s.length>0&&l.jsx("ul",{className:"space-y-1",children:s.map(a=>l.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[l.jsx(vi,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px]",children:a.originalName||a.name}),l.jsx("button",{type:"button","aria-label":`Remove ${a.originalName||a.name}`,onClick:()=>i(a.id),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]},a.id))})]})}function _yt({connection:e,selectedEntities:t,onSelectionChange:n}){const[r,s]=v.useState(""),[o,i]=v.useState(""),[a,c]=v.useState("api"),u=t.filter(h=>h.connectionId===e.id&&h.type==="url"),d=()=>{const h=r.trim(),p=o.trim();if(!h||!p)return;const g={id:`url-${Date.now()}-${Math.random()}`,name:h,type:"url",connectionId:e.id,connectionType:e.type,label:h,description:`URL source of type ${a}`,originalName:h,url:p,sourceType:a};n([...t,g]),s(""),i(""),c("api")},f=h=>{n(t.filter(p=>!("id"in p&&p.id===h&&p.connectionId===e.id&&p.type==="url")))};return l.jsxs("div",{className:"space-y-2 px-8 py-2",children:[l.jsxs("div",{className:"space-y-2 rounded-[6px] border border-border bg-muted/20 p-3",children:[l.jsx(m.Input,{value:r,onChange:h=>s(h.target.value),placeholder:"Source name",className:"h-7 text-[12px]"}),l.jsx(m.Input,{value:o,onChange:h=>i(h.target.value),placeholder:"https://api.example.com/data",className:"h-7 text-[12px]"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("select",{value:a,onChange:h=>c(h.target.value),className:"h-7 flex-1 rounded-control border border-input bg-background px-2 text-[12px]",children:[l.jsx("option",{value:"api",children:"API endpoint"}),l.jsx("option",{value:"csv",children:"CSV file"}),l.jsx("option",{value:"json",children:"JSON file"})]}),l.jsxs(m.Button,{type:"button",size:"sm",className:"h-7 text-[12px]",disabled:!r.trim()||!o.trim(),onClick:d,children:[l.jsx(dr,{className:"mr-1 h-3 w-3"}),"Add"]})]})]}),u.length>0&&l.jsx("ul",{className:"space-y-1",children:u.map(h=>l.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[l.jsx(gg,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"truncate text-[12px]",children:h.name}),l.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:h.url})]}),l.jsx("button",{type:"button","aria-label":`Remove ${h.name}`,onClick:()=>f(h.id),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]},h.id))})]})}function jyt({connection:e,requiresSchema:t,search:n,selectedEntities:r,onSelectionChange:s}){var a;const o=dE("/v1/databases",{connection_id:e.id},["databases",e.id]);if(o.isLoading)return l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading databases…"});const i=((a=o.data)==null?void 0:a.databases)??[];return i.length===0?l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No databases."}):l.jsx("div",{children:i.map(c=>l.jsx(Mfe,{label:c.database_name,indentLevel:1,search:n,renderChildren:u=>u&&(t?l.jsx(Tfe,{connection:e,databaseName:c.database_name,search:n,selectedEntities:r,onSelectionChange:s}):l.jsx(d$,{connection:e,databaseName:c.database_name,schemaName:"",search:n,selectedEntities:r,onSelectionChange:s}))},c.database_name))})}function Tfe({connection:e,databaseName:t,search:n,selectedEntities:r,onSelectionChange:s}){var a;const o=dE("/v1/schemas",{connection_id:e.id,database_name:t||"NA"},["schemas",e.id,t],!!e.id);if(o.isLoading)return l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading schemas…"});const i=((a=o.data)==null?void 0:a.schemas)??[];return i.length===0?l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No schemas."}):l.jsx("div",{children:i.map(c=>l.jsx(Mfe,{label:c.schema_name,indentLevel:t?2:1,search:n,renderChildren:u=>u&&l.jsx(d$,{connection:e,databaseName:t,schemaName:c.schema_name,search:n,selectedEntities:r,onSelectionChange:s})},c.schema_name))})}function d$({connection:e,databaseName:t,schemaName:n,search:r,selectedEntities:s,onSelectionChange:o}){const i=dE("/v1/tables",{connection_id:e.id,database_name:t||void 0,schema_name:n||void 0},["tables",e.id,t,n]),a=v.useMemo(()=>{var f;const u=((f=i.data)==null?void 0:f.tables)??[];if(!r)return u;const d=r.trim().toLowerCase();return u.filter(h=>h.table_name.toLowerCase().includes(d))},[i.data,r]);if(i.isLoading)return l.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"Loading tables…"});if(a.length===0)return r?null:l.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"No tables."});const c=(u,d)=>{const f={connectionId:e.id,connectionType:e.type,type:"table",dialect:e.dialect,database:t||void 0,schema:n||void 0,name:u,dbObjectType:d==null?void 0:d.toLowerCase()},h=s.some(p=>zr(p,f));o(h?s.filter(p=>!zr(p,f)):[...s,f])};return l.jsx("ul",{children:a.map(u=>{var h;const d={connectionId:e.id,connectionType:e.type,type:"table",dialect:e.dialect,database:t||void 0,schema:n||void 0,name:u.table_name,dbObjectType:(h=u.table_type)==null?void 0:h.toLowerCase()},f=s.some(p=>zr(p,d));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 py-1.5 pl-12 pr-4 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:f,onCheckedChange:()=>c(u.table_name,u.table_type),className:"h-3.5 w-3.5 shrink-0"}),l.jsx(m.Table2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"flex min-w-0 flex-1 items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:u.table_name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:u.table_type??"table"})]})]})},u.table_name)})})}function Eyt({connection:e,search:t,selectedEntities:n,onSelectionChange:r}){const s=dE("/v1/datamodels",{connection_id:e.id},["datamodels",e.id]),o=v.useMemo(()=>{var u;const a=((u=s.data)==null?void 0:u.datamodels)??[];if(!t)return a;const c=t.trim().toLowerCase();return a.filter(d=>`${d.label??""} ${d.name??""} ${d.description??""}`.toLowerCase().includes(c))},[s.data,t]);if(s.isLoading||o.length===0)return null;const i=a=>{const c={id:a.id,name:a.name,label:a.label||"",description:a.description||"",connectionId:e.id,connectionType:e.type,type:"model",dialect:a.dialect??e.dialect,database:a.database||"",schema:a.schema||""},u=n.some(d=>zr(d,c));r(u?n.filter(d=>!zr(d,c)):[...n,c])};return l.jsxs("div",{children:[l.jsx("div",{className:"px-8 pb-1 pt-2",children:l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data models"})}),l.jsx("ul",{children:o.map(a=>{const c={id:a.id,name:a.name,label:a.label||"",description:a.description||"",connectionId:e.id,connectionType:e.type,type:"model",dialect:a.dialect??e.dialect,database:a.database||"",schema:a.schema||""},u=n.some(d=>zr(d,c));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5 py-1.5 pl-12 pr-4 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:u,onCheckedChange:()=>i(a),className:"mt-[2px] h-3.5 w-3.5 shrink-0"}),l.jsx(sme,{className:"mt-[2px] h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:a.label||a.name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:"model"})]}),a.description&&l.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",children:a.description})]})]})},a.id)})})]})}function Mfe({label:e,indentLevel:t,search:n,renderChildren:r}){const[s,o]=v.useState(!1),i=s||n.length>0,a=t===1?"pl-8":"pl-10";return l.jsxs("div",{children:[l.jsxs("button",{type:"button",onClick:()=>o(c=>!c),className:m.cn("flex h-6 w-full items-center gap-1.5 pr-4 text-left transition-colors hover:bg-muted/40",a),children:[l.jsx(Mr,{className:m.cn("h-2.5 w-2.5 shrink-0 text-muted-foreground transition-transform",i&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate font-mono text-[11px] text-muted-foreground",children:e})]}),r(i)]})}function dE(e,t,n,r=!0){const{tokenProps:s}=Ct(),o=m.useDashboardStore(a=>a.authToken),i=v.useMemo(()=>Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0)),[t]);return On({queryKey:n,queryFn:()=>m.getRequest(`${s.apiServiceUrl}${e}`,(o==null?void 0:o.accessToken)||"",i),enabled:r&&!!(o!=null&&o.accessToken)&&Object.values(i).every(a=>a.length>0)})}function eW(e){return e.type==="dataset"&&e.label||e.name}function Dyt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs("span",{className:"inline-flex items-center gap-1 rounded-control border border-input bg-muted/50 py-0.5 pl-1.5 pr-0.5 text-[11px] text-foreground/80",children:[l.jsx("span",{className:"max-w-[180px] truncate",children:eW(n)}),l.jsx("button",{type:"button",onClick:s=>{s.stopPropagation(),t(n)},"aria-label":`Remove ${eW(n)}`,className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-2.5 w-2.5"})})]},`${n.type}-${n.name}-${r}`))})}function tW(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function u2(e){if(e!=null&&e.length)return e.every(t=>t.type==="dataset")?"semanticDomain":e.every(t=>t.type==="url")?"url":e.every(t=>t.type==="upload"||t.type==="file")?"upload":"database"}function f$({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o,saveAsDashboardDefault:i=!1}){var ue,ve;const{tokenProps:a}=Ct(),c=a.config,u=a.semanticDomainAccess||bhe.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[d,f]=v.useState([]),[h,p]=v.useState(void 0),[g,b]=v.useState(""),[x,y]=v.useState("all"),[S,w]=v.useState(void 0),C=v.useRef(!1),{updateDataSource:N}=m.useEditorActions(),k=m.useDashboardStore(xe=>xe.isVisualEditing),_=m.useDashboardStore(xe=>xe.dashboard.aiContext),{setAiContext:E}=m.useDashboardActions(),D=u.mode,j=(c==null?void 0:c.showDirectSource)!==!1,I=D==="include"||D==="exclude"||!j,T=D!=="all",F=j&&!I,P=I?"semanticDomain":n.mode,R=r==="dataSource"&&!j,B=D==="include"&&(((ue=u.domainIds)==null?void 0:ue.length)||0)===1?(ve=u.domainIds)==null?void 0:ve[0]:void 0,z=v.useCallback(xe=>{C.current=!0,N({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:xe,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...xe!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,N]),U=v.useCallback(xe=>{N({...n,...xe})},[n,N]),Y=v.useCallback(xe=>{if(r==="aiContext"){"semanticDomainId"in xe&&p(xe.semanticDomainId);return}U(xe)},[r,U]),O=r==="aiContext"?h:n.semanticDomainId;r==="aiContext"&&{...n},v.useEffect(()=>{if(r==="aiContext"&&!e)return;if(I&&n.mode!=="semanticDomain"&&r==="dataSource"){z("semanticDomain");return}if(!T||P!=="semanticDomain")return;const xe=O,ke=u.domainIds??[],se=r==="aiContext"?d:n.selectedEntities,be=((se==null?void 0:se.length)??0)>0,Ce=((d==null?void 0:d.length)??0)>0;yyt({mode:D,currentDomainId:xe,scopedDomainIds:ke,hasSelectedEntities:be})&&(r==="dataSource"?U({semanticDomainId:void 0,selectedEntities:[]}):p(void 0),Ce&&f([]))},[I,T,P,n.mode,O,n.selectedEntities,r,h,d,e,u.domainIds,D,j,U,z]),v.useEffect(()=>{B&&!O&&Y({semanticDomainId:B})},[B,O,Y]),v.useEffect(()=>{if(!e){C.current=!1,b(""),w(void 0),y(I?"semantic":"all");return}if(C.current)return;f([...s||[]]);const xe=r==="aiContext"?tW(s):void 0;p(n.semanticDomainId||xe),w(u2(s))},[e,r,s,n.semanticDomainId,I]);const K=xe=>{C.current=!0,f(d.filter(ke=>!zr(ke,xe)))},q=v.useCallback((xe,ke)=>{C.current=!0,f(xe),w(ke??u2(xe))},[]),M=()=>{var ke,se;if(r==="aiContext"){if(k&&N(n),i){const be={..._,selectedEntities:d,mode:d.length>0?"fixed":"auto"};E(be)}o==null||o(d),t(!1);return}const xe=u2(d)??S??P;if(xe==="semanticDomain"){const be=tW(d)||h||n.semanticDomainId,Ce=((ke=d==null?void 0:d[0])==null?void 0:ke.connectionId)||n.connectionId,ge=((se=d==null?void 0:d[0])==null?void 0:se.connectionType)||n.connectionType;N({...n,mode:"semanticDomain",semanticDomainId:be,connectionId:Ce,connectionType:ge,selectedEntities:d})}else if(xe==="upload"||xe==="url"){const be=d==null?void 0:d[0];N({...n,mode:xe,semanticDomainId:void 0,connectionId:(be==null?void 0:be.connectionId)||n.connectionId,connectionType:(be==null?void 0:be.connectionType)||n.connectionType,selectedEntities:d})}else{const be=d==null?void 0:d[0];N({...n,mode:"database",semanticDomainId:void 0,connectionId:(be==null?void 0:be.connectionId)||n.connectionId,connectionType:(be==null?void 0:be.connectionType)||n.connectionType,selectedEntities:d})}t(!1)},{semanticDomains:G}=Dfe(),{connections:L}=Xc(),$=xe=>{y(xe),xe==="semantic"||xe.startsWith("domain:")?n.mode!=="semanticDomain"&&z("semanticDomain"):(xe==="direct"||xe.startsWith("conn:"))&&n.mode==="semanticDomain"&&z("database")},V=x.startsWith("domain:"),H=x.startsWith("conn:"),A=V?x.slice(7):void 0,W=H?x.slice(5):void 0,X=!F||x==="all"||x==="semantic"||V,Z=j&&!I&&(x==="all"||x==="direct"||H),J=((s==null?void 0:s.length)??0)>0,re=d.length===0&&!J,fe=d.length===0&&J?"Clear":"Add",de=r==="aiContext"?"Data context":R?"Select dataset":"Add data",Se=r==="aiContext"?"Set the overall data scope for the dashboard":R?"Choose a curated dataset to analyze":"Search your semantic domains and connections";return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{showCloseButton:!1,className:"flex h-[560px] w-[620px] max-w-[620px] flex-col gap-0 overflow-hidden rounded-[6px] border border-border bg-popover p-0",children:[l.jsx(m.VisuallyHidden,{children:l.jsx(go,{children:de})}),l.jsxs("div",{className:"flex items-start justify-between border-b border-border px-4 py-2.5",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-[14px] font-semibold text-foreground",children:de}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:Se})]}),l.jsx("button",{type:"button",onClick:()=>t(!1),"aria-label":"Close",className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3.5 w-3.5"})})]}),l.jsxs("div",{className:"border-b border-border px-4 py-2.5",children:[l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[l.jsx(Ws,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("input",{type:"text",value:g,onChange:xe=>b(xe.target.value),placeholder:"Search datasets, tables, views, models",className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none"}),g&&l.jsx("button",{type:"button",onClick:()=>b(""),"aria-label":"Clear search",className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),F&&l.jsx("div",{className:"-mx-4 mt-2 overflow-x-auto px-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:l.jsxs("div",{className:"flex w-max items-center gap-1",children:[l.jsx(ux,{label:"All",active:x==="all",onClick:()=>$("all")}),(G.length>0||L.length>0)&&l.jsxs(l.Fragment,{children:[l.jsx(ux,{label:"Semantic",active:x==="semantic",onClick:()=>$("semantic")}),l.jsx(ux,{label:"Direct",active:x==="direct",onClick:()=>$("direct")}),l.jsx("span",{className:"shrink-0 px-0.5 text-muted-foreground/50",children:"·"})]}),G.map(xe=>l.jsx(ux,{label:xe.label||xe.name,active:x===`domain:${xe.id}`,onClick:()=>$(`domain:${xe.id}`)},`domain:${xe.id}`)),L.map(xe=>l.jsx(ux,{label:xe.name,active:x===`conn:${xe.id}`,onClick:()=>$(`conn:${xe.id}`)},`conn:${xe.id}`))]})})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[X&&l.jsx(vyt,{domainAccess:u,search:g,scopeDomainId:A,selectedEntities:d,onSelectionChange:xe=>q(xe,"semanticDomain")}),Z&&l.jsx(Cyt,{search:g,scopeConnectionId:W,selectedEntities:d,onSelectionChange:xe=>q(xe)})]}),l.jsxs("div",{className:"flex flex-col gap-0.5 border-t border-border px-4 py-2.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[l.jsx("span",{children:"Selected"}),l.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["· ",d.length]})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("button",{type:"button",onClick:()=>t(!1),className:"inline-flex h-7 items-center rounded-control px-2.5 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:"Cancel"}),l.jsxs("button",{type:"button",onClick:M,disabled:re,className:m.cn("inline-flex h-7 items-center gap-1.5 rounded-control bg-primary px-2.5 text-[12px] font-medium text-primary-foreground transition-colors hover:bg-primary/90",re&&"cursor-not-allowed opacity-50 hover:bg-primary"),children:[l.jsx("span",{children:fe}),d.length>0&&l.jsxs("span",{className:"font-mono tabular-nums text-primary-foreground/70",children:["· ",d.length]})]})]})]}),d.length>0&&l.jsx(Dyt,{selectedEntities:d,onDeselectEntity:K})]})]})})}function ux({label:e,active:t,onClick:n}){return l.jsx("button",{type:"button",onClick:n,"aria-pressed":t,className:m.cn("inline-flex h-6 shrink-0 items-center whitespace-nowrap rounded-control px-2 text-[11px] font-medium transition-colors",t?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:e})}function xk(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(vF,{className:r});case"view":return l.jsx(tv,{className:r});case"materialized view":return l.jsx(ume,{className:r});case"model":return l.jsx(nv,{className:r});case"file":return l.jsx(vi,{className:r});case"dataset":return l.jsx(ei,{className:r});case"upload":return l.jsx(m.Upload,{className:r});case"url":return l.jsx(hF,{className:r});default:return l.jsx(gg,{className:r})}}const ZR=e=>e.name||e.name,Iyt=e=>{const t=ZR(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function Tyt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=v.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(m.TooltipProvider,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const p="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsxs(Yr,{variant:"secondary",className:"group relative h-6 cursor-pointer gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors",children:[xk(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate",children:ZR(f)}),l.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>n(f),children:l.jsx(m.X,{className:"h-3 w-3"})})]})}),l.jsx(m.TooltipContent,{side:"top",className:"max-w-xs",children:Iyt(f)})]},p)}),d&&l.jsxs(m.Tooltip,{open:o,onOpenChange:i,children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsxs(Yr,{variant:"secondary",className:"flex h-6 cursor-pointer items-center gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(ja,{className:"h-3 w-3"}),l.jsxs("span",{children:[u.length," more"]}),l.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>r(u),children:l.jsx(m.X,{className:"h-3 w-3"})})]})}),l.jsx(m.TooltipContent,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:xk(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:ZR(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(m.X,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const Afe=Q.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Ws,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(bo.Input,{ref:n,className:m.cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Afe.displayName=bo.Input.displayName;const bS=e=>e.label||(e==null?void 0:e.name),nW=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Myt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=Ct(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=v.useState(""),[g,b]=v.useState(""),x=s.filter(k=>{if(!h)return!0;const _=bS(k).toLowerCase(),E=(nW(k)||"").toLowerCase(),D=h.toLowerCase();return _.includes(D)||E.includes(D)});v.useEffect(()=>{e||(p(""),b(""))},[e]),v.useEffect(()=>{x.length>0&&!g&&b(bS(x[0]))},[x,g]);const y=()=>{if(!g)return;const k=x.find(_=>bS(_)===g);k&&(o.some(E=>"id"in k&&"id"in E?k.id===E.id:k.name===E.name&&k.connectionId===E.connectionId)||t(k),i(k),r())},S=k=>{(k.key==="Tab"||k.key==="Enter")&&(k.preventDefault(),y())};if(!e)return null;const w=k=>o.some(_=>"id"in k&&"id"in _?k.id===_.id:k.name===_.name&&k.connectionId===_.connectionId),C=o.length===s.length,N=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(Pj,{shouldFilter:!1,value:g,onValueChange:b,onKeyDown:S,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx(Afe,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),u==null||u()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(dr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),a==null||a()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},disabled:C,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),N&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),c==null||c()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(m.X,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(Oj,{className:"min-h-60",children:[l.jsx(Lj,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),u==null||u()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(dr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx($j,{children:x.map((k,_)=>{const E=w(k),D="id"in k?k.id:`${k.connectionId}-${k.name}`,j=bS(k);return l.jsxs(zj,{value:j,onSelect:()=>{E?n==null||n(k):t(k)},onMouseDown:I=>{I.preventDefault(),I.stopPropagation()},className:m.cn("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:xk(k.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:j}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:nW(k)})]}),E&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(m.Check,{className:"h-3 w-3 text-background"})})]},D)})})]})]})})}function XR({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:p="secondary",triggerLabel:g="Add entity",triggerIconOnly:b=!0,assistantType:x}){const[y,S]=v.useState(!1),[w,C]=v.useState(!1),N=o??y,k=o!==void 0,_=v.useRef(!1),D=m.useEditorStore(A=>A.card.dataSource)??z0,{selectedEntities:j,availableEntities:I,syncWithGlobalContext:T,setSelectedEntities:F,applyDashboardDefaultEntities:P,isEntitySelected:R}=jj(x),B=e==="full"||e==="display",z=e==="full"||e==="trigger",U=v.useMemo(()=>b&&j.length>0?`Add entity (${j.length})`:g,[j.length,b,g]);v.useEffect(()=>{N&&!_.current&&s&&T(),_.current=N},[N,s,T]);const Y=v.useCallback(A=>{k||S(A),i==null||i(A)},[k,i]),O=v.useCallback(A=>{const W=j.filter(X=>!zr(X,A));F(W),c==null||c(A),d==null||d(W)},[c,d,j,F]),K=v.useCallback(A=>{if(A.length===0)return;const W=j.filter(X=>!A.some(Z=>zr(X,Z)));F(W),u==null||u(A),d==null||d(W)},[u,d,j,F]),q=v.useCallback(A=>{const W=R(A)?j.filter(X=>!zr(X,A)):[...j,A];F(W),d==null||d(W)},[R,d,j,F]),M=v.useCallback(()=>{F(I),d==null||d(I)},[I,d,F]),G=v.useCallback(()=>{F([]),d==null||d([])},[d,F]),L=v.useCallback(A=>{x==="dashboard"?P():F(A),d==null||d(A)},[P,x,d,F]),$=v.useCallback(A=>{const W=j.some(X=>zr(X,A))?j:[...j,A];F(W),a==null||a(A),d==null||d(W),Y(!1)},[a,d,j,Y,F]),V=B?l.jsx(Tyt,{className:m.cn(n?"contents":"space-y-2"),entities:j,availableEntities:I,onRemoveEntity:O,onRemoveEntities:K}):null,H=z?l.jsxs(l.Fragment,{children:[l.jsxs(m.Popover,{open:N,onOpenChange:Y,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsxs(m.Button,{variant:p,size:"xs",className:m.cn(t&&"h-6 gap-1.5 px-2 text-[11px] font-medium",h),title:g,children:[l.jsx(QW,{className:"h-3 w-3 text-muted-foreground"}),!b&&l.jsx("span",{children:U})]})}),l.jsx(m.PopoverContent,{className:m.cn("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:A=>A.preventDefault(),children:l.jsx(Myt,{isOpen:!0,onSelect:q,onDeselect:q,onClose:()=>Y(!1),availableEntities:I,selectedEntities:j,onTabComplete:$,onSelectAll:M,onRemoveAll:G,onAddContext:()=>{Y(!1),C(!0)}})})]}),l.jsx(f$,{incomingSelectedEntities:j,open:w,onOpenChange:C,dataSource:D,dialogMode:"aiContext",onSaveSelectedEntities:L,saveAsDashboardDefault:x==="dashboard"})]}):null;return l.jsx("div",{className:m.cn(n?"flex flex-wrap items-center gap-1":"",!n&&B?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[H,V]}):l.jsxs(l.Fragment,{children:[V,H]})})}const h$=v.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=v.useState(!1),h=v.useRef(null),{queueMessage:p}=m.useQueueActions(),{addFileAttachment:g,removeFileAttachment:b,clearFileAttachments:x}=m.useFileActions(),y=m.useFileAttachments(c);v.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const S=v.useCallback(()=>{const j=h.current;if(j){if(!e||e.length===0){j.style.height="10px";return}j.style.height="auto";const I=Math.min(Math.max(j.scrollHeight,10),200);j.style.height=`${I}px`}},[e]);v.useEffect(()=>{S()},[S]),v.useEffect(()=>{const j=setTimeout(()=>{S()},0);return()=>clearTimeout(j)},[S]);const w=()=>{const j=e.trim();!j&&y.length===0||(a!=="ready"?(p(c,j,y),t(""),x(c)):r({preventDefault:()=>{}}))},C=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),w()),j.key==="@"&&f(!0)},N=v.useCallback(j=>{const I=Cft(j.nativeEvent);I.length>0&&(j.preventDefault(),I.forEach(async T=>{const F=await Z3(T);g(c,F)}))},[g,c]),k=v.useCallback(j=>{j.forEach(I=>{g(c,I)})},[g,c]),_=v.useCallback(j=>{j.forEach(I=>{g(c,I)})},[g,c]),E=v.useCallback(j=>{b(c,j)},[b,c]),D=v.useCallback(j=>{const I=`@${j}`;e.includes(I)&&t(e.replace(I,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(byt,{onFilesDropped:k,currentFileCount:y.length,disabled:s,className:"space-y-4",children:[l.jsx(XR,{mode:"display",assistantType:c,onEntityRemoved:j=>{const I="label"in j?j.label:j.name;D(I)},onEntitiesRemoved:j=>{let I=e;j.forEach(T=>{const F="label"in T?T.label:T.name;I=I.replace(`@${F}`,"")}),I!==e&&t(I.replace(/\s{2,}/g," ").trim())}}),y.length>0&&l.jsx(Rft,{files:y,onRemove:E,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-control border border-border/60 bg-background shadow-sm transition-colors focus-within:border-border focus-within:ring-1 focus-within:ring-ring/20",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:C,onPaste:N,onFocus:()=>{S(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 pb-1 pt-3 text-sm text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsx(XR,{mode:"trigger",assistantType:c,syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:j=>{var T;const I="label"in j?j.label:j.name;t(`${e}@${I} `),(T=h.current)==null||T.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(gyt,{onFilesSelected:_,disabled:s,currentFileCount:y.length})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[s&&l.jsx(m.Button,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:o,children:l.jsx(_me,{className:"size-3.5"})}),!s&&l.jsx(m.Button,{disabled:!e.trim()&&y.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",className:"h-8 w-8 rounded-full p-0",onClick:w,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(bF,{className:"size-3.5"})})]})]})]})]})});h$.displayName="ChatInputWithContext";function Rfe({assistantType:e,className:t}){const n=m.useMessageQueue(e),{removeFromQueue:r}=m.useQueueActions();return n.length===0?null:l.jsxs("div",{className:m.cn("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(fF,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:l.jsx(m.X,{className:"h-3 w-3"})})]})},s.id))})]})}function Ffe({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=m.useMessageQueue(e),{dequeueMessage:o}=m.useQueueActions();v.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Ayt(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function Ryt(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Ayt(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Pfe(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=v.useRef(null),a=v.useRef(null),[c,u]=v.useState(!0),[d,f]=v.useState(!0),[h,p]=v.useState(!1),[g,b]=v.useState(0),x=v.useRef(!0),y=v.useRef(!0),S=v.useRef(!1),w=v.useRef(!1),C=v.useRef(0),N=v.useRef({count:0,signature:"none"}),k=v.useCallback(()=>{if(i.current)return i.current;const R=a.current;if(!R)return null;const B=R.closest("[data-radix-scroll-area-viewport]");if(B)return i.current=B,B;const z=R.parentElement;return z?(i.current=z,z):null},[]),_=v.useCallback(()=>{const R=k();return R?R.scrollHeight-R.scrollTop-R.clientHeight:0},[k]),E=v.useCallback(()=>_()<=n,[_,n]),D=v.useCallback(R=>{x.current!==R&&(x.current=R,u(R))},[]),j=v.useCallback(R=>{y.current!==R&&(y.current=R,f(R))},[]),I=v.useCallback(()=>{p(R=>R&&!1),b(R=>R===0?R:0)},[]),T=v.useCallback((R={})=>{const B=k();if(!B)return;const{force:z=!1,instant:U=!1}=R;if(!z&&S.current)return;const Y=U||r==="auto"||r==="instant"?"auto":r;w.current=!0,Y==="smooth"&&"scrollTo"in B?B.scrollTo({top:B.scrollHeight,behavior:"smooth"}):B.scrollTop=B.scrollHeight,C.current=B.scrollTop,S.current=!1,D(!0),j(!0),I(),requestAnimationFrame(()=>{w.current=!1})},[r,I,k,D,j]),F=v.useCallback(()=>{b(0),p(!1)},[]),P=v.useCallback(()=>{const R=k();if(!R)return;const B=C.current,z=R.scrollTop,U=z-B;C.current=z;const Y=E();if(w.current){j(Y),Y&&(S.current=!1,D(!0));return}if(U<-1&&!Y){S.current=!0,D(!1),j(!1);return}if(Y){S.current=!1,D(!0),j(!0),I();return}j(!1),S.current&&D(!1)},[I,k,E,D,j]);return v.useEffect(()=>{const R=k();if(!e||e.length===0){N.current={count:0,signature:"none"},R&&(C.current=R.scrollTop),I();return}const B=e[e.length-1],z=Ryt(B),U=N.current,Y=e.length>U.count,O=z!==U.signature;N.current={count:e.length,signature:z};const K=o||s&&(B==null?void 0:B.role)==="assistant"&&O;if(!S.current){D(!0),R&&E()&&j(!0),(Y||O||K)&&T({force:!1,instant:K});return}if(Y){const q=e.length-U.count;q>0&&(p(!0),b(M=>M+q))}else O&&(p(!0),b(q=>q>0?q:1))},[I,o,s,k,E,e,T,D,j]),v.useEffect(()=>{T({force:!0,instant:!0})},[T]),v.useEffect(()=>{if(typeof ResizeObserver>"u")return;const R=a.current;if(!R)return;const B=new ResizeObserver(()=>{S.current||T({force:!1,instant:!0})});return B.observe(R),()=>{B.disconnect()}},[T]),v.useEffect(()=>()=>{w.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:g,scrollToBottom:T,handleScroll:P,resetNewMessageCount:F}}function Ofe(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=v.useState(r),a=v.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=v.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=v.useCallback(()=>{i(r)},[r]);return v.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const rW={"tool-getTableColumns":{"input-streaming":"Fetching table columns...","input-available":"Reading column definitions..."},"tool-getChartDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartDataFromCardConfig":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getForecastDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartSQLSyntax":{"input-streaming":"Generating SQL syntax...","input-available":"SQL syntax generated"},"tool-validateCardConfigFormat":{"input-streaming":"Validating card config format...","input-available":"Card config format validated"},"tool-generateQueryConfig":{"input-streaming":"Generating query config...","input-available":"Sending query config..."},"tool-generateDynamicVisual":{"input-streaming":"Planning dynamic visual...","input-available":"Generating dynamic visual..."},"tool-generateDynamicVisualFromData":{"input-streaming":"Planning dynamic visual...","input-available":"Building visual..."},"tool-askForMoreInfo":{"input-streaming":"Asking for more information...","input-available":"More information requested"},"tool-createChartFromSql":{"input-streaming":"Creating chart...","input-available":"Chart created"},"tool-getUserSql":{"input-streaming":"Getting SQL...","input-available":"SQL retrieved"},"tool-inspectTableData":{"input-streaming":"Inspecting table data...","input-available":"Analyzing data..."},"tool-getDomainRelationships":{"input-streaming":"Getting domain relationships...","input-available":"Analyzing data..."}};function Fyt(e,t){var r;if((r=rW[e])!=null&&r[t])return rW[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function Lfe(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:Fyt(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const Pyt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Oyt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=v.useState(!1),[a,c]=v.useState(m.isDevEnv),[u,d]=v.useState(!1),[f,h]=v.useState("auto"),[p,g]=v.useState(!1),[b,x]=v.useState(!1),y=n??b,{isLocalDev:S,isConsoleMode:w}=xg(),C=v.useRef(null);m.useDashboardStore(me=>me.dashboard.aiScopeTables),m.useDashboardStore(me=>me.isDashboardEditing);const N=m.useDashboardStore(me=>me.selectedSheetId),{setDataSource:k}=m.useEditorActions(),{setSelectedFrameId:_,setIsDashboardEditing:E}=m.useDashboardActions(),D=OL(),{setReasoningEffort:j,setShowReasoning:I,clearAssistantMessageContexts:T}=m.useAIActions(),{clearQueue:F}=m.useQueueActions(),{clearFileAttachments:P,getFileAttachments:R}=m.useFileActions(),B=m.useFileAttachments("dashboard"),z=m.useEditorStore(me=>me.card.dataSource),{assistantProfile:U}=jfe(),Y=m.useDashboardStore(me=>me.handleOpenAssistantProfile),{selectedEntities:O,applyDashboardDefaultEntities:K}=jj("dashboard"),{sendMessage:q,isLoading:M,messages:G,setMessages:L,status:$,stop:V,errorMessage:H,clearError:A}=myt({dynamicVisualMode:f}),W=v.useCallback(me=>{r==null||r(me),n===void 0&&x(me)},[n,r]),X=v.useCallback(()=>{W(!y)},[y,W]);v.useEffect(()=>{if(!y)return;function me(Ye){Ye.key==="Escape"&&W(!1)}return window.addEventListener("keydown",me),()=>{window.removeEventListener("keydown",me)}},[y,W]);const[Z,J]=v.useState(""),re=me=>{J(me.target.value)};async function fe({sql:me,cardTitle:Ye,connectionId:Ve,cardType:$e,python:Ae,cardConfig:Re,dataSource:He,customVisualPreferences:Ge,visualizationMode:ht,dynamicCardPreferences:lt}){if(!N)return;const st=ht==="dynamic",Fe=m.hasValidCardConfig(Re),Ke=Ve||(He==null?void 0:He.connectionId)||"",_t=He?{...He,connectionId:Ke||He.connectionId,connectionType:He.connectionType||"",mode:He.mode||"database",selectedEntities:He.selectedEntities||[]}:Ke?{connectionId:Ke,connectionType:"",mode:"database",selectedEntities:[]}:z0,Te=!Fe||!st||(lt==null?void 0:lt.provenance)!=="card-config",Ze=Te?me:"",at=Te?Ae:"",bt={id:m.v4(),title:Ye||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:$e==="horizontalBar"?"y":"x"},...st&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:$e,sql:Ze,python:at,dataSource:_t,config:Re,connectionId:Ke,visualizationMode:ht,dynamicCardPreferences:lt,customCardPreferences:Ge?{url:Ge.url,componentName:Ge.componentName,pluginChartType:Ge.pluginChartType,settings:Ge.settings,type:"component"}:void 0},ft={id:m.v4(),cards:[bt],activeCardId:bt.id};try{await D(N,ft,"end"),E(!0),_(ft.id)}catch(Et){console.error("Failed to add assistant visual to dashboard:",Et),ut.error(Et instanceof Error?Et.message:"Failed to prepare semantic metadata for the new visual")}}const de=me=>{me.preventDefault();const Ye=Z.trim();if(!Ye&&B.length===0)return;const Ve=[];Ye&&Ve.push({type:"text",text:Ye}),B.forEach($e=>{$e.data&&Ve.push({type:"file",mediaType:$e.type,filename:$e.name,url:`data:${$e.type};base64,${$e.data}`})}),q({role:"user",parts:Ve}),J(""),P("dashboard"),le({force:!0})};v.useEffect(()=>{var me;e&&((me=C.current)==null||me.focus())},[e]),Ffe({assistantType:"dashboard",status:$,isLoading:M,sendMessage:q});const{hasActiveTools:Se,activeToolText:ue}=Lfe(G),{visibleMessages:ve,hasMoreMessages:xe,totalMessageCount:ke,loadMoreMessages:se,resetMessageWindow:be}=Ofe(G,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Ce,contentRef:ge,isAtBottom:ee,hasNewMessages:te,newMessageCount:ce,scrollToBottom:le,handleScroll:Ee,resetNewMessageCount:ye}=Pfe(ve,{threshold:40,behavior:"smooth",isStreaming:M});function ne(me){const Ye={role:"user",parts:[{type:"text",text:me.title+" "+me.subtitle}]};q(Ye)}function je(me){q({role:"user",parts:[{type:"text",text:me}]})}function Ue(me){q({role:"user",parts:[{type:"text",text:me}]}),le({force:!0})}const Be=v.useCallback(async()=>{const me=JSON.stringify(G??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(me),ut.success("Conversation copied")}catch(Ye){console.error("Failed to copy conversation",Ye),ut.error("Unable to copy conversation")}},[G]),rt=(Z==null?void 0:Z.length)===0&&(G==null?void 0:G.filter(me=>me.role==="user").length)===0;function Xe(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function et(){return l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(Lh,{className:"size-3.5"})})}),l.jsxs(fo,{align:"end",children:[l.jsx(kc,{children:"Options"}),l.jsx(Ea,{}),l.jsx(bu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(bu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(bu,{checked:u,onCheckedChange:d,children:"System Message"}),(S||w)&&l.jsxs(l.Fragment,{children:[l.jsx(Ea,{}),l.jsx(kc,{children:"Dynamic Visuals"}),l.jsx(bu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(bu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(bu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const tt=l.jsxs("div",{"data-role":"dashboard-assistant",className:m.cn("flex h-full grow flex-col justify-between break-words px-6 py-4",y&&"rounded-card border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Xe(),Y&&l.jsx(m.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:Y,children:(U==null?void 0:U.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[w&&et(),a&&l.jsx(m.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Be,children:"Copy Conversation"}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:y?"Exit Fullscreen":"Expand",onClick:X,children:y?l.jsx(pF,{className:"size-4"}):l.jsx(_k,{className:"size-4"})}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const me=G.filter(Ye=>Ye.role==="assistant").map(Ye=>Ye.id).filter(Ye=>!!Ye);L([]),F("dashboard"),A(),T(me),be()},children:l.jsx(jk,{className:"size-4"})}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(m.X,{className:"size-4"})})]})]}),l.jsxs(zl,{"data-role":"dashboard-assistant-scroll-area",ref:Ce,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:Ee,children:[l.jsxs("div",{ref:ge,className:"min-w-0 space-y-3 pb-4",children:[xe&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(m.Button,{variant:"outline",size:"sm",onClick:se,className:"text-xs",children:["Load ",Math.min(5,ke-ve.length)," ","more messages (",ke-ve.length," ","hidden)"]})}),l.jsx(cde,{showTools:a,showSystemMessage:u,messages:ve,onAddToDashboard:fe,onQuickReply:Ue,disableQuickReplies:M}),l.jsx(lde,{status:$,errorMessage:H,activeToolText:M&&Se?ue:void 0})]}),l.jsx(m.ScrollBar,{orientation:"horizontal"})]}),e&&!ee&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(m.Button,{onClick:()=>{le({force:!0}),ye()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(m.ChevronDown,{className:"h-4 w-4"}),te&&ce>0&&l.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:ce>9?"9+":ce})]})}),l.jsxs("div",{className:"space-y-3",children:[!U&&rt&&l.jsx(ude,{onClick:ne,placeholders:Pyt}),l.jsx("div",{children:rt&&U&&l.jsx(Efe,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:je})}),l.jsx(Rfe,{assistantType:"dashboard",className:"mb-3"}),l.jsx(h$,{ref:C,setInput:J,stop:V,input:Z,handleInputChange:re,handleSubmit:me=>{de(me),le({force:!0})},isLoading:M,status:$,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(f$,{incomingSelectedEntities:O,open:p,onOpenChange:g,dataSource:z||z0,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:me=>K()})]});return y&&s?Sr.createPortal(l.jsx(sb,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:l.jsx("div",{className:"flex h-full w-full",children:tt})}),s):tt}function Lyt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=m.useDashboardActions(),s=Iie(),o=m.useDashboardStore(d=>d.dashboard.sheets),a=m.useDashboardStore(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=m.useDashboardStore(d=>d.isDashboardEditing),u=m.useDashboardStore(d=>d.isVisualEditing);v.useEffect(()=>{if(!c||u)return;async function d(p){if($yt(p.target))return;const g=p.ctrlKey||p.metaKey;g&&p.key==="c"?(await f(),ut.success("Card copied to clipboard"),p.preventDefault()):g&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText(),g=zyt(p);if(g!=null&&g.id){const b=jie(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await s(a,b),r(b.id),ut.success("Card pasted from clipboard")}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[s,n,r,a,c,u,t])}function $yt(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.closest("[contenteditable]");return t&&t.getAttribute("contenteditable")!=="false"?!0:!!e.closest('input, textarea, select, [role="textbox"]')}function zyt(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.id=="string"&&Array.isArray(t.cards)?t:null}catch{return null}}function Byt(e,t){switch(e.interactionMode){case"drillToDetail":Vyt(e,t);break;case"drillThrough":Hyt(e,t);break;case"drillToURL":Uyt(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function Vyt(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function Hyt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Uyt(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function Wyt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(na,{children:[l.jsx(go,{children:i||"Insight Detail"}),l.jsx(si,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(Aie,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(Gie,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function qyt(){const e=m.useInteractionStore(C=>C.interactionStates),t=m.useInteractionStore(C=>C.setInteractionState),n=m.useInteractionStore(C=>C.clearLastInteractionEvent),r=m.useInteractionStore(C=>C.replaceCardWithInsight),s=m.useInteractionStore(C=>C.setPendingDrillThrough),o=m.useInteractionStore(C=>C.pendingDrillThrough),i=m.useInteractionStore(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=m.useDashboardActions(),{selectDashboard:u}=Ph(),d=m.useDashboardStore(C=>C.dashboard),f=m.useDashboardStore(C=>C.filterValues),{data:h,isLoading:p}=LY((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[g,b]=v.useState({open:!1,insightId:""}),x=Kie(g.insightId,{enabled:g.open&&!!g.insightId}),y=v.useRef(new Set),S=v.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:N,contextMode:k})=>{b({open:!0,insightId:C,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:k})},replaceCardContent:({cardId:C,insightId:N,filters:k,contextMode:_})=>{r(C,N,k,_)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:E})=>{const D={filters:C},j={sourceCardId:m.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[D]},I={...m.createInitialInteractionState(),appliedClickFilters:[j],contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:E};t(m.DRILL_CONTEXT_CARD_ID,I)}}),[a,r,f,c,d,s,t]);v.useEffect(()=>{Object.entries(e).forEach(([C,N])=>{if(N!=null&&N.lastInteractionEvent){const k=N.lastInteractionEvent,_=`${C}-${k.interactionMode}-${k.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{Byt(k,S)}catch(E){console.error("Error executing interaction event:",E)}finally{n(C),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,S]),v.useEffect(()=>{if(!(!o||!h||p))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,p,u,c,i]);const w=()=>{b({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Wyt,{open:g.open,onOpenChange:w,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&p&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[l.jsx(m.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Yyt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=Gyt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function Gyt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function Kyt(e){return e?`Back to ${e}`:"Back"}function Zyt(){var y,S,w,C,N;const e=m.useInteractionStore(k=>k.interactionStates[m.DRILL_CONTEXT_CARD_ID]),t=m.useDashboardStore(k=>k.actions.goBackFromDrill),n=m.useDashboardStore(k=>k.actions.clearDrillContext),{selectDashboard:r}=Ph(),[s,o]=v.useState({x:16,y:16}),[i,a]=v.useState(!1),c=v.useRef({x:0,y:0});v.useEffect(()=>{if(!i)return;const k=E=>{o({x:E.clientX-c.current.x,y:E.clientY-c.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",k),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",k),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(w=(S=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:S.filterGroups)==null?void 0:w[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(k){console.error("[DrillBack] Error during back navigation:",k)}},g=()=>{n()},b=k=>{k.target.closest("button")||(a(!0),c.current={x:k.clientX-s.x,y:k.clientY-s.y})};Yyt(f);const x=Kyt(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:b,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((k,_)=>{const E=k.field.label||k.field.name,D=String(k.value);return l.jsxs(Yr,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",D]},_)})})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(m.Button,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(ev,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Xyt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Qyt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:p,transition:g,isDragging:b}=db({id:`filter:${e.id}`,disabled:n||!t}),x={transform:_i.Translate.toString(p),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return l.jsx("div",{ref:h,style:x,...d,children:l.jsx(bL,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u})})}const sW="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Jyt=[];function $fe({open:e,onOpenChange:t}){var L,$,V;const[n,r]=v.useState(!1),[s,o]=v.useState(!1),[i,a]=v.useState({sheetSelection:"current",protectPdf:!1,password:""}),c=m.useDashboardStore(H=>{var A;return(A=H.dashboard)==null?void 0:A.sheets}),u=m.useDashboardStore(H=>H.dashboard),d=m.useDashboardStore(H=>H.dashboardInputValues),f=m.useDashboardStore(H=>H.filterValues),h=m.useDashboardStore(H=>H.controlValues),p=m.useDashboardStore(H=>H.inlineFilterValuesMap),g=m.useDashboardStore(H=>H.cardControlValuesMap),b=m.useDashboardStore(H=>H.selectedSheetId),x=m.useDashboardStore(H=>H.selectedSheetId?H.documentInputRuntimeBySheetId[H.selectedSheetId]:void 0),y=m.useDashboardStore(H=>H.isDownloadingPdf),{authToken:S,tokenProps:w}=Ct(),C=c==null?void 0:c.find(H=>H.id===b),N=v.useMemo(()=>m.getDashboardExportSheets(c),[c]),k=m.isDocumentSheet(C),_=k&&C?C.document:void 0,E=v.useMemo(()=>k&&C?dw(u,C.id):[],[C,k,u]),D=E.length>0,j=v.useMemo(()=>k&&C?Tce(u,C.id):!1,[C,k,u]),I=v.useMemo(()=>D?E.map(fw):(_==null?void 0:_.inputs)||Jyt,[_,E,D]),T=(($=(L=w==null?void 0:w.params)==null?void 0:L.calendarContext)==null?void 0:$.tz)||((V=w==null?void 0:w.params)==null?void 0:V.timezone)||(typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),F=v.useMemo(()=>Tle(I),[I]),P=v.useMemo(()=>Dle(I,T),[I,T]),R=v.useMemo(()=>Ile(I),[I]),B=x?x.filterValuesByInputId:P,z=x?x.controlValuesByInputId:R,U=v.useMemo(()=>k?j&&C&&_?VZ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(H=>H.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},timezone:T}):Rle(I,B,z,F,F):[],[_,I,C,k,u,g,h,f,p,d,z,B,F,T,j]),Y=!!C,O=N.length>0,K=((c==null?void 0:c.length)||0)>1||k,q=i.sheetSelection==="current"&&(!Y||k&&U.length>0)||i.sheetSelection==="all"&&!O;v.useEffect(()=>{e&&i.sheetSelection==="all"&&!O&&a(H=>({...H,sheetSelection:"current"}))},[O,e,i.sheetSelection]);const M=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function G(){if(y){ut.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){ut.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!Y){ut.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!O){ut.error("No dashboard sheets are available to export");return}o(!0);const H=i.sheetSelection==="current"&&k,A=H?i.protectPdf?"Generating protected document PDF... may take up to 60 seconds":"Generating document PDF... may take up to 60 seconds":i.sheetSelection==="all"?"Generating PDF for all dashboard sheets... This may take a while.":i.protectPdf?"Generating protected PDF... may take up to 60 seconds":"Generating PDF... may take up to 60 seconds",W=ut.loading(A);try{if(H){if(!_||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){ut.dismiss(W),ut.error(`Set ${U.join(", ")} before exporting`);return}const Z=new Date().toISOString(),J=j?UZ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(re=>re.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},generatedAt:Z,timezone:T}).snapshot:void 0;await PP(w.apiServiceUrl,S,{sheetId:C.id,title:C.title||"Document",pageSize:_.page.size,orientation:_.page.orientation,timezone:T,password:i.protectPdf?i.password:void 0,inputSnapshot:J,...J?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:B,controlValuesByInputId:z,generatedAt:Z}}})}else{const Z=xee();await XZ(w.apiServiceUrl,S,i.protectPdf?i.password:void 0,i.sheetSelection,Z)}ut.dismiss(W);const X=H?i.protectPdf?"Protected document PDF downloaded successfully!":"Document PDF downloaded successfully!":i.sheetSelection==="all"?"Dashboard sheets PDF downloaded successfully!":i.protectPdf?"Protected PDF downloaded successfully!":"PDF downloaded successfully!";ut.success(X,{duration:2e3}),M()}catch(X){ut.dismiss(W),ut.error("Failed to download PDF",{description:m_(X,"Please try again or contact support."),descriptionClassName:p_,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",X)}finally{o(!1)}}return l.jsx(Oo,{open:e,onOpenChange:H=>{if(!H){M();return}t(!0)},children:l.jsxs(mo,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[l.jsxs(na,{children:[l.jsx(go,{className:"text-[15px]",children:k?"Export document":"Export dashboard"}),l.jsx(si,{className:"text-[13px] leading-5",children:k?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),l.jsxs("div",{className:"space-y-4 py-1",children:[K&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:sW,children:"Export scope"}),l.jsxs(Ia,{value:i.sheetSelection,onValueChange:H=>a({...i,sheetSelection:H}),className:"gap-1.5",children:[l.jsxs(m.Label,{htmlFor:"scope-current",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!Y&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(js,{value:"current",id:"scope-current",disabled:!Y}),k?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),l.jsxs(m.Label,{htmlFor:"scope-all",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!O&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(js,{value:"all",id:"scope-all",disabled:!O}),"Dashboard sheets (",N.length," ",N.length===1?"sheet":"sheets",")"]})]}),k&&l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:U.length>0?`Set ${U.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),l.jsx(m.Separator,{className:"bg-border/60"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs(m.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[l.jsx(Ln,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:H=>{a({...i,protectPdf:H,password:H?i.password:""}),H||r(!1)}}),l.jsx(kk,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&l.jsxs("div",{className:"ml-6 space-y-1.5",children:[l.jsx(m.Label,{htmlFor:"pdf-password",className:sW,children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(m.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:H=>a({...i,password:H.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:H=>{H.key==="Enter"&&i.password&&G()}}),l.jsx("button",{type:"button",className:"absolute right-1 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>r(!n),"aria-label":n?"Hide password":"Show password",children:n?l.jsx(Nk,{className:"h-3.5 w-3.5"}):l.jsx(tv,{className:"h-3.5 w-3.5"})})]}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),l.jsxs(Gc,{children:[l.jsx(m.Button,{variant:"outline",size:"xs",onClick:M,disabled:s,children:"Cancel"}),l.jsx(m.Button,{size:"xs",onClick:G,disabled:s||y||q,children:s?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):l.jsxs(l.Fragment,{children:[l.jsx(qc,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function zfe({iconClassName:e,open:t,onOpenChange:n}){const[r,s]=v.useState(!1),o=t!==void 0,i=o?t:r,a=u=>{o||s(u),n==null||n(u)},c=m.useDashboardStore(u=>u.isDownloadingPdf);return l.jsxs(l.Fragment,{children:[o?null:l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:c,onClick:()=>a(!0),children:l.jsx(qc,{className:m.cn("size-4",e)})}),l.jsx($fe,{open:i,onOpenChange:a})]})}function oW(e,t,n){const r=new Set(t),s=[...n];return e.map(o=>r.has(o.id)?s.shift()??o.id:o.id)}function e0t({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:c,isDragging:u}=db({id:`control:${e.id}`,disabled:!n}),d={transform:_i.Translate.toString(a),transition:c,opacity:u?.5:1,zIndex:u?10:void 0};return l.jsx("div",{ref:i,style:d,...s,children:l.jsx(Gle,{control:e,value:t,isEditing:n,dragListeners:n?o:void 0,onChange:r})})}function iW(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function aW(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function t0t(e,t,n){const r=new Set([...t.map(a=>`filter:${a.id}`),...n.map(a=>`control:${a.id}`)]);if(!(e!=null&&e.length))return aW(t,n);const s=e.filter(a=>r.has(a)),o=new Set(s),i=aW(t,n).filter(a=>!o.has(a));return[...s,...i]}function n0t(e,t){return m.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function r0t(e){return zm(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>zm(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function lW(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function s0t(e){const t={sheetId:e.selectedSheetId},n=m.getDashboardInputRuntimeSlot(e.dashboardInputValues,e.dashboardInput,t);if(n)return n;const r=m.getDashboardInputRuntimeSlot(e.defaultInputValues,e.dashboardInput,t);return r||m.getBackingDefaultSlot(e.dashboardInput)}function o0t(e){return Bfe(e).filter(t=>{var n,r;return t.filter.hide||t.filter.location==="frame"?!1:((n=t.compatibility)==null?void 0:n.source)==="dashboardFilter"?!0:(((r=t.presentation)==null?void 0:r.placement)||"toolbar")==="toolbar"})}function Bfe(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=n0t(e.dashboard,t);return lZ(a_({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!r0t({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function i0t(e,t){return"toolbar"}function a0t(){const e=Zc("interactive"),t=m.useDashboardStore($=>$.selectedSheetId),n=m.useDashboardStore($=>$.dashboard.filters),r=m.useDashboardStore($=>$.dashboard.filterLayout),s=m.useDashboardStore($=>$.isDashboardEditing),o=m.useDashboardStore($=>$.controlValues),i=m.useDashboardStore($=>$.filterValues);m.useDashboardStore($=>$.filteringCards);const a=m.useDashboardStore($=>$.inlineFilterValuesMap),c=m.useDashboardStore($=>$.dashboardInputValues),u=m.useInteractionStore($=>$.clearAllClickFilters),d=m.useInteractionStore($=>Object.entries($.interactionStates).reduce((V,[H,A])=>{var W;return H===m.DRILL_CONTEXT_CARD_ID?V:V+(((W=A.appliedClickFilters)==null?void 0:W.length)??0)},0)),f=m.useDashboardStore($=>$.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:p,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:S,setFilteringCards:w,upsertDashboardInput:C}=m.useDashboardActions(),N=Tj(cg(cb,{activationConstraint:{distance:5}})),k=m.useDashboardStore($=>$.dashboard),_=o0t({dashboard:k,selectedSheetId:t}).filter($=>i0t($.filter)==="toolbar"),E=Bfe({dashboard:k,selectedSheetId:t}),D=_.map($=>$.filter),j=new Map(_.map($=>[`filter:${$.filter.id}`,$])),I=wKe(k),T=I.filter($=>!$.hidden&&C0($)==="toolbar"),F=I.filter($=>!$.hidden&&C0($)==="advanced"),P=t0t(r==null?void 0:r.toolbarItemOrder,D,T),R=new Map(D.map($=>[`filter:${$.id}`,$])),B=new Map(T.map($=>[`control:${$.id}`,$]));function z($){const{active:V,over:H}=$;if(!H||V.id===H.id)return;const A=String(V.id),W=String(H.id),X=P.findIndex(ve=>ve===A),Z=P.findIndex(ve=>ve===W);if(X===-1||Z===-1)return;const J=ub(P,X,Z);y({toolbarItemOrder:J});const re=new Set((n||[]).map(ve=>ve.id)),fe=P.filter(ve=>ve.startsWith("filter:")).map(ve=>ve.replace("filter:","")).filter(ve=>re.has(ve)),de=J.filter(ve=>ve.startsWith("filter:")).map(ve=>ve.replace("filter:","")).filter(ve=>re.has(ve)),Se=P.filter(ve=>ve.startsWith("control:")).map(ve=>ve.replace("control:","")),ue=J.filter(ve=>ve.startsWith("control:")).map(ve=>ve.replace("control:",""));h(oW(n||[],fe,de)),g(oW(k.controls||[],Se,ue))}const U=(r==null?void 0:r.toolbarWrap)??!1,Y=(r==null?void 0:r.showDownloadButton)??!1,O=(i==null?void 0:i.filter($=>iW($)).length)??0,K=E.filter(lW),q=K.filter($=>{const V=s0t({dashboardInput:$,dashboardInputValues:c,defaultInputValues:k.defaultInputValues,selectedSheetId:t});return(V==null?void 0:V.status)==="set"&&V.value.kind==="filter"&&iW(V.value.filterValue)}).length,M=a?Object.values(a).reduce(($,V)=>$+((V==null?void 0:V.length)??0),0):0,G=O+q+M+d,L=()=>{S([]),K.forEach($=>{p($,{sheetId:t})}),w([]),u(),a&&Object.entries(a).forEach(([$,V])=>{V==null||V.forEach(H=>{f($,H.filterId)})})};return!D.length&&!T.length&&!F.length&&!Y&&G===0?null:l.jsx("div",{className:"z-20 border-b border-border/60 bg-background/95 px-3 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/85",style:e.containerStyle,role:"toolbar","aria-label":"Dashboard filters and controls",children:l.jsx(ow,{sensors:N,collisionDetection:nw,onDragEnd:z,children:l.jsxs("div",{className:m.cn("flex items-center",U?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[l.jsx(iw,{items:P,strategy:qL,children:l.jsx(NR,{className:"gap-3 pr-0",wrap:U,children:P.map($=>{const V=R.get($);if(V){const A=j.get($),W=A&&lW(A);return l.jsx(Qyt,{filter:V,isEditing:s,storageOptions:W?{storageTarget:"dashboardInput",dashboardInput:A,sheetId:t??void 0}:void 0,inputVariableName:W?A.variableName:void 0,onUpdateFilter:W?(X,Z)=>{C({...A,variableName:(Z==null?void 0:Z.variableName)||A.variableName,filter:X})}:void 0,onRemoveFilter:W?()=>{S((i||[]).filter(X=>X.filterId!==V.id)),b(A.id)}:void 0},$)}const H=B.get($);return H?l.jsx(e0t,{control:H,value:o==null?void 0:o[H.id],isEditing:s,onChange:A=>x(H.id,A)},$):null})})}),F.length>0&&l.jsx(Hie,{title:"",controls:F,values:o,onChange:($,V)=>x($.id,V),immediatePlacement:"toolbar",advancedLabel:"More controls"}),G>0&&l.jsxs("button",{type:"button",onClick:L,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(m.X,{className:"h-3 w-3"}),"Clear all",l.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:G})]}),Y&&l.jsx("div",{className:m.cn(G>0?"ml-1.5":"ml-auto"),children:l.jsx(zfe,{})})]})})})}function Vfe(){var te,ce;const{showAssistant:e,tokenProps:t,renderMode:n}=Ct(),r=Xyt((te=t.config)==null?void 0:te.showDashboardAssistant,e),{preferences:s,isConsoleMode:o}=xg(),i=(ce=s==null?void 0:s.cardDisplay)==null?void 0:ce.mode,a=Wh(i),c=_Z({displayMode:i,renderMode:n}),u=v.useRef(null),d=v.useRef(null),[f,h]=v.useState(!1),{handleDragStart:p,isDraggingRef:g,getStyle:b,getPositionClasses:x}=Sot({initialPosition:"bottom-right"}),y=Hf(le=>le.setFullscreen),S=Hf(le=>le.setPanelOpen),w=Hf(le=>le.setContainer),C=mK("dashboard"),N=gK(),k=bK("dashboard"),_=C.isOpen,E=N==="dashboard",D=m.useDashboardStore(le=>le.isVisualEditing),j=m.useDashboardStore(le=>le.themeStyle),I=Rl(),T=m.useDashboardStore(le=>{var Ee;return(Ee=le.dashboard)==null?void 0:Ee.sheets}),F=m.useDashboardStore(le=>le.showFilters),P=m.useDashboardStore(le=>le.isDashboardEditing),R=m.useDashboardStore(le=>le.selectedSheetId),B=T==null?void 0:T.find(le=>le.id===R),z=m.useDashboardStore(le=>{var Ee,ye,ne;return(ne=(ye=(Ee=le.dashboard)==null?void 0:Ee.sheets)==null?void 0:ye.find(je=>je.id===le.selectedSheetId))==null?void 0:ne.kind}),U=m.useDashboardStore(le=>{var Ee,ye;return((ye=(Ee=le.dashboard)==null?void 0:Ee.summary)==null?void 0:ye.position)||"top"}),Y=z==="document",O=m.useDashboardStore(le=>{var Ee;return(Ee=le.dashboard)==null?void 0:Ee.id}),K=m.useDashboardStore(le=>le.isDashboardPanelOpen),q=m.useDashboardStore(le=>le.actions.setIsDashboardPanelOpen),{getDefaultSheetId:M,setDefaultSheetId:G,clearDefaultSheetId:L}=YW(O),[$,V]=v.useState(null);Rk(Xr.DASHBOARD);const{setSelectedSheetId:H,setSheetTitle:A,addSheet:W,setSheets:X}=m.useDashboardActions();Lyt(d);const{setActiveAssistantType:Z}=m.useAIActions();v.useEffect(()=>{if(O){const le=M();V(le)}},[O,M]),v.useEffect(()=>{_?Z("dashboard"):N==="dashboard"&&y(null)},[_,Z,N,y]),v.useEffect(()=>{var le;_||(le=u.current)==null||le.resize(0)},[_]);function J(le){var Ee,ye;le?((Ee=u.current)==null||Ee.resize(40),S("dashboard",!0),y("dashboard"),Z("dashboard")):(S("dashboard",!1),y(null),(ye=u.current)==null||ye.resize(0),Z(null))}function re(le="dashboard"){const Ee={id:m.v4(),title:le==="document"?"New Document":"New Sheet",...le==="document"?{kind:le,document:m.createDefaultDocumentDefinition()}:{}};W(Ee),H(Ee.id)}function fe(le,Ee){if(!O)return;$===le?(L(),V(null),ut.success("Default sheet cleared")):(G(le),V(le),ut.success(`"${Ee}" set as default sheet`))}function de(le){var Ee;le<1?(S("dashboard",!1),y(null),Z(null),(Ee=u.current)==null||Ee.resize(0)):(_||S("dashboard",!0),Z("dashboard"))}function Se(){return(j==null?void 0:j.canvasTheme)==="muted"||!(j!=null&&j.canvasTheme)?"hsl(var(--semaphor-muted))":(j==null?void 0:j.canvasTheme)==="clear"?"":j==null?void 0:j.canvasTheme}const ue=(le,Ee)=>{le.dataTransfer.setData("tabIndex",Ee.toString())},ve=le=>{le.preventDefault()},xe=(le,Ee)=>{const ye=le.dataTransfer.getData("tabIndex");if(ye===Ee.toString())return;const ne=Array.from(T||[]),[je]=ne.splice(parseInt(ye),1);ne.splice(Ee,0,je),X(ne)},ke=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,se=r===!0&&!a&&!_&&!D&&!F;function be(){if(T&&T.length>1||P)return l.jsxs("div",{className:"relative flex w-full items-stretch border-b border-border",children:[o&&ke&&!K&&l.jsx("button",{type:"button","aria-label":"Toggle dashboards panel",onClick:()=>{q(!K)},className:"group/panel mx-2 inline-flex h-9 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",children:l.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-[4px] group-hover/panel:bg-muted",children:l.jsx(mF,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),l.jsxs("div",{className:"relative min-w-0 flex-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-4 bg-gradient-to-r from-background to-transparent"}),l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-4 bg-gradient-to-l from-background to-transparent"}),l.jsxs(m.TabsList,{role:"tab-list",className:"flex w-0 min-w-full items-stretch justify-start overflow-x-auto rounded-none bg-transparent p-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[T==null?void 0:T.map((le,Ee)=>{const ye=R===le.id,ne=$===le.id;return l.jsxs(m.TabsTrigger,{draggable:!0,onDragStart:je=>ue(je,Ee),onDragOver:ve,onDrop:je=>xe(je,Ee),onClick:()=>H(le.id),className:m.cn("group relative inline-flex h-9 shrink-0 items-center gap-1.5 rounded-none bg-transparent px-3 py-0 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-transparent hover:text-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none","after:pointer-events-none after:absolute after:inset-x-2 after:-bottom-px after:h-0.5 after:bg-transparent data-[state=active]:after:bg-foreground"),value:le.id,children:[le.kind==="document"&&l.jsx(vi,{className:"h-3 w-3 text-muted-foreground"}),l.jsx(ON,{enabled:P&&ye,text:le.title,onSave:je=>A(le.id,je),children:le.title},le.id),l.jsx("span",{role:"button",tabIndex:0,"aria-label":ne?"Clear default sheet":"Set as default sheet",title:ne?"Clear default sheet":"Set as default sheet",onClick:je=>{je.stopPropagation(),fe(le.id,le.title||"Sheet")},onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(je.preventDefault(),je.stopPropagation(),fe(le.id,le.title||"Sheet"))},className:m.cn("inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] transition-opacity hover:bg-muted focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",ye||ne?"opacity-100":"opacity-0 group-hover:opacity-100"),children:l.jsx(yF,{className:m.cn("h-3 w-3 transition-colors",ne?"fill-current text-amber-500":"text-muted-foreground")})}),P&&ye&&T.length>1&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Delete sheet",className:"inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",onClick:je=>{je.stopPropagation(),h(!0)},onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(je.preventDefault(),je.stopPropagation(),h(!0))},children:l.jsx(m.X,{className:"h-3 w-3"})})]},le.id)}),P&&l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add sheet",className:"ml-1 inline-flex h-9 shrink-0 items-center gap-1 px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(dr,{className:"h-3 w-3"}),"Sheet"]})}),l.jsxs(fo,{align:"start",className:"w-48",children:[l.jsxs(jn,{onSelect:()=>re("dashboard"),children:[l.jsx(Rm,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),l.jsxs(jn,{onSelect:()=>re("document"),children:[l.jsx(vi,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})]})}function Ce(){return l.jsx("div",{ref:d,style:{},className:"h-full min-h-0 grow",children:T==null?void 0:T.map(le=>l.jsx(m.TabsContent,{style:{backgroundColor:Se(),...I.dashboardCanvasStyle},className:m.cn("mt-0 h-full min-h-0",{}),value:le.id,children:l.jsx(xH,{sheet:le})},le.id))})}function ge(){return l.jsxs(m.Tabs,{"data-role":"dashboard-tabs-container",className:m.cn("relative flex h-full flex-col",j==null?void 0:j.dashboardTabsContainer),onValueChange:le=>{H(le)},value:R||void 0,children:[be(),U==="top"&&!Y&&l.jsx(sR,{}),R&&!Y&&l.jsx(a0t,{}),Y?l.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:Ce()}):l.jsx(zl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:Ce()}),U==="bottom"&&!Y&&l.jsx(sR,{}),l.jsx(Cot,{open:f,setOpen:h})]})}const ee=v.useCallback(le=>{w("dashboard",le)},[w]);return T?c&&R&&!Y?l.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',R,'" was not found or is not a document sheet in the loaded dashboard.']}):c&&Y&&B?l.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:l.jsx(xH,{sheet:B})}):l.jsxs(l.Fragment,{children:[l.jsx(qyt,{}),l.jsx(Zyt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(UF,{className:m.cn("flex-1 basis-0 overflow-y-auto transition-opacity",E&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(Ry,{children:ge()}),r===!0&&l.jsxs(l.Fragment,{children:[l.jsx(wot,{open:_,onTabClick:J,withHandle:!0,disabled:!_}),l.jsx(Ry,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:de,defaultSize:_?40:0,ref:u,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Oyt,{open:_,setOpen:J,isFullscreen:E,onFullscreenChange:le=>y(le?"dashboard":null),fullscreenContainer:k})})})]})]}),l.jsx("div",{ref:ee,className:m.cn("absolute inset-0",!E&&"pointer-events-none")}),se&&l.jsx("div",{className:m.cn("absolute z-50 transition-all duration-300 ease-in-out",x().horizontal,x().vertical),style:b(),children:l.jsx(m.Button,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{g.current||J(!0)},onMouseDown:p,onTouchStart:p,title:"Open Assistant (drag to move)",children:l.jsx(vme,{className:"h-5 w-5"})})})]})]}):null}const Hfe=v.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:s,children:o,className:i,style:a,...c},u)=>{const d=v.useId(),f=v.useMemo(()=>l0t(d),[d]),{theme:h}=nF(),p=c0t(h),g=v.useMemo(()=>s??Wc.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,s,n]),b=v.useMemo(()=>m.compileAppearance({spec:g,systemMode:p}),[g,p]),x=v.useMemo(()=>m.createAppearanceContextValue(f,b),[b,f]);return l.jsx(m.AppearanceContext.Provider,{value:x,children:l.jsx(sb,{...c,ref:u,className:i,style:a,children:o})})});Hfe.displayName="AppearanceProvider";function l0t(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function c0t(e){const t=hC(e),[n,r]=v.useState(()=>u0t());return v.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const s=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!s)return;const o=()=>{r(s.matches?"dark":"light")};return o(),typeof s.addEventListener=="function"?(s.addEventListener("change",o),()=>s.removeEventListener("change",o)):((a=s.addListener)==null||a.call(s,o),()=>{var c;return(c=s.removeListener)==null?void 0:c.call(s,o)})},[t]),t==="system"?n:t}function u0t(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const Ufe=v.createContext({openBrandStudioPreview:()=>{}}),d0t=Ufe.Provider;function f0t(){return v.useContext(Ufe)}function h0t({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const s=hC(t),[o,i]=v.useState(()=>p0t(n)||s),a=v.useCallback(u=>{const d=hC(u);m0t(n,d),i(d)},[n]),c=v.useMemo(()=>({theme:o,setTheme:a}),[o,a]);return l.jsx(kW.Provider,{...r,value:c,children:e})}function p0t(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=hC(t,"system");return n===t?n:null}catch{return null}}function m0t(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const g0t=v.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function p$({appearance:e,children:t}){var I,T;const{authToken:n,id:r,tokenProps:s}=Ct(),o=Q0(),i=(I=o.data)==null?void 0:I.organizationAppearance,a=(T=s.config)==null?void 0:T.appearance,[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,p]=v.useState(null),[g,b]=v.useState(null),[x,y]=v.useState(null),S=`${s.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,w=On({queryKey:AY({resourceType:Xr.DASHBOARD,apiServiceUrl:s.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>m.getRequest(`${s.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:F=>(F==null?void 0:F.organizationAppearance)??null,enabled:!o.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});v.useEffect(()=>{i!==void 0&&y({scopeKey:S,appearance:i})},[i,S]),v.useEffect(()=>{w.data!==void 0&&y({scopeKey:S,appearance:w.data})},[w.data,S]);const C=(x==null?void 0:x.scopeKey)===S?x.appearance:null,N=i!==void 0?i:w.data!==void 0?w.data:C,k=v.useMemo(()=>Wc.resolveAppearance({organizationAppearance:N,tokenAppearance:a,reactAppearance:e}),[e,N,a]),_=v.useCallback(()=>{f(g??h??k),u(!0)},[g,h,k]),E=v.useCallback(()=>{u(!1)},[]);v.useEffect(()=>{f(null),p(null),b(null),u(!1)},[r]);const D=v.useMemo(()=>({openBrandStudioPreview:_}),[_]),j=g??h??e;return l.jsx(h0t,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(d0t,{value:D,children:l.jsx(Hfe,{organizationAppearance:N,tokenAppearance:a,reactAppearance:j,style:{height:"100%",width:"100%"},children:l.jsxs(m.TooltipProvider,{delayDuration:0,children:[t,c&&l.jsx("aside",{"aria-label":"Brand Studio","aria-modal":"false",role:"dialog",className:"fixed bottom-0 right-0 top-0 z-50 flex w-[min(520px,100vw)] flex-col border-l border-border bg-background text-foreground shadow-sm",children:l.jsx(v.Suspense,{fallback:l.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:l.jsx(g0t,{appearance:d,onDraftChange:b,onSave:F=>{p(F),b(F),f(F)},onCancel:E})})})]})})})})}function Wfe({children:e,preferences:t}){const{currentUser:n}=ta(),r=v.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(IY.Provider,{value:r,children:l.jsx(kj,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function b0t(e=2e3,t=500){const n=Ipe(),[r,s]=v.useState(!1),[o,i]=v.useState(!1),a=v.useRef(null);return v.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),v.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function m$({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=b0t(e,t);return v.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function qfe(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Aa,{FallbackComponent:Cj,children:l.jsxs(lF,{dashboardProps:e,children:[l.jsx(m$,{componentType:"dashboard",componentId:e.id}),l.jsx(p$,{appearance:e.appearance,children:l.jsx(Wfe,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(YF,{...e,type:"dashboard",children:l.jsx(Vfe,{})})})})})]})})}function x0t(e=[]){const t=v.useRef(null),n=v.useRef(null),r=v.useRef(null),[s,o]=v.useState(),i=v.useCallback(()=>{var p,g,b;const a=((p=t.current)==null?void 0:p.clientWidth)??0,c=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);o(x=>x===h?x:h)},[]);return v.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function y0t({filter:e}){var g;const t=m.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=xg(),r=Wh((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),s=m.useDashboardStore(b=>b.filterValues),o=s==null?void 0:s.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=m.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:p}=x0t([t,o,r]);return v.useEffect(()=>{p()},[e.title,p]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(m.Label,{className:"my-1 block w-full text-sm",children:l.jsx(Zi,{value:e.title||e.column,onSave:b=>c({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(gL,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(m.X,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function v0t(){const e=m.useDashboardStore(r=>r.dashboard.filters),t=m.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:m.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(y0t,{filter:r}),l.jsx(gj,{filter:r})]},r.id))}):null}function w0t(){var i;const e=m.useDashboardStore(a=>a.dashboard),t=m.useDashboardStore(a=>a.selectedSheetId),n=m.useDashboardStore(a=>a.isVisualEditing),r=m.useDashboardStore(a=>a.isDashboardEditing),s=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),o=m.isDocumentSheet(s);return l.jsx("div",{role:"dashboard-plus-main",className:m.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:l.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!o&&l.jsx(v0t,{}),l.jsx(Vfe,{})]})})}const S0t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-By7aKmDj.js"))),C0t=v.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BuXlHmJH.js"))),N0t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BOyLuhS6.js"))),k0t=v.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-ByR-FD3h.js")).then(e=>({default:e.ResourceManagementPanel})));function _0t({showControls:e=!1,showFooter:t=!0,...n}){const r=m.useDashboardStore(u=>u.isDashboardPanelOpen),s=m.useDashboardStore(u=>u.isVisualEditing),o=m.useDashboardStore(u=>u.showDashboardJSON),i=m.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{appearance:a,preferences:c}=n;return l.jsx(Aa,{FallbackComponent:Cj,children:l.jsxs(lF,{dashboardProps:n,children:[l.jsx(m$,{componentType:"surfboard",componentId:n.id}),l.jsxs(p$,{appearance:a,children:[l.jsx(Ebe,{toastOptions:{classNames:{toast:"max-w-[calc(100vw-2rem)] overflow-x-hidden !items-start [--toast-close-button-end:0.5rem] [--toast-close-button-start:auto] [--toast-close-button-transform:translate(0,0)] sm:max-w-[44rem]",content:"min-w-0 flex-1",icon:"mt-0.5 shrink-0",title:"max-w-full break-words pr-8",description:"max-w-full break-words",closeButton:"!top-2 h-6 w-6 rounded-md border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"}}}),l.jsxs(Wfe,{preferences:c,children:[o&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(N0t,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(S0t,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(k0t,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(YF,{...n,type:"dashboard",children:[s&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(C0t,{})}),l.jsx(w0t,{})]})})]})]})]})]})]})})}var j0t=Object.defineProperty,E0t=(e,t,n)=>t in e?j0t(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xS=(e,t,n)=>E0t(e,typeof t!="symbol"?t+"":t,n);const D0t={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},I0t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},T0t={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function M0t(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Yfe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const A0t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=Yfe(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},R0t={stringify:e=>`${e}`,parse:e=>parseFloat(e)},F0t={stringify:e=>e,parse:e=>e},d2={string:F0t,number:R0t,boolean:D0t,function:I0t,method:A0t,json:T0t},dx=Symbol.for("r2wc.render"),yS=Symbol.for("r2wc.connected"),Xd=Symbol.for("r2wc.context"),li=Symbol.for("r2wc.props");function P0t(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const p of i){c[p]=Array.isArray(t.props)?"string":t.props[p];const g=M0t(p);d[p]=g,f[g]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),xS(this,o,!0),xS(this,s),xS(this,r,{}),xS(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[li].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=c[g],S=y?d2[y]:null;if(y==="method"){const w=Yfe(b);Object.defineProperty(this[li].container,w,{enumerable:!0,configurable:!0,get(){return this[li][w]},set(C){this[li][w]=C,this[dx]()}}),this[li][g]=S.parse(x,b,this)}S!=null&&S.parse&&x&&(this[li][g]=S.parse(x,b,this))}for(const g of a)this[li][g]=b=>{const x=g.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:b,...u[g]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[yS]=!0,this[dx]()}disconnectedCallback(){this[yS]=!1,this[Xd]&&n.unmount(this[Xd]),delete this[Xd]}attributeChangedCallback(g,b,x){const y=f[g],S=c[y],w=S?d2[S]:null;y in c&&w!=null&&w.parse&&x&&(this[li][y]=w.parse(x,g,this),this[dx]())}[(o=yS,s=Xd,r=li,dx)](){this[yS]&&(this[Xd]?n.update(this[Xd],this[li]):this[Xd]=n.mount(this.container,e,this[li]))}}for(const p of i){const g=d[p],b=c[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[li][p]},set(x){this[li][p]=x;const y=b?d2[b]:null;if(y!=null&&y.stringify){const S=y.stringify(x,g,this);this.getAttribute(g)!==S&&this.setAttribute(g,S)}else this[dx]()}})}return h}function O0t(e,t,n){const r=CW.createRoot(e),s=v.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function L0t({root:e,ReactComponent:t},n){const r=v.createElement(t,n);e.render(r)}function $0t({root:e}){e.unmount()}function z0t(e,t={}){return P0t(e,t,{mount:O0t,update:L0t,unmount:$0t})}const B0t={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},V0t=z0t(qfe,{props:B0t}),H0t=v.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(g3,{context:t})," "]})}),Gfe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),U0t=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),W0t=Array.from(Gfe).join(", "),q0t=3,Y0t="Self-heal",G0t=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function K0t({card:e}){var Y,O,K,q,M;const[t,n]=v.useState({}),{authToken:r}=Ct(),s=m.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:o}=m.useAppearance(),i=v.useMemo(()=>Yv(o),[o]),a=m.useEditorStore(G=>G.frame),c=m.useEditorStore(G=>G.inlineFilterValuesMap[e.id]),u=m.useEditorStore(G=>G.actions.setCardInlineFilterValue),d=m.useEditorStore(G=>G.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:p}=Qh(((Y=f.customCardPreferences)==null?void 0:Y.url)||""),g=(O=p==null?void 0:p.visuals)==null?void 0:O.find(G=>{var L;return G.name===((L=f.customCardPreferences)==null?void 0:L.componentName)}),b=Gv(f,g)??"single",x=v.useMemo(()=>wL({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=v.useMemo(()=>{const G=x.findIndex(L=>(L==null?void 0:L.id)===e.id);return G<0?-1:y0(e,G)},[x,e]),S=v.useMemo(()=>b!=="multiple"||y<0?e.type:pm(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),w=v.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==e.type?{...e,type:S}:e,[e,S,b]),{data:C}=f_(w),N=m.useInteractionStore(G=>G.interactionStates),k=m.useDashboardStore(G=>{var L;return(L=G.dashboard)==null?void 0:L.id}),_=m.useDashboardStore(G=>G.dashboard.filters),E=m.useDashboardStore(G=>G.filterValues),D=m.useDashboardStore(G=>G.selectedSheetId),j=v.useMemo(()=>xL({card:e,sheetId:D||"",inlineFilterValues:c,setInlineFilterValue:G=>u(e.id,G),removeInlineFilterValue:G=>d(e.id,G)}),[e,D,c,u,d]),{cardFilters:I,cardFilterValues:T}=v.useMemo(()=>dv({card:e,interactionStates:N,currentDashboardId:k,filters:_,filterValues:E,selectedSheetId:D}),[e,N,k,_,E,D]),F=v.useCallback((G,L)=>{const $=CL(L);n(V=>({...V,[G]:$}))},[]),P=(K=f.customCardPreferences)==null?void 0:K.componentName,R=P?h(P):null,B=FN((q=f.customCardPreferences)==null?void 0:q.settings,f),z=v.useMemo(()=>vL(x),[x]),U=v.useMemo(()=>z.map((G,L)=>pm(G,L,g==null?void 0:g.slots)),[z,g==null?void 0:g.slots]);return P?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(v.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[R&&b==="single"&&l.jsx(R,{editing:!0,params:s,theme:i,settings:B,cardMetadata:oie({card:e,dataMetadata:C==null?void 0:C.metadata}),onDataChange:F,data:(C==null?void 0:C.records)||[],filters:I,filterValues:[...T||[],...c||[]],inlineFilters:j}),R&&b==="multiple"&&l.jsxs(l.Fragment,{children:[x.map((G,L)=>{if(!G)return null;const $=y0(G,L),V=pm(G,$,g==null?void 0:g.slots);return l.jsx(U5,{onDataChange:F,card:G,effectiveCardType:V},`${G.id}-${$}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(R,{editing:!0,onDataChange:F,...NL({configCard:f,slotOrderedCards:z,slotTypes:U,multiInputData:t,params:s,theme:i,chartSettings:B,filters:I,filterValues:[...T||[],...c||[]],inlineFilters:j})})})]})]},(M=f.customCardPreferences)==null?void 0:M.componentName)}):null}const Z0t=v.memo(K0t,(e,t)=>{var n,r,s,o,i,a,c,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((c=e.card.customCardPreferences)==null?void 0:c.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),X0t=m.create()(m.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var Kfe=["PageUp","PageDown"],Zfe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Xfe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},bb="Slider",[QR,Q0t,J0t]=m.createCollection(bb),[Qfe]=m.createContextScope(bb,[J0t]),[evt,fE]=Qfe(bb),Jfe=Q.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:p=!1,form:g,...b}=e,x=Q.useRef(new Set),y=Q.useRef(0),w=i==="horizontal"?tvt:nvt,[C=[],N]=m.useControllableState({prop:d,defaultProp:u,onChange:I=>{var F;(F=[...x.current][y.current])==null||F.focus(),f(I)}}),k=Q.useRef(C);function _(I){const T=avt(C,I);j(I,T)}function E(I){j(I,y.current)}function D(){const I=k.current[y.current];C[y.current]!==I&&h(C)}function j(I,T,{commit:F}={commit:!1}){const P=dvt(o),R=fvt(Math.round((I-r)/o)*o+r,P),B=m.clamp(R,[r,s]);N((z=[])=>{const U=ovt(z,B,T);if(uvt(U,c*o)){y.current=U.indexOf(B);const Y=String(U)!==String(z);return Y&&F&&h(U),Y?U:z}else return z})}return l.jsx(evt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:y,thumbs:x.current,values:C,orientation:i,form:g,children:l.jsx(QR.Provider,{scope:e.__scopeSlider,children:l.jsx(QR.Slot,{scope:e.__scopeSlider,children:l.jsx(w,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:m.composeEventHandlers(b.onPointerDown,()=>{a||(k.current=C)}),min:r,max:s,inverted:p,onSlideStart:a?void 0:_,onSlideMove:a?void 0:E,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&j(r,0,{commit:!0}),onEndKeyDown:()=>!a&&j(s,C.length-1,{commit:!0}),onStepKeyDown:({event:I,direction:T})=>{if(!a){const R=Kfe.includes(I.key)||I.shiftKey&&Zfe.includes(I.key)?10:1,B=y.current,z=C[B],U=o*R*T;j(z+U,B,{commit:!0})}}})})})})});Jfe.displayName=bb;var[ehe,the]=Qfe(bb,{startEdge:"left",endEdge:"right",size:"width",direction:1}),tvt=Q.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=Q.useState(null),p=m.useComposedRefs(t,w=>h(w)),g=Q.useRef(void 0),b=m.useDirection(s),x=b==="ltr",y=x&&!o||!x&&o;function S(w){const C=g.current||f.getBoundingClientRect(),N=[0,C.width],_=g$(N,y?[n,r]:[r,n]);return g.current=C,_(w-C.left)}return l.jsx(ehe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:l.jsx(nhe,{dir:b,"data-orientation":"horizontal",...d,ref:p,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const C=S(w.clientX);i==null||i(C)},onSlideMove:w=>{const C=S(w.clientX);a==null||a(C)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:w=>{const N=Xfe[y?"from-left":"from-right"].includes(w.key);u==null||u({event:w,direction:N?-1:1})}})})}),nvt=Q.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=Q.useRef(null),f=m.useComposedRefs(t,d),h=Q.useRef(void 0),p=!s;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],w=g$(y,p?[r,n]:[n,r]);return h.current=x,w(b-x.top)}return l.jsx(ehe,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:l.jsx(nhe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);o==null||o(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Xfe[p?"from-bottom":"from-top"].includes(b.key);c==null||c({event:b,direction:y?-1:1})}})})}),nhe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=fE(bb,n);return l.jsx(m.Primitive.span,{...u,ref:t,onKeyDown:m.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):Kfe.concat(Zfe).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:m.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:m.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:m.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),rhe="SliderTrack",she=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=fE(rhe,n);return l.jsx(m.Primitive.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});she.displayName=rhe;var JR="SliderRange",ohe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=fE(JR,n),o=the(JR,n),i=Q.useRef(null),a=m.useComposedRefs(t,i),c=s.values.length,u=s.values.map(h=>lhe(h,s.min,s.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(m.Primitive.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});ohe.displayName=JR;var eF="SliderThumb",ihe=Q.forwardRef((e,t)=>{const n=Q0t(e.__scopeSlider),[r,s]=Q.useState(null),o=m.useComposedRefs(t,a=>s(a)),i=Q.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return l.jsx(rvt,{...e,ref:o,index:i})}),rvt=Q.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=fE(eF,n),a=the(eF,n),[c,u]=Q.useState(null),d=m.useComposedRefs(t,S=>u(S)),f=c?i.form||!!c.closest("form"):!0,h=m.useSize(c),p=i.values[r],g=p===void 0?0:lhe(p,i.min,i.max),b=ivt(r,i.values.length),x=h==null?void 0:h[a.size],y=x?lvt(x,g,a.direction):0;return Q.useEffect(()=>{if(c)return i.thumbs.add(c),()=>{i.thumbs.delete(c)}},[c,i.thumbs]),l.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[l.jsx(QR.ItemSlot,{scope:e.__scopeSlider,children:l.jsx(m.Primitive.span,{role:"slider","aria-label":e["aria-label"]||b,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...o,ref:d,style:p===void 0?{display:"none"}:e.style,onFocus:m.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&l.jsx(ahe,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:p},r)]})});ihe.displayName=eF;var svt="RadioBubbleInput",ahe=Q.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=Q.useRef(null),o=m.useComposedRefs(s,r),i=m.usePrevious(t);return Q.useEffect(()=>{const a=s.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),l.jsx(m.Primitive.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});ahe.displayName=svt;function ovt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function lhe(e,t,n){const o=100/(n-t)*(e-t);return m.clamp(o,[0,100])}function ivt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function avt(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function lvt(e,t,n){const r=e/2,o=g$([0,50],[0,r]);return(r-o(t)*n)*n}function cvt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function uvt(e,t){if(t>0){const n=cvt(e);return Math.min(...n)>=t}return!0}function g$(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function dvt(e){return(String(e).split(".")[1]||"").length}function fvt(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var che=Jfe,hvt=she,pvt=ohe,mvt=ihe;const uhe=Q.forwardRef(({className:e,...t},n)=>l.jsxs(che,{ref:n,className:m.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx(hvt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(pvt,{className:"absolute h-full bg-primary"})}),l.jsx(mvt,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));uhe.displayName=che.displayName;const dhe=["SUN","MON","TUE","WED","THU","FRI","SAT"],gvt=dhe.reduce((e,t,n)=>({...e,[t]:n}),{}),tc={repeats:"weekly",hour:9,minute:0,weekdays:[1,2,3,4,5],isCustom:!1};function bvt(e){if(!e||!e.trim())return{...tc};const t=e.trim(),r=(t.startsWith("cron(")&&t.endsWith(")")?t.slice(5,-1):t).trim().split(/\s+/);if(r.length<5||r.length>6)return{...tc,isCustom:!0};const[s,o,i,a,c]=r,u=Number(s),d=Number(o);if(!Number.isInteger(u)||u<0||u>59||!Number.isInteger(d)||d<0||d>23)return{...tc,isCustom:!0};if(i==="*"&&(c==="?"||c==="*"))return{...tc,repeats:"daily",hour:d,minute:u};if(i==="?"&&c!=="?"&&c!=="*"){const h=c.split(",").map(p=>p.toUpperCase()).map(p=>gvt[p]).filter(p=>typeof p=="number");if(h.length>0)return{...tc,repeats:"weekly",hour:d,minute:u,weekdays:h}}return i==="1,15"&&(c==="?"||c==="*")?{...tc,repeats:"biweekly",hour:d,minute:u}:i==="1"&&(c==="?"||c==="*")?{...tc,repeats:"monthly",hour:d,minute:u}:{...tc,hour:d,minute:u,isCustom:!0}}function xvt(e){const t=e.minute,n=e.hour;switch(e.repeats){case"daily":return`cron(${t} ${n} * * ? *)`;case"weekly":{const r=e.weekdays.length>0?e.weekdays.slice().sort((s,o)=>s-o).map(s=>dhe[s]).join(","):"MON";return`cron(${t} ${n} ? * ${r} *)`}case"biweekly":return`cron(${t} ${n} 1,15 * ? *)`;case"monthly":return`cron(${t} ${n} 1 * ? *)`}}function fhe(e,t){const n=e<12?"AM":"PM",r=e%12===0?12:e%12,s=t.toString().padStart(2,"0");return`${r}:${s} ${n}`}function yvt(e){return!e||e==="UTC"?"UTC":(e.split("/").pop()??e).replace(/_/g," ")}function vvt(e){if(e.length===7)return"every day";const t=e.slice().sort((s,o)=>s-o);if(t.length===5&&t.every(s=>s>=1&&s<=5))return"weekdays";const r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return t.map(s=>r[s]).join(", ")}function wvt(e,t,n,r){const s=fhe(e.hour,e.minute),o=yvt(t);let i;if(e.isCustom)i=`Custom schedule · ${s} ${o}`;else switch(e.repeats){case"daily":i=`Daily at ${s} ${o}`;break;case"weekly":i=`Weekly · ${vvt(e.weekdays)} at ${s} ${o}`;break;case"biweekly":i=`Every two weeks (1st and 15th) at ${s} ${o}`;break;case"monthly":i=`Monthly on the 1st at ${s} ${o}`;break}const a=[];return n&&n!=="Today"&&a.push(`from ${n}`),r&&a.push(`until ${r}`),a.length>0?`${i}, ${a.join(" ")}`:i}const Svt=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Berlin","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];exports.Accordion=l3;exports.AccordionContent=T0;exports.AccordionItem=D0;exports.AccordionTrigger=I0;exports.AddDataPicker=f$;exports.AggregateTable=W_;exports.Alert=zP;exports.AlertDescription=BP;exports.AlertDialog=Lc;exports.AlertDialogAction=kl;exports.AlertDialogCancel=_l;exports.AlertDialogContent=vl;exports.AlertDialogDescription=Nl;exports.AlertDialogFooter=Sl;exports.AlertDialogHeader=wl;exports.AlertDialogTitle=Cl;exports.AlertDialogTrigger=V2;exports.AlertTitle=wX;exports.ArrowDown=Js;exports.ArrowDownIcon=wqe;exports.ArrowLeft=ev;exports.ArrowRight=Sk;exports.ArrowUp=eo;exports.ArrowUpIcon=Cqe;exports.AssistantContextEntityControls=XR;exports.AssistantStatus=lde;exports.AtSign=QW;exports.AxisConfigurator=jg;exports.Badge=Yr;exports.Bell=SS;exports.BookType=eq;exports.BulletChartIcon=ade;exports.COMMON_TIMEZONES=Svt;exports.CSS=_i;exports.CalculatedFieldEditor=yle;exports.Calculator=nq;exports.Calendar=gi;exports.Calendar$1=ZS;exports.CalendarRange=rq;exports.Card=Tm;exports.CardContent=wk;exports.CardHeader=vk;exports.CardSummary=dR;exports.CardTitle=mg;exports.ChartArea=F2;exports.ChartColumnIncreasing=sq;exports.ChartColumnStacked=oq;exports.ChartJsVisual=$v;exports.ChartLine=iq;exports.ChartNoAxesGantt=lq;exports.ChartPie=cq;exports.ChartScatter=uq;exports.ChatInputWithContext=h$;exports.Checkbox=Ln;exports.ChevronLeft=Oh;exports.ChevronRight=Mr;exports.Circle=Ck;exports.CircleAlert=ih;exports.CircleCheck=hq;exports.CircleHelp=pq;exports.Clock=fF;exports.CodeHighlighter=Uu;exports.CodeXml=Bf;exports.Collapsible=Vc;exports.CollapsibleContent=Uc;exports.CollapsibleTrigger=Hc;exports.ColorField=Bi;exports.Command=Pj;exports.CommandEmpty=Lj;exports.CommandGroup=$j;exports.CommandInput=ZL;exports.CommandItem=zj;exports.CommandList=Oj;exports.CommandSeparator=$ae;exports.ComparisonMetadataBadge=Wee;exports.Container=YF;exports.ControlDefaultValueEditor=Ble;exports.ControlDefinitionOptionsEditor=zle;exports.ControlIdInput=Ple;exports.ControlVisibilitySettings=$tt;exports.Copy=Pc;exports.CopyButton=Ac;exports.CopyPlus=O2;exports.Cross2Icon=jqe;exports.CustomFilterPopover=gL;exports.CustomScrollArea=zl;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=GJ;exports.DEFAULT_SCHEDULE_VM=tc;exports.Dashboard=qfe;exports.DashboardActionsMenu=TY;exports.DashboardCard=Wie;exports.DashboardCreateDialogBase=aG;exports.DashboardExportDialog=$fe;exports.DashboardPlus=_0t;exports.DashboardWC=V0t;exports.DataAppBuilder=pK;exports.DataTableConditionalFormattingSettings=Dce;exports.DataTablePagination=z_;exports.Database=ei;exports.DateRangePicker=Z5;exports.DefaultChatTransport=c$;exports.Dialog=Oo;exports.DialogContent=mo;exports.DialogDescription=si;exports.DialogFooter=Gc;exports.DialogHeader=na;exports.DialogTitle=go;exports.DialogTrigger=oG;exports.DisplayPreferencesProvider=kj;exports.DndContext=ow;exports.Donut=mq;exports.Download=qc;exports.DownloadPdf=zfe;exports.DragOverlay=kae;exports.DropdownMenu=Ao;exports.DropdownMenuCheckboxItem=bu;exports.DropdownMenuContent=fo;exports.DropdownMenuItem=jn;exports.DropdownMenuLabel=kc;exports.DropdownMenuRadioGroup=tbe;exports.DropdownMenuRadioItem=DY;exports.DropdownMenuSeparator=Ea;exports.DropdownMenuSub=TF;exports.DropdownMenuSubContent=Tk;exports.DropdownMenuSubTrigger=Ik;exports.DropdownMenuTrigger=Ro;exports.EMPTY_DATA_SOURCE=z0;exports.Editable=ON;exports.EditableText=Zi;exports.EditorCustomVisual=Z0t;exports.Ellipsis=ja;exports.EllipsisVertical=Lh;exports.ErrorBoundary=Aa;exports.ExportError=Rg;exports.ExternalLink=Am;exports.Eye=tv;exports.EyeOff=Nk;exports.Fallback=Cj;exports.FallbackVisual=w0;exports.FeedbackCategory=xd;exports.FeedbackDialog=L0;exports.FieldsList=g3;exports.FieldsSection=H0t;exports.FileSpreadsheet=gq;exports.FileText=vi;exports.Filter=ah;exports.FilterComponent=gj;exports.FilterInfo=aR;exports.FilterableFieldsPanel=wle;exports.Globe=gg;exports.Grid3x3=bq;exports.GripVertical=Yc;exports.HEATMAP_PRESET_PALETTES=YM;exports.Hash=xq;exports.House=yq;exports.HoverCard=Pg;exports.HoverCardContent=cd;exports.HoverCardTrigger=Og;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=Gfe;exports.INLINE_ALLOWED_TOOL_LIST=W0t;exports.INLINE_BLOCKED_MUTATING_TOOLS=U0t;exports.IconButton=Vu;exports.IconForFieldType=rC;exports.InfoHover=LL;exports.InlineFilterBar=Fie;exports.KPICard=Th;exports.KeyboardSensor=rw;exports.Layers=nv;exports.LayoutDashboard=Rm;exports.Link=hF;exports.LoadingDots=dd;exports.Lock=kk;exports.MAX_SELF_HEAL_ATTEMPTS=q0t;exports.Map=Sq;exports.Markdown=bue;exports.Maximize2=_k;exports.MdStackedLineChart=ode;exports.Minimize2=pF;exports.MultiInputEmptyRenderer=U5;exports.PYTHON_DEFAULT_CODE=tF;exports.PanelLeft=mF;exports.PanelResizeHandle=qk;exports.Paperclip=Nq;exports.PenLine=L2;exports.Pencil=$2;exports.PendingMessagesDisplay=Rfe;exports.PersistedDynamicVisual=Nj;exports.PiChartPolar=tde;exports.PivotTableTanstack=rb;exports.Placeholders=ude;exports.Play=kq;exports.Plus=dr;exports.PointerSensor=cb;exports.PrintMessages=cde;exports.Progress=J3;exports.RECOVERABLE_SQL_ERROR_CODES=G0t;exports.Radar=_q;exports.RadioGroup=Ia;exports.RadioGroupItem=js;exports.RefreshCw=Oc;exports.ResizableHandle=uK;exports.ResizablePanel=Ry;exports.ResizablePanelGroup=UF;exports.ResourceEditDialog=LG;exports.ResourceType=Xr;exports.SELF_HEAL_TIMELINE_STEP=Y0t;exports.Search=Ws;exports.SeedQuestions=Efe;exports.SemaphorContext=pg;exports.SemaphorContextProvider=lF;exports.SemaphorQueryClient=qW;exports.SemaphorReadyIndicator=m$;exports.SemaphorStyleWrapper=sb;exports.Send=bF;exports.Settings=xF;exports.Settings2=bg;exports.Share2=jq;exports.ShareDialog=OG;exports.Sheet=Aee;exports.SheetContent=BO;exports.SheetDescription=HO;exports.SheetHeader=Fee;exports.SheetTitle=VO;exports.SheetTrigger=DOe;exports.Slider=uhe;exports.SortableContext=iw;exports.Sparkles=Fm;exports.Square=Eq;exports.SquarePen=jk;exports.Star=yF;exports.StructuralParticipantSelector=Ole;exports.SummaryCard=sR;exports.TABLE_PRESENTATION_DEFAULT_STYLE=Xu;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=Ui;exports.TableBody=xh;exports.TableCell=sr;exports.TableColumnVisibilitySettings=bce;exports.TableHead=Ko;exports.TableHeader=Fg;exports.TablePresentationSettings=yce;exports.TableRow=Kr;exports.TableSkeleton=$L;exports.TableVisual=ud;exports.TbChartBubble=nde;exports.TbChartFunnel=rde;exports.TbChartTreemap=sde;exports.TextCard=og;exports.Textarea=Bh;exports.TiSortNumerically=ide;exports.Toggle=wj;exports.Tornado=Dq;exports.Trash2=yl;exports.TreePalm=wF;exports.TrendingUp=Iq;exports.TriangleAlert=ba;exports.TypeGlyph=Qv;exports.UXProvider=p$;exports.User=Mq;exports.UserRound=Tq;exports.Users=SF;exports.applyFilterOverridesToDashboardInputSlots=BZ;exports.areContextEntitiesEqual=zr;exports.areEntitiesJoined=JJ;exports.arrayMove=ub;exports.buildCardControlUsageById=Btt;exports.buildCustomCardTheme=Yv;exports.buildDashboardCardExecutionSnapshot=zZ;exports.buildDashboardControlUsageById=ztt;exports.buildDashboardExecutionSnapshot=RP;exports.buildDashboardInputExecutionSnapshot=Wu;exports.buildDashboardSheetsInputExecutionSnapshot=HZ;exports.buildDashboardStructuralParticipantIdsByControlId=Ule;exports.buildFilterFieldMeta=n3;exports.buildFilterSemanticContext=r3;exports.buildInlineFilterNodes=xL;exports.buildMultiInputCustomVisualProps=NL;exports.buildScheduleExpr=xvt;exports.buildSchedulePreview=wvt;exports.buildSlotOrderedCards=vL;exports.calculateContextAwareFilters=dv;exports.calculateFieldState=MO;exports.canUserAccessVisuals=bKe;exports.canUserCreateDashboards=gKe;exports.canUserEdit=hKe;exports.canUserManageDashboards=mKe;exports.canUserManageGroups=xKe;exports.canUserUseFilters=pKe;exports.cancelExport=bPe;exports.chartSupportsDataLabels=WQ;exports.chartSupportsLegend=HQ;exports.chartTypes=iE;exports.cleanupKpiMetricComparisonMode=Yae;exports.cloneDeep=Zo;exports.cloneLinkedFrameWithSourceMapping=LGe;exports.closestCenter=nw;exports.commitSharedCalculatedFields=af;exports.createAssistantConversationId=qp;exports.createAssistantRequestId=_fe;exports.createCardsFromSlots=eYe;exports.createChartConfig=Ag;exports.createDashboardControlInputFromControl=Pst;exports.createDefaultGlobalDateFilter=ZCe;exports.createExport=yee;exports.createUniqueDashboardInputVariableNameFromName=Ju;exports.dedup=Jxt;exports.doesStoredFilterMatchField=ug;exports.downloadDocumentPdf=PP;exports.downloadPdf=XZ;exports.extractSqlParamReferences=Yse;exports.extractTableMetadata=t3;exports.fieldAlreadyExists=tee;exports.findCustomVisualConfigCard=SL;exports.findDashboardFrameById=BCe;exports.flexRender=Qo;exports.formatDisplayFormula=AJe;exports.formatFileSize=vPe;exports.formatFilterLine=CX;exports.formatTimeLabel=fhe;exports.getAutoDetectedChartIcon=Wft;exports.getChartGridStyle=v_e;exports.getChartIconByType=qft;exports.getColorForValue=uM;exports.getConfigSlotExpectedType=Jqe;exports.getCoreRowModel=O_;exports.getCustomVisualInputCards=wL;exports.getDateFormatOptionsForGranularity=j0;exports.getDefaultAxisConfig=fM;exports.getDefaultChartColors=qh;exports.getDefaultDataLabelsConfig=Cv;exports.getDefaultExportFormat=zX;exports.getDefaultFilterSql=tL;exports.getDefaultLegendConfig=mO;exports.getDefaultRunningTotalPartitionByFieldIds=vy;exports.getDocumentSectionEditorCard=xtt;exports.getDocumentSheetDashboardInputs=dw;exports.getDownloadUrl=gPe;exports.getEffectiveCardTypeForSlot=pm;exports.getEntityIcon=xk;exports.getErrorMessage=xfe;exports.getExportStatus=mPe;exports.getExports=pPe;exports.getExpressionFieldKind=bd;exports.getFieldExpressionAnnotation=s3;exports.getFilterCount=VN;exports.getGlobalDateFilter=wg;exports.getGlobalDateFilterCoverage=XCe;exports.getGranularityOptionsForFieldType=S3;exports.getKeys=pr;exports.getMetricDisplayLabel=PFe;exports.getNewField=iee;exports.getObjectDiff=_W;exports.getPaginationRowModel=L_;exports.getRoleBasedDisplayOverrides=Rie;exports.getRunningTotalOrderByCandidates=nJe;exports.getSelectedDateFilterColumn=Kse;exports.getSheetScopedFilterValues=Ly;exports.getSlotDefinitionForIndex=yL;exports.getSlotExpectedChartType=yj;exports.getSlotIndexForCard=y0;exports.getSortedRowModel=Mee;exports.getSupportedExportFormats=$X;exports.getTableConditionalFormattingColumnOptions=Cce;exports.getTableOutputColumnOptions=Nce;exports.getTablePageSizeOptions=gee;exports.handleAggregationChange=lR;exports.handleAggregationLabelChange=Mie;exports.hasFlatTableTotalsBehavior=WNe;exports.horizontalListSortingStrategy=qL;exports.isCalculatedFilterField=E0;exports.isCardSummaryVisibleOnCard=kL;exports.isCustomVisualConfigCard=nR;exports.isDefaultColor=eke;exports.isEligibleFlatTableTotalsCard=Sg;exports.isExportComplete=yPe;exports.isExportInProgress=xPe;exports.isInAiScopeArray=Qxt;exports.isManagedCalculatedExpressionField=ka;exports.isMetricTransformEnabled=eJe;exports.isPromiseLike=KR;exports.isSubtotalEnabledAggregateTable=e3;exports.isSupportedDocumentTableCardType=ytt;exports.lastAssistantMessageIsCompleteWithToolCalls=pfe;exports.merge=xl;exports.mergeAxisConfig=hM;exports.normalizeConditionalFormatting=jP;exports.normalizeContextFormatMode=DX;exports.normalizeDashboardInputVariableName=J0;exports.normalizeMultiInputPayload=CL;exports.parseScheduleExpr=bvt;exports.pivotData=gv;exports.prepareFeedbackData=oE;exports.purify=PA;exports.reindexSlotCards=Qqe;exports.remarkGfm=Bue;exports.removeFromScopeArray=eyt;exports.resolveDashboardInputContext=$l;exports.resolveDomainCalculatedFieldForEdit=Iet;exports.resolveMultiInputType=Gv;exports.resolveMultiInputTypeFromVisual=tYe;exports.resolveTablePageSize=R_;exports.resolveTablePresentationStyle=JO;exports.sanitizeAIScope=bfe;exports.saveCalculatedFieldToCardScope=vR;exports.saveCalculatedFieldToSharedScope=vle;exports.saveCalculatedFieldToSheetScope=wR;exports.seedSemanticMetricFormatDefaults=Kae;exports.setTableColumnVisibility=See;exports.setupEditorWithCard=h_;exports.showAllTableColumns=NPe;exports.showJoinRequiredNotification=eee;exports.sortByColumnsToSortState=tte;exports.sortStateToSortByColumns=nte;exports.sortableKeyboardCoordinates=GL;exports.supportsMetricTransformForMetric=Gae;exports.supportsTableConditionalFormatting=vce;exports.toEntityArray=Na;exports.ue=ut;exports.useActiveExports=awe;exports.useActiveToolStatus=Lfe;exports.useAddFrameWithFreshSemanticExecutionPayload=OL;exports.useAddNewFrame=tae;exports.useAssistantContainer=bK;exports.useAssistantContextEntities=jj;exports.useAssistantLayoutStore=Hf;exports.useAssistantPanel=mK;exports.useAssistantProfile=jfe;exports.useAutoScroll=Pfe;exports.useAutoSubmitQueue=Ffe;exports.useBrandStudioPreview=f0t;exports.useCard=GFe;exports.useCardFilterValues=lee;exports.useCardSummary=_L;exports.useChat=gfe;exports.useColumns=XL;exports.useCreateVisualWithFrame=Ybe;exports.useCurrentUserInfo=ta;exports.useCustomVisual=Qh;exports.useCustomVisualsQuery=mL;exports.useDashboardAppearance=Rl;exports.useDashboardById=LY;exports.useDashboardCreation=BY;exports.useDashboardManagement=zY;exports.useDashboardPreferences=xg;exports.useDashboardQuery=Q0;exports.useDashboardStructuralParticipants=Wle;exports.useDashboardSummary=pie;exports.useDataColumns=Xae;exports.useDateFilterHook=M7e;exports.useDebounce=py;exports.useDefaultDashboardMutation=MY;exports.useDisplayPreferences=Ll;exports.useDroppable=Nae;exports.useEditorAside=Bj;exports.useEditorCardQuery=f_;exports.useEnsureReactGlobals=Sse;exports.useExportActions=xK;exports.useExportStore=Yk;exports.useFieldManagement=Zae;exports.useFilterableFields=Uae;exports.useFullscreenAssistant=gK;exports.useGroupMembers=Vxe;exports.useGroups=DG;exports.useHasDashboardId=yK;exports.useInProgressExportsCount=lwe;exports.useIsDashboardSelected=Rpe;exports.useIsVisualSelected=Fpe;exports.useJoinabilityMap=JL;exports.useManagementActions=Ph;exports.useManagementStore=is;exports.useMessageWindow=Ofe;exports.useMutation=co;exports.usePivotTableConfig=Gh;exports.usePluginQuery=eie;exports.useQuery=On;exports.useQueryClient=ns;exports.useReactTable=$_;exports.useResolveExistingFrameSemanticExecutionPayload=VGe;exports.useResourceManagement=Rk;exports.useResourceUpdateState=$Y;exports.useScopedFields=Hae;exports.useSelectedVisual=Ape;exports.useSemaphorContext=Ct;exports.useSensor=cg;exports.useSensors=Tj;exports.useSortable=db;exports.useStarredChartsStore=X0t;exports.useSurfaceAppearance=Zc;exports.useTableQueryState=qee;exports.useTextFilterHook=H7e;exports.useTheme=nF;exports.useTopoJson=kv;exports.useUnifiedUsers=OF;exports.useUpdateResource=RY;exports.useUpdateVisualMutation=Gbe;exports.useUserPreferences=lG;exports.useVisualById=Ak;exports.useVisualManagement=qbe;exports.validateFieldForChartType=qae;exports.verticalListSortingStrategy=YL;
1425
+ `)}})}});var Axt=_bt(()=>sfe(ea([Or({type:yn("text-start"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("text-delta"),id:Ut(),delta:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("text-end"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("error"),errorText:Ut()}),Or({type:yn("tool-input-start"),toolCallId:Ut(),toolName:Ut(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),Or({type:yn("tool-input-delta"),toolCallId:Ut(),inputTextDelta:Ut()}),Or({type:yn("tool-input-available"),toolCallId:Ut(),toolName:Ut(),input:Qa(),providerExecuted:Uo().optional(),providerMetadata:Jr.optional(),dynamic:Uo().optional()}),Or({type:yn("tool-input-error"),toolCallId:Ut(),toolName:Ut(),input:Qa(),providerExecuted:Uo().optional(),providerMetadata:Jr.optional(),dynamic:Uo().optional(),errorText:Ut()}),Or({type:yn("tool-output-available"),toolCallId:Ut(),output:Qa(),providerExecuted:Uo().optional(),dynamic:Uo().optional(),preliminary:Uo().optional()}),Or({type:yn("tool-output-error"),toolCallId:Ut(),errorText:Ut(),providerExecuted:Uo().optional(),dynamic:Uo().optional()}),Or({type:yn("reasoning-start"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("reasoning-delta"),id:Ut(),delta:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("reasoning-end"),id:Ut(),providerMetadata:Jr.optional()}),Or({type:yn("source-url"),sourceId:Ut(),url:Ut(),title:Ut().optional(),providerMetadata:Jr.optional()}),Or({type:yn("source-document"),sourceId:Ut(),mediaType:Ut(),title:Ut(),filename:Ut().optional(),providerMetadata:Jr.optional()}),Or({type:yn("file"),url:Ut(),mediaType:Ut(),providerMetadata:Jr.optional()}),Or({type:Jde(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Ut().optional(),data:Qa(),transient:Uo().optional()}),Or({type:yn("start-step")}),Or({type:yn("finish-step")}),Or({type:yn("start"),messageId:Ut().optional(),messageMetadata:Qa().optional()}),Or({type:yn("finish"),finishReason:Zde(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:Qa().optional()}),Or({type:yn("abort")}),Or({type:yn("message-metadata"),messageMetadata:Qa()})])));function Rxt(e){return e.type.startsWith("data-")}function ffe(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;const n={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const s=t[r];if(s===void 0)continue;const o=r in e?e[r]:void 0,i=s!==null&&typeof s=="object"&&!Array.isArray(s)&&!(s instanceof Date)&&!(s instanceof RegExp),a=o!=null&&typeof o=="object"&&!Array.isArray(o)&&!(o instanceof Date)&&!(o instanceof RegExp);i&&a?n[r]=ffe(o,s):n[r]=s}return n}function Fxt(e){const t=["ROOT"];let n=-1,r=null;function s(c,u,d){switch(c){case'"':{n=u,t.pop(),t.push(d),t.push("INSIDE_STRING");break}case"f":case"t":case"n":{n=u,r=u,t.pop(),t.push(d),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=u,t.pop(),t.push(d),t.push("INSIDE_NUMBER");break}case"{":{n=u,t.pop(),t.push(d),t.push("INSIDE_OBJECT_START");break}case"[":{n=u,t.pop(),t.push(d),t.push("INSIDE_ARRAY_START");break}}}function o(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(c,u){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let c=0;c<e.length;c++){const u=e[c];switch(t[t.length-1]){case"ROOT":s(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=c,t.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{s(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=c;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=c,t.pop();break}default:{n=c,s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=c,t.pop();break}default:{n=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{n=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,c);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,c+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,c)):n=c;break}}}let a=e.slice(0,n+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{a+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{a+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{a+="]";break}case"INSIDE_LITERAL":{const d=e.substring(r,e.length);"true".startsWith(d)?a+="true".slice(d.length):"false".startsWith(d)?a+="false".slice(d.length):"null".startsWith(d)&&(a+="null".slice(d.length))}}return a}async function hfe(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await bk({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await bk({text:Fxt(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function aC(e){return e.type.startsWith("tool-")}function Pxt(e){return e.type==="dynamic-tool"}function qR(e){return aC(e)||Pxt(e)}function XU(e){return e.type.split("-").slice(1).join("-")}function Oxt({lastMessage:e,messageId:t}){return{message:(e==null?void 0:e.role)==="assistant"?e:{id:t,metadata:void 0,role:"assistant",parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Lxt({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,c){await r(async({state:u,write:d})=>{var f,h,p,g;function b(C){const k=u.message.parts.filter(aC).find(_=>_.toolCallId===C);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function x(C){const k=u.message.parts.filter(_=>_.type==="dynamic-tool").find(_=>_.toolCallId===C);if(k==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return k}function y(C){var N;const k=u.message.parts.find(D=>aC(D)&&D.toolCallId===C.toolCallId),_=C,E=k;k!=null?(k.state=C.state,E.input=_.input,E.output=_.output,E.errorText=_.errorText,E.rawInput=_.rawInput,E.preliminary=_.preliminary,E.providerExecuted=(N=_.providerExecuted)!=null?N:k.providerExecuted,_.providerMetadata!=null&&k.state==="input-available"&&(k.callProviderMetadata=_.providerMetadata)):u.message.parts.push({type:`tool-${C.toolName}`,toolCallId:C.toolCallId,state:C.state,input:_.input,output:_.output,rawInput:_.rawInput,errorText:_.errorText,providerExecuted:_.providerExecuted,preliminary:_.preliminary,..._.providerMetadata!=null?{callProviderMetadata:_.providerMetadata}:{}})}function S(C){var N,k;const _=u.message.parts.find(j=>j.type==="dynamic-tool"&&j.toolCallId===C.toolCallId),E=C,D=_;_!=null?(_.state=C.state,D.toolName=C.toolName,D.input=E.input,D.output=E.output,D.errorText=E.errorText,D.rawInput=(N=E.rawInput)!=null?N:D.rawInput,D.preliminary=E.preliminary,D.providerExecuted=(k=E.providerExecuted)!=null?k:_.providerExecuted,E.providerMetadata!=null&&_.state==="input-available"&&(_.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:C.toolName,toolCallId:C.toolCallId,state:C.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function w(C){if(C!=null){const N=u.message.metadata!=null?ffe(u.message.metadata,C):C;t!=null&&await qU({value:N,schema:t}),u.message.metadata=N}}switch(a.type){case"text-start":{const C={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=C,u.message.parts.push(C),d();break}case"text-delta":{const C=u.activeTextParts[a.id];C.text+=a.delta,C.providerMetadata=(f=a.providerMetadata)!=null?f:C.providerMetadata,d();break}case"text-end":{const C=u.activeTextParts[a.id];C.state="done",C.providerMetadata=(h=a.providerMetadata)!=null?h:C.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const C={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=C,u.message.parts.push(C),d();break}case"reasoning-delta":{const C=u.activeReasoningParts[a.id];C.text+=a.delta,C.providerMetadata=(p=a.providerMetadata)!=null?p:C.providerMetadata,d();break}case"reasoning-end":{const C=u.activeReasoningParts[a.id];C.providerMetadata=(g=a.providerMetadata)!=null?g:C.providerMetadata,C.state="done",delete u.activeReasoningParts[a.id],d();break}case"file":{u.message.parts.push({type:"file",mediaType:a.mediaType,url:a.url}),d();break}case"source-url":{u.message.parts.push({type:"source-url",sourceId:a.sourceId,url:a.url,title:a.title,providerMetadata:a.providerMetadata}),d();break}case"source-document":{u.message.parts.push({type:"source-document",sourceId:a.sourceId,mediaType:a.mediaType,title:a.title,filename:a.filename,providerMetadata:a.providerMetadata}),d();break}case"tool-input-start":{const C=u.message.parts.filter(aC);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:C.length,dynamic:a.dynamic},a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const C=u.partialToolCalls[a.toolCallId];C.text+=a.inputTextDelta;const{value:N}=await hfe(C.text);C.dynamic?S({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}):y({toolCallId:a.toolCallId,toolName:C.toolName,state:"input-streaming",input:N}),d();break}case"tool-input-available":{a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d(),o&&!a.providerExecuted&&await o({toolCall:a});break}case"tool-input-error":{a.dynamic?S({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:void 0,rawInput:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}),d();break}case"tool-output-available":{if(a.dynamic){const C=x(a.toolCallId);S({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-available",input:C.input,output:a.output,preliminary:a.preliminary})}else{const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:XU(C),state:"output-available",input:C.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const C=x(a.toolCallId);S({toolCallId:a.toolCallId,toolName:C.toolName,state:"output-error",input:C.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const C=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:XU(C),state:"output-error",input:C.input,rawInput:C.rawInput,errorText:a.errorText,providerExecuted:a.providerExecuted})}d();break}case"start-step":{u.message.parts.push({type:"step-start"});break}case"finish-step":{u.activeTextParts={},u.activeReasoningParts={};break}case"start":{a.messageId!=null&&(u.message.id=a.messageId),await w(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await w(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await w(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(Rxt(a)){(n==null?void 0:n[a.type])!=null&&await qU({value:a.data,schema:n[a.type]});const C=a;if(C.transient){i==null||i(C);break}const N=C.id!=null?u.message.parts.find(k=>C.type===k.type&&C.id===k.id):void 0;N!=null?N.data=C.data:u.message.parts.push(C),i==null||i(C),d()}}c.enqueue(a)})}}))}async function $xt({stream:e,onError:t}){const n=e.getReader();try{for(;;){const{done:r}=await n.read();if(r)break}}catch(r){t==null||t(r)}finally{n.releaseLock()}}xw({prefix:"aitxt",size:24});xw({prefix:"aiobj",size:24});var zxt=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(r){n(r)}}),this.processQueue()})}};xw({prefix:"aiobj",size:24});var Bxt={};Cxt(Bxt,{object:()=>Hxt,text:()=>Vxt});var Vxt=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),Hxt=({schema:e})=>{const t=wxt(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await hfe(n);switch(r.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:r.value};default:{const s=r.state;throw new Error(`Unsupported parse state: ${s}`)}}},async parseOutput({text:n},r){const s=await bk({text:n});if(!s.success)throw new KU({message:"No object generated: could not parse the response.",cause:s.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});const o=await a$({value:s.value,schema:t});if(!o.success)throw new KU({message:"No object generated: response did not match schema.",cause:o.error,text:n,response:r.response,usage:r.usage,finishReason:r.finishReason});return o.value}}};async function Uxt(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new Error("FileList is not supported in the current environment");return Promise.all(Array.from(e).map(async t=>{const{name:n,type:r}=t,s=await new Promise((o,i)=>{const a=new FileReader;a.onload=c=>{var u;o((u=c.target)==null?void 0:u.result)},a.onerror=c=>i(c),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var Wxt=class{constructor({api:e="/api/chat",credentials:t,headers:n,body:r,fetch:s,prepareSendMessagesRequest:o,prepareReconnectToStreamRequest:i}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=s,this.prepareSendMessagesRequest=o,this.prepareReconnectToStreamRequest=i}async sendMessages({abortSignal:e,...t}){var n,r,s,o,i;const a=await Ip(this.body),c=await Ip(this.headers),u=await Ip(this.credentials),d={...cf(c),...cf(t.headers)},f=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:d,credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),h=(r=f==null?void 0:f.api)!=null?r:this.api,p=(f==null?void 0:f.headers)!==void 0?cf(f.headers):d,g=(f==null?void 0:f.body)!==void 0?f.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},b=(s=f==null?void 0:f.credentials)!=null?s:u,y=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:UU({"Content-Type":"application/json",...p},`ai-sdk/${ZU}`,HU()),body:JSON.stringify(g),credentials:b,signal:e});if(!y.ok)throw new Error((i=await y.text())!=null?i:"Failed to fetch the chat response.");if(!y.body)throw new Error("The response body is empty.");return this.processResponseStream(y.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await Ip(this.body),a=await Ip(this.headers),c=await Ip(this.credentials),u={...cf(a),...cf(e.headers)},d=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:u,credentials:c,requestMetadata:e.metadata})),f=(n=d==null?void 0:d.api)!=null?n:`${this.api}/${e.chatId}/stream`,h=(d==null?void 0:d.headers)!==void 0?cf(d.headers):u,p=(r=d==null?void 0:d.credentials)!=null?r:c,b=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:UU(h,`ai-sdk/${ZU}`,HU()),credentials:p});if(b.status===204)return null;if(!b.ok)throw new Error((o=await b.text())!=null?o:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}},c$=class extends Wxt{constructor(e={}){super(e)}processResponseStream(e){return Dbt({stream:e,schema:Axt}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},qxt=class{constructor({generateId:e=ybt,id:t=e(),transport:n=new c$,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:c,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new zxt,this.sendMessage=async(f,h)=>{var p,g,b,x;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let y;if("text"in f||"files"in f?y={parts:[...Array.isArray(f.files)?f.files:await Uxt(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:y=f,f.messageId!=null){const S=this.state.messages.findIndex(w=>w.id===f.messageId);if(S===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[S].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,S+1),this.state.replaceMessage(S,{...y,id:f.messageId,role:(g=y.role)!=null?g:"user",metadata:f.metadata})}else this.state.pushMessage({...y,id:(b=y.id)!=null?b:this.generateId(),role:(x=y.role)!=null?x:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const p=f==null?this.state.messages.length-1:this.state.messages.findIndex(g=>g.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolOutput=async({state:f="output-available",tool:h,toolCallId:p,output:g,errorText:b})=>this.jobExecutor.run(async()=>{var x,y;const S=this.state.messages,w=S[S.length-1];this.state.replaceMessage(S.length-1,{...w,parts:w.parts.map(C=>qR(C)&&C.toolCallId===p?{...C,state:f,output:g,errorText:b}:C)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(C=>qR(C)&&C.toolCallId===p?{...C,state:f,output:g,errorText:b}:C)),this.status!=="streaming"&&this.status!=="submitted"&&((x=this.sendAutomaticallyWhen)!=null&&x.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(y=this.lastMessage)==null?void 0:y.id})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var f;this.status!=="streaming"&&this.status!=="submitted"||(f=this.activeResponse)!=null&&f.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=s,this.state=o,this.onError=i,this.onToolCall=a,this.onFinish=c,this.onData=u,this.sendAutomaticallyWhen=d}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:s}){var o,i,a,c;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const p={state:Oxt({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};p.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=p;let g;if(e==="resume-stream"){const x=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(x==null){this.setStatus({status:"ready"});return}g=x}else g=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:p.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const b=x=>this.jobExecutor.run(()=>x({state:p.state,write:()=>{var y;this.setStatus({status:"streaming"}),p.state.message.id===((y=this.lastMessage)==null?void 0:y.id)?this.state.replaceMessage(this.state.messages.length-1,p.state.message):this.state.pushMessage(p.state.message)}}));await $xt({stream:Lxt({stream:g,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:b,onError:x=>{throw x}}),onError:x=>{throw x}}),this.setStatus({status:"ready"})}catch(p){if(d||p.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,p instanceof TypeError&&(p.message.toLowerCase().includes("fetch")||p.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&p instanceof Error&&this.onError(p),this.setStatus({status:"error",error:p})}finally{try{(i=this.onFinish)==null||i.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:d,isDisconnect:f,isError:h,finishReason:(o=this.activeResponse)==null?void 0:o.state.finishReason})}catch(p){console.error(p)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(c=this.lastMessage)==null?void 0:c.id,metadata:t,headers:n,body:r})}};function pfe({messages:e}){const t=e[e.length-1];if(!t||t.role!=="assistant")return!1;const n=t.parts.reduce((s,o,i)=>o.type==="step-start"?i:s,-1),r=t.parts.slice(n+1).filter(qR).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function Yxt(e,t){if(typeof e!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...o){clearTimeout(n);const i=Date.now(),a=i-r,c=t-a;c<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},c)}}var Gxt=Yxt;const Kxt=m.getDefaultExportFromCjs(Gxt);var mfe=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},jr=(e,t,n)=>(mfe(e,t,"read from private field"),n?n.call(e):t.get(e)),qa=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},gu=(e,t,n,r)=>(mfe(e,t,"write to private field"),t.set(e,n),n);function Zxt(e,t){return t!=null?Kxt(e,t):e}var Ai,lC,cC,Hx,Ux,Wx,Up,YR,GR,Xxt=class{constructor(e=[]){qa(this,Ai,void 0),qa(this,lC,"ready"),qa(this,cC,void 0),qa(this,Hx,new Set),qa(this,Ux,new Set),qa(this,Wx,new Set),this.pushMessage=t=>{gu(this,Ai,jr(this,Ai).concat(t)),jr(this,Up).call(this)},this.popMessage=()=>{gu(this,Ai,jr(this,Ai).slice(0,-1)),jr(this,Up).call(this)},this.replaceMessage=(t,n)=>{gu(this,Ai,[...jr(this,Ai).slice(0,t),this.snapshot(n),...jr(this,Ai).slice(t+1)]),jr(this,Up).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?Zxt(t,n):t;return jr(this,Hx).add(r),()=>{jr(this,Hx).delete(r)}},this["~registerStatusCallback"]=t=>(jr(this,Ux).add(t),()=>{jr(this,Ux).delete(t)}),this["~registerErrorCallback"]=t=>(jr(this,Wx).add(t),()=>{jr(this,Wx).delete(t)}),qa(this,Up,()=>{jr(this,Hx).forEach(t=>t())}),qa(this,YR,()=>{jr(this,Ux).forEach(t=>t())}),qa(this,GR,()=>{jr(this,Wx).forEach(t=>t())}),gu(this,Ai,e)}get status(){return jr(this,lC)}set status(e){gu(this,lC,e),jr(this,YR).call(this)}get error(){return jr(this,cC)}set error(e){gu(this,cC,e),jr(this,GR).call(this)}get messages(){return jr(this,Ai)}set messages(e){gu(this,Ai,[...e]),jr(this,Up).call(this)}};Ai=new WeakMap;lC=new WeakMap;cC=new WeakMap;Hx=new WeakMap;Ux=new WeakMap;Wx=new WeakMap;Up=new WeakMap;YR=new WeakMap;GR=new WeakMap;var Wp,QU=class extends qxt{constructor({messages:e,...t}){const n=new Xxt(e);super({...t,state:n}),qa(this,Wp,void 0),this["~registerMessagesCallback"]=(r,s)=>jr(this,Wp)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>jr(this,Wp)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>jr(this,Wp)["~registerErrorCallback"](r),gu(this,Wp,n)}};Wp=new WeakMap;function gfe({experimental_throttle:e,resume:t=!1,...n}={}){const r=v.useRef("chat"in n?n.chat:new QU(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new QU(n));const o="id"in n?n.id:null,i=v.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=v.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),c=v.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=v.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=v.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return v.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:a,setMessages:d,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:u,resumeStream:r.current.resumeStream,status:c,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function Qxt(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function Jxt(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function eyt(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function tyt(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function bfe(e){return e.map(r=>{const s=r.connectionType==="API"||r.connectionType==="S3"||r.connectionType==="S3Tables"?"DuckDb":r.connectionType;return r.datamodelName?{...r,databaseName:"",schemaName:"",tableName:"",connectionType:s,tableReferenceFormat:"dm.{table_name}"}:{...r,connectionType:s,tableReferenceFormat:tyt(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function xfe(e){var n,r;if(!e)return"";let t="";try{const s=JSON.parse((e==null?void 0:e.message)||"{}");t=((r=(n=s==null?void 0:s.error)==null?void 0:n.lastError)==null?void 0:r.message)||(s==null?void 0:s.error)||e.message}catch{t=e.message}return t}function uE(e,t){var n;if((n=e.sheets)!=null&&n.length)return t&&e.sheets.find(r=>r.id===t)||e.sheets[0]}function yfe(e,t,n){const r=uE(e,t);if(!r)return[];const s=o=>{var i;return{sourceCard:o,visibleCard:((i=n==null?void 0:n[o.id])==null?void 0:i.visibleCard)||o,...n!=null&&n[o.id]?{replacedCard:n[o.id]}:{}}};return(r.frames||[]).map(o=>_j(o)).filter(o=>o!==void 0).map(s)}function vfe(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).map(r=>({name:r.name,type:r.type,connectionId:r.connectionId,...r.label?{label:r.label}:{}}))}function nyt(e){return{id:(e==null?void 0:e.id)||"",name:(e==null?void 0:e.name)||"",label:(e==null?void 0:e.label)||(e==null?void 0:e.name)||"",...e!=null&&e.dataType?{dataType:e.dataType}:{},...e!=null&&e.aggregate?{aggregate:e.aggregate}:{},...e!=null&&e.granularity?{granularity:e.granularity}:{},...e!=null&&e.direction?{direction:e.direction}:{}}}function nm(e){return(e||[]).map(nyt)}function wfe(e){return nm([...(e==null?void 0:e.groupByColumns)||[],...(e==null?void 0:e.pivotByColumns)||[],...(e==null?void 0:e.detailColumns)||[]])}function u$(e){const t={operation:e.operation};return"value"in e&&e.value!==void 0&&(t.value=e.value),"values"in e&&Array.isArray(e.values)&&(t.values=e.values),t}function ryt(e,t,n){const r=new Map((e||[]).map(s=>[s.id,s]));return(t||[]).map(s=>{const o=r.get(s.filterId);return{filterId:s.filterId,label:(o==null?void 0:o.title)||s.label||s.name||s.filterId,...o!=null&&o.type?{type:o.type}:{},...o!=null&&o.column||s.name?{column:(o==null?void 0:o.column)||s.name}:{},...o!=null&&o.dataType?{dataType:o.dataType}:{},origin:n,...u$(s)}})}function syt(e){return(e||[]).map(t=>({filterId:t.filterId,label:t.label||t.name||t.filterId,...t.name?{column:t.name}:{},origin:"inline",...u$(t)}))}function Sfe(e,t){var n,r,s,o,i,a,c;return{filterId:t,label:((n=e.field)==null?void 0:n.label)||((r=e.field)==null?void 0:r.name)||t,...(s=e.field)!=null&&s.qualifiedFieldName||(o=e.field)!=null&&o.name?{column:((i=e.field)==null?void 0:i.qualifiedFieldName)||((a=e.field)==null?void 0:a.name)}:{},...(c=e.field)!=null&&c.dataType?{dataType:e.field.dataType}:{},origin:"interaction",operation:e.operator,...e.value!==void 0?{value:e.value}:{}}}function l2(e,t){return(e||[]).flatMap((n,r)=>(n.filters||[]).map((s,o)=>Sfe(s,`${t}:${r}:${o}`)))}function oyt(e){return!!e&&typeof e=="object"&&"field"in e&&"operator"in e}function iyt(e){return!!e&&typeof e=="object"&&"filterId"in e&&"operation"in e}function ayt(e){if(!e)return{dashboardFilterValues:[],interactionFilterValues:[]};const t=e.filter(iyt).map(r=>({filterId:r.filterId,label:r.label||r.name||r.filterId,...r.name?{column:r.name}:{},origin:"dashboard",...u$(r)})),n=e.filter(oyt).map((r,s)=>Sfe(r,`replaced-insight:${s}`));return{dashboardFilterValues:t,interactionFilterValues:n}}function lyt({card:e,interactionStates:t,currentDashboardId:n}){var c;if(!t)return[];const r=m.getClickFiltersForCardFromStates(e.id,t),s=t[m.DRILL_CONTEXT_CARD_ID],i=(s==null?void 0:s.targetDashboardId)===n&&(s==null?void 0:s.contextMode)!=="none"?(s==null?void 0:s.appliedClickFilters)||[]:[],a=((c=t[e.id])==null?void 0:c.breadcrumbs)??[];return[...r.flatMap((u,d)=>l2(u.filterGroups,`interaction:${u.sourceCardId||e.id}:${d}`)),...i.flatMap((u,d)=>l2(u.filterGroups,`global-interaction:${u.sourceCardId||e.id}:${d}`)),...a.flatMap((u,d)=>l2(u.sourceFilterGroups,`breadcrumb:${e.id}:${d}`))]}function Cfe(e){return e?{logicalOperator:e.logicalOperator,negate:e.negate,conditions:(e.conditions||[]).map(t=>{var n,r;return{field:((n=t.field)==null?void 0:n.label)||((r=t.field)==null?void 0:r.name)||"",operator:t.operator,value:t.value}}),groups:(e.groups||[]).map(t=>Cfe(t)).filter(Boolean)}:null}function Nfe(e){var n;const t=(n=e.python)==null?void 0:n.trim();return!!t&&t!==tF.trim()}function cyt(e){var t;return(t=e.sql)!=null&&t.trim()?"custom-sql":Nfe(e)?"custom-python":"config"}function kfe({sourceCard:e,card:t,replacedCard:n,dashboard:r,viewState:s,runtimeFilterValues:o,interactionStates:i,inlineFilterValuesMap:a}){const c=uE(r,s.selectedSheetId),u=(c==null?void 0:c.id)||s.selectedSheetId,{finalConfig:d}=fv({card:t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u,inlineFilterValuesMap:a}),f=dv({card:e||t,interactionStates:i,currentDashboardId:r.id,filters:r.filters,filterValues:o??s.activeFilters,selectedSheetId:u}),h=ayt(n==null?void 0:n.filters),p=!!n&&n.filters!==void 0;return{selectedSheetId:u,finalConfig:d,dashboardFilterValues:p?h.dashboardFilterValues:ryt(f.cardFilters,f.cardFilterValues,"dashboard"),inlineFilterValues:syt(a==null?void 0:a[t.id]),interactionFilterValues:p?h.interactionFilterValues:lyt({card:t,interactionStates:i,currentDashboardId:r.id})}}function uyt({sourceCard:e,visibleCard:t,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o,replacedCard:i,renderOrder:a}){const{finalConfig:c}=kfe({sourceCard:e,card:t,replacedCard:i,dashboard:n,viewState:r,interactionStates:s,inlineFilterValuesMap:o});return{cardId:e.id,...e.id!==t.id?{visibleCardId:t.id}:{},...i!=null&&i.insightId?{replacementInsightId:i.insightId}:{},title:t.title||"Untitled Card",type:t.type,renderOrder:a,metrics:nm(c.metricColumns),dimensions:wfe(c),selectedEntities:vfe(t)}}function dyt({activeFilters:e}){return Array.from(new Set((e||[]).map(t=>t.filterId)))}function JU({dashboard:e,selectedSheetId:t,activeFilters:n}){var s;const r=((s=uE(e,t??null))==null?void 0:s.id)||t||null;return{selectedSheetId:r,activeFilters:Ly(e.filters,n,r)}}function fyt({dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCards:s}){const o=uE(e,t.selectedSheetId),i=(o==null?void 0:o.id)||t.selectedSheetId,a=yfe(e,t.selectedSheetId,s),c=Nd(e.filters,i);return{dashboardId:e.id,dashboardTitle:e.title||"Untitled Dashboard",selectedSheetId:i,sheetTitle:(o==null?void 0:o.title)||"Untitled Sheet",cards:a.map(({sourceCard:u,visibleCard:d,replacedCard:f},h)=>uyt({sourceCard:u,visibleCard:d,dashboard:e,viewState:t,interactionStates:n,inlineFilterValuesMap:r,replacedCard:f,renderOrder:h})),availableFilters:c.map(u=>{var d,f;return{filterId:u.id,label:u.title,...u.type?{type:u.type}:{},scope:(d=u.applyToCardIds)!=null&&d.length||(f=u.excludeCardIds)!=null&&f.length?"card":"sheet"}}),activeFilterIds:dyt({activeFilters:t.activeFilters})}}function hyt({dashboard:e,viewState:t,cardId:n,runtimeFilterValues:r,interactionStates:s,inlineFilterValuesMap:o,replacedCards:i}){var w,C;const c=yfe(e,t.selectedSheetId,i).find(({sourceCard:N,visibleCard:k})=>N.id===n||k.id===n);if(!c)return{found:!1,cardId:n,selectedEntities:[],metrics:[],dimensions:[],comparison:null,cardFilters:null,effectiveDashboardFilters:[],activeInlineFilters:[],activeInteractionFilters:[],sortingOrGroupingSummary:{groupBy:[],pivotBy:[],sortBy:[]},notes:["Card not found in the current selected sheet."]};const{sourceCard:u,visibleCard:d,replacedCard:f}=c,{finalConfig:h,dashboardFilterValues:p,inlineFilterValues:g,interactionFilterValues:b}=kfe({sourceCard:u,card:d,replacedCard:f,interactionStates:s,dashboard:e,viewState:t,runtimeFilterValues:r,inlineFilterValuesMap:o}),{comparisonType:x,targetValue:y}=_Ye(h,d.type),S=cyt(d);return{found:!0,cardId:u.id,...u.id!==d.id?{visibleCardId:d.id}:{},...f!=null&&f.insightId?{replacementInsightId:f.insightId}:{},title:d.title,type:d.type,queryMode:S,...(w=d.sql)!=null&&w.trim()?{sql:d.sql.trim()}:{},...Nfe(d)?{python:(C=d.python)==null?void 0:C.trim()}:{},selectedEntities:vfe(d),metrics:nm(h.metricColumns),dimensions:wfe(h),comparison:x!=="none"?{type:x,...y!==void 0?{targetValue:y}:{}}:null,cardFilters:Cfe(h.filters),effectiveDashboardFilters:p,activeInlineFilters:g,activeInteractionFilters:b,sortingOrGroupingSummary:{groupBy:nm(h.groupByColumns),pivotBy:nm(h.pivotByColumns),sortBy:nm(h.sortByColumns)},notes:[...f?["This frame is currently showing a linked insight replacement."]:[],...S==="custom-sql"?["This card runs custom SQL."]:S==="custom-python"?["This card runs custom Python."]:[]]}}function qp(){return crypto.randomUUID()}function _fe(){return crypto.randomUUID()}function KR(e){return typeof(e==null?void 0:e.then)=="function"}async function pyt({replacedCards:e,apiServiceUrl:t,accessToken:n,queryClient:r}){const s=Object.entries(e);if(s.length===0||!n)return{};const o=await Promise.all(s.map(async([i,a])=>{const c=["resource-by-id",Xr.VISUAL,a.insightId];let u=r.getQueryData(c);if(!u)try{u=await r.fetchQuery({queryKey:c,queryFn:()=>m.getRequest(`${t}/management/v1/visuals/${a.insightId}`,n)})}catch{return null}const d=Yie(u);return d?[i,{insightId:a.insightId,visibleCard:d,filters:a.filters,contextMode:a.contextMode}]:null}));return Object.fromEntries(o.filter(i=>i!==null))}function myt({dynamicVisualMode:e="auto"}={}){var R;const{compiledAppearance:t}=m.useAppearance(),n=v.useMemo(()=>PL(t),[t]),r=v.useRef(n);v.useEffect(()=>{r.current=n},[n]);const{authToken:s,tokenProps:o}=Ct(),i=ns(),a=m.useDashboardStore(B=>B.dashboard.aiScopeTables),c=(R=Q0().data)==null?void 0:R.assistantProfileId,u=v.useRef(null),d=v.useRef(qp()),f=v.useRef(!1),h=v.useRef(!1),p=v.useRef(e);p.current=e;function g(){const B=m.useAIInteractionStore.getState(),z=m.useDashboardStore.getState(),U=Jie({overrides:B.dashboardEntitySelectionOverrides,dashboardId:z.dashboard.id,draftScopeKey:z.dashboardAssistantDraftScopeKey});return m.appendQualifiedEntityNameToAIContext(BKe({currentAIContext:B.currentAIContext,manualSelectedEntities:U.selectedEntities,hasManualOverride:U.hasManualOverride,dashboardAIContext:z.dashboard.aiContext,derivedSelectedSheetEntities:Qie(z.dashboard,z.selectedSheetId)}))}function b(){const B=m.useDashboardStore.getState();return{aiContext:g(),dashboardViewState:JU({dashboard:B.dashboard,selectedSheetId:B.selectedSheetId,activeFilters:B.filterValues})}}const{sendMessage:x,messages:y,setMessages:S,regenerate:w,status:C,addToolResult:N,error:k,stop:_,clearError:E}=gfe({transport:new c$({api:`${o.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${s==null?void 0:s.accessToken}`}),body:()=>{const B=m.useAIInteractionStore.getState();u.current||(u.current=b());const{aiContext:z,dashboardViewState:U}=u.current;return{assistantId:"dashboard-assistant",assistantProfileId:c,conversationId:d.current,assistantRequestId:_fe(),aiContext:z,dashboardViewState:U,dynamicVisualMode:p.current,dynamicVisualTheme:r.current,reasoningEffort:B.reasoningEffort,showReasoning:B.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:B,body:z})=>({body:{...z,messages:m.cleanupIncompleteMessages(B)}})}),onToolCall:T,sendAutomaticallyWhen:pfe,onFinish({message:B,isAbort:z,isDisconnect:U,isError:Y}){var O;h.current=!1,B!=null&&B.id&&((O=u.current)!=null&&O.aiContext)&&m.useAIInteractionStore.getState().actions.setAssistantMessageContext(B.id,u.current.aiContext),console.log(z?"[Dashboard Assistant] Stream aborted by user":U?"[Dashboard Assistant] Stream disconnected (network error)":Y?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully"),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]))},onError(B){var z;if(h.current=!1,B.name==="AbortError"||(z=B.message)!=null&&z.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)"),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]));return}console.error("[Dashboard Assistant] Stream error:",B),u.current=null,f.current&&(f.current=!1,d.current=qp(),S([]))}}),D=v.useCallback((...B)=>{h.current=!0;try{const z=x(...B);return KR(z)?z.catch(U=>{throw h.current=!1,U}):z}catch(z){throw h.current=!1,z}},[x]),j=v.useCallback((...B)=>{h.current=!0;try{const z=w(...B);return KR(z)?z.catch(U=>{throw h.current=!1,U}):z}catch(z){throw h.current=!1,z}},[w]),I=B=>{let z=!1;S(U=>{const Y=typeof B=="function"?B(U):B;if(Y.length===0){if(h.current)return f.current=!0,z=!0,U;f.current=!1,d.current=qp()}return Y}),z&&_()};async function T({toolCall:B}){var M,G;if(B.toolName==="getCurrentTableScope"){N({tool:B.toolName,toolCallId:B.toolCallId,output:{tables:bfe(a||[])}});return}const z=m.useDashboardStore.getState().dashboard,U=m.useDashboardStore.getState().inlineFilterValuesMap,Y=m.useInteractionStore.getState(),O=Y.interactionStates,K=await pyt({replacedCards:Y.replacedCards,apiServiceUrl:o.apiServiceUrl,accessToken:(s==null?void 0:s.accessToken)||"",queryClient:i}),q=JU({dashboard:z,selectedSheetId:m.useDashboardStore.getState().selectedSheetId,activeFilters:m.useDashboardStore.getState().filterValues});if(B.toolName==="getDashboardSynopsis"){N({tool:B.toolName,toolCallId:B.toolCallId,output:fyt({dashboard:z,viewState:q,interactionStates:O,inlineFilterValuesMap:U,replacedCards:K})});return}if(B.toolName==="getCardContext"){const L=((M=B.input)==null?void 0:M.cardId)||((G=B.args)==null?void 0:G.cardId)||"";N({tool:B.toolName,toolCallId:B.toolCallId,output:hyt({dashboard:z,viewState:q,cardId:L,runtimeFilterValues:m.useDashboardStore.getState().filterValues,interactionStates:O,inlineFilterValuesMap:U,replacedCards:K})})}}const F=!["ready","error"].includes(C),P=xfe(k);return{sendMessage:D,regenerate:j,isLoading:F,messages:y,setMessages:I,status:C,stop:_,errorMessage:P,clearError:E}}function jfe(){var u;const{authToken:e,tokenProps:t}=Ct(),n=(u=Q0().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=On({queryKey:["assistant-profile",n],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/assistant/${n}`,(e==null?void 0:e.accessToken)||""),enabled:r()});return{assistantProfile:s==null?void 0:s.assistantProfile,isLoading:o,isFetching:i,isError:a}}function Efe({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:l.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[l.jsxs("div",{className:"mb-3 flex items-center",children:[l.jsx(pq,{className:"mr-2 h-4 w-4 text-muted-foreground"}),l.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>l.jsx(m.Button,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function gyt({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=v.useRef(null),o=async a=>{const c=Array.from(a.target.files||[]);if(c.length===0)return;const u=ic-n;if(c.length>u){ut.error(`You can only attach ${ic} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=que(c);if(f.forEach(({file:h,error:p})=>{ut.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>Z3(p)));e(h)}catch(h){console.error("Failed to process files:",h),ut.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=ic}),l.jsx(m.Button,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=ic,title:n>=ic?`Maximum ${ic} files allowed`:"Attach files",children:l.jsx(Nq,{className:"h-4 w-4 text-muted-foreground"})})]})}function byt({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=v.useState(!1),a=v.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),c=v.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,g=f.clientY;(p<h.left||p>=h.right||g<h.top||g>=h.bottom)&&i(!1)},[]),u=v.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=v.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=ic-r;if(h.length>p){ut.error(`You can only attach ${ic} files per message. You have ${p} slot(s) remaining.`);return}const{valid:g,errors:b}=que(h);if(b.forEach(({file:x,error:y})=>{ut.error(`${x.name}: ${y}`)}),g.length>0)try{const x=await Promise.all(g.map(y=>Z3(y)));t(x),ut.success(`${x.length} file(s) attached successfully`)}catch(x){console.error("Failed to process files:",x),ut.error("Failed to process one or more files")}},[n,r,t]);return l.jsxs("div",{className:m.cn("relative",s),onDragEnter:a,onDragLeave:c,onDragOver:u,onDrop:d,children:[e,o&&!n&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-control border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2",children:[l.jsx(m.Upload,{className:"h-8 w-8 text-primary"}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:[ic-r," slot(s) available"]})]})})]})}function xyt(e,t,n){switch(e){case"none":return!1;case"include":return n.includes(t);case"exclude":return!n.includes(t);case"all":default:return!0}}function yyt({mode:e,currentDomainId:t,scopedDomainIds:n,hasSelectedEntities:r}){return e==="all"?!1:e==="none"?!!t||r:t?!xyt(e,t,n):r}function Dfe(e){const{tokenProps:t}=Ct(),n=m.useDashboardStore(c=>c.authToken)||e;m.useEditorStore(c=>c.selectedConnectionId),m.useEditorStore(c=>{var u,d;return(d=(u=c==null?void 0:c.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=On({queryKey:["semantic-domains"],queryFn:()=>m.getRequest(`${t.apiServiceUrl}/v1/domains`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)});return{isPending:s,error:a,semanticDomainsData:o,semanticDomains:(o==null?void 0:o.domains)||[],isSemanticDomainsLoading:i,isSemanticDomainsError:a,refetchSemanticDomains:r}}function vyt({domainAccess:e,search:t,scopeDomainId:n,selectedEntities:r,onSelectionChange:s}){const{semanticDomains:o,isSemanticDomainsLoading:i}=Dfe(),a=v.useMemo(()=>Syt(o,e),[o,e]),c=v.useMemo(()=>n?a.filter(d=>d.id===n):a,[a,n]);if(i&&c.length===0)return l.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading semantic domains…"});if(c.length===0)return null;const u=!!n;return l.jsxs("div",{children:[l.jsx(Ife,{label:"Semantic Domains"}),c.map(d=>l.jsx(wyt,{domain:d,search:t,forceExpanded:u,selectedEntities:r,onSelectionChange:s},d.id))]})}function wyt({domain:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:s}){const[o,i]=v.useState(!1),a=o||t.length>0||!!n,{datasets:c,isPending:u}=nNe(a?e.id:void 0),d=v.useMemo(()=>{if(!t)return c;const x=t.trim().toLowerCase();return c.filter(y=>`${y.label??""} ${y.name??""} ${y.description??""}`.toLowerCase().includes(x))},[c,t]),f=t.length>0&&d.length>0,h=o||f||!!n,p=c.length,g=v.useMemo(()=>d.filter(x=>r.some(y=>zr(y,c2(x)))).length,[d,r]),b=x=>{const y=c2(x),S=r.some(w=>zr(w,y));s(S?r.filter(w=>!zr(w,y)):[...r,y])};return t.length>0&&!f&&!u?null:l.jsxs("div",{children:[l.jsxs("button",{type:"button",onClick:()=>i(x=>!x),className:"flex w-full items-center gap-1.5 rounded-[4px] px-3 py-1.5 text-left transition-colors hover:bg-muted/50",children:[l.jsx(Mr,{className:m.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",h&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:e.label||e.name}),p>0&&l.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["· ",p," dataset",p===1?"":"s"," · curated"]}),l.jsx("span",{className:"ml-auto font-mono text-[10px] tabular-nums text-muted-foreground",children:g>0?g:""})]}),h&&l.jsx("ul",{className:"space-y-px pb-1",children:u&&c.length===0?l.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"Loading datasets…"}):d.length===0?l.jsx("li",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:"No datasets in this domain."}):d.map(x=>{const y=c2(x),S=r.some(w=>zr(w,y));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-start gap-2 rounded-[4px] px-9 py-1.5 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:S,onCheckedChange:()=>b(x),className:"mt-[3px] h-3.5 w-3.5 shrink-0"}),l.jsx(ei,{className:"mt-[3px] h-3 w-3 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground",children:x.label||x.name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:x.type==="virtual"?"virtual":"dataset"})]}),x.description&&l.jsx("p",{className:"mt-0.5 text-[11px] leading-[1.4] text-muted-foreground",children:x.description})]})]})},x.id)})})]})}function Ife({label:e}){return l.jsx("div",{className:"px-3 pb-1.5 pt-2.5",children:l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e})})}function Syt(e,t){if(!t||t.mode==="all")return e;const n=new Set(t.domainIds??[]);return t.mode==="include"?e.filter(r=>n.has(r.id)):t.mode==="exclude"?e.filter(r=>!n.has(r.id)):[]}function c2(e){return{id:e.id,datasetType:e.type,name:e.name||e.table,label:e.label,domainId:e.domainId,description:e.description,database:e.database,schema:e.schema,table:e.table,type:"dataset",connectionId:e.connectionId,connectionType:e.connectionType,dialect:e.dialect,datamodelId:e.datamodelId,sql:e.sql}}function Cyt({search:e,scopeConnectionId:t,selectedEntities:n,onSelectionChange:r}){const{connections:s,isConnectionsLoading:o}=Xc(),i=v.useMemo(()=>t?s.filter(c=>c.id===t):s,[s,t]);if(o&&i.length===0)return l.jsx("div",{className:"px-3 py-4 text-[11px] text-muted-foreground",children:"Loading connections…"});if(i.length===0)return null;const a=!!t;return l.jsxs("div",{children:[l.jsx(Ife,{label:"Direct Sources"}),i.map(c=>l.jsx(Nyt,{connection:c,search:e,forceExpanded:a,selectedEntities:n,onSelectionChange:r},c.id))]})}function Nyt({connection:e,search:t,forceExpanded:n,selectedEntities:r,onSelectionChange:s}){var g;const[o,i]=v.useState(!1),a=o||t.length>0||!!n,c=((g=e.capabilities)==null?void 0:g.path)??[],u=c.includes("database"),d=c.includes("schema"),f=e.type==="upload",h=e.type==="url",p=v.useMemo(()=>r.filter(b=>b.connectionId===e.id).length,[r,e.id]);return l.jsxs("div",{className:"border-b border-border/60 last:border-b-0",children:[l.jsxs("button",{type:"button",onClick:()=>i(b=>!b),className:"flex w-full items-center gap-2 px-4 py-1.5 text-left transition-colors hover:bg-muted/40",children:[l.jsx(Mr,{className:m.cn("h-3 w-3 shrink-0 text-muted-foreground transition-transform",a&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate text-[13px] font-medium text-foreground/90",children:e.name}),l.jsxs("span",{className:"truncate text-[11px] text-muted-foreground",children:["· ",e.type]}),l.jsx("span",{className:"ml-auto shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground",children:p>0?p:""})]}),a&&l.jsxs(l.Fragment,{children:[f?l.jsx(kyt,{connection:e,selectedEntities:r,onSelectionChange:s}):h?l.jsx(_yt,{connection:e,selectedEntities:r,onSelectionChange:s}):u?l.jsx(jyt,{connection:e,requiresSchema:d,search:t,selectedEntities:r,onSelectionChange:s}):d?l.jsx(Tfe,{connection:e,databaseName:"",search:t,selectedEntities:r,onSelectionChange:s}):l.jsx(d$,{connection:e,databaseName:"",schemaName:"",search:t,selectedEntities:r,onSelectionChange:s}),!f&&!h&&l.jsx(Eyt,{connection:e,search:t,selectedEntities:r,onSelectionChange:s})]})]})}function kyt({connection:e,selectedEntities:t,onSelectionChange:n}){const r=`upload-source-${e.id}`,s=t.filter(a=>a.connectionId===e.id&&(a.type==="upload"||a.type==="file")),o=a=>{if(!(a!=null&&a.length))return;const c=Array.from(a).map(u=>({id:`file-${Date.now()}-${Math.random()}`,name:u.name,type:"upload",connectionId:e.id,connectionType:e.type,label:u.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:u.name,file:u}));n([...t,...c])},i=a=>{n(t.filter(c=>!("id"in c&&c.id===a&&c.connectionId===e.id&&(c.type==="upload"||c.type==="file"))))};return l.jsxs("div",{className:"space-y-2 px-8 py-2",children:[l.jsxs("div",{className:"rounded-[6px] border border-dashed border-border bg-muted/20 p-4 text-center",children:[l.jsx(m.Upload,{className:"mx-auto mb-2 h-5 w-5 text-muted-foreground"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Add CSV, JSON, or Excel files."}),l.jsx("input",{id:r,type:"file",multiple:!0,className:"hidden",onChange:a=>o(a.target.files),accept:".csv,.json,.xlsx,.xls"}),l.jsx(m.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2 h-7 text-[12px]",onClick:()=>{var a;return(a=document.getElementById(r))==null?void 0:a.click()},children:"Select files"})]}),s.length>0&&l.jsx("ul",{className:"space-y-1",children:s.map(a=>l.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[l.jsx(vi,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px]",children:a.originalName||a.name}),l.jsx("button",{type:"button","aria-label":`Remove ${a.originalName||a.name}`,onClick:()=>i(a.id),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]},a.id))})]})}function _yt({connection:e,selectedEntities:t,onSelectionChange:n}){const[r,s]=v.useState(""),[o,i]=v.useState(""),[a,c]=v.useState("api"),u=t.filter(h=>h.connectionId===e.id&&h.type==="url"),d=()=>{const h=r.trim(),p=o.trim();if(!h||!p)return;const g={id:`url-${Date.now()}-${Math.random()}`,name:h,type:"url",connectionId:e.id,connectionType:e.type,label:h,description:`URL source of type ${a}`,originalName:h,url:p,sourceType:a};n([...t,g]),s(""),i(""),c("api")},f=h=>{n(t.filter(p=>!("id"in p&&p.id===h&&p.connectionId===e.id&&p.type==="url")))};return l.jsxs("div",{className:"space-y-2 px-8 py-2",children:[l.jsxs("div",{className:"space-y-2 rounded-[6px] border border-border bg-muted/20 p-3",children:[l.jsx(m.Input,{value:r,onChange:h=>s(h.target.value),placeholder:"Source name",className:"h-7 text-[12px]"}),l.jsx(m.Input,{value:o,onChange:h=>i(h.target.value),placeholder:"https://api.example.com/data",className:"h-7 text-[12px]"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("select",{value:a,onChange:h=>c(h.target.value),className:"h-7 flex-1 rounded-control border border-input bg-background px-2 text-[12px]",children:[l.jsx("option",{value:"api",children:"API endpoint"}),l.jsx("option",{value:"csv",children:"CSV file"}),l.jsx("option",{value:"json",children:"JSON file"})]}),l.jsxs(m.Button,{type:"button",size:"sm",className:"h-7 text-[12px]",disabled:!r.trim()||!o.trim(),onClick:d,children:[l.jsx(dr,{className:"mr-1 h-3 w-3"}),"Add"]})]})]}),u.length>0&&l.jsx("ul",{className:"space-y-1",children:u.map(h=>l.jsxs("li",{className:"flex items-center gap-2 rounded-[5px] border border-border bg-background px-2 py-1.5",children:[l.jsx(gg,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"truncate text-[12px]",children:h.name}),l.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:h.url})]}),l.jsx("button",{type:"button","aria-label":`Remove ${h.name}`,onClick:()=>f(h.id),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]},h.id))})]})}function jyt({connection:e,requiresSchema:t,search:n,selectedEntities:r,onSelectionChange:s}){var a;const o=dE("/v1/databases",{connection_id:e.id},["databases",e.id]);if(o.isLoading)return l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading databases…"});const i=((a=o.data)==null?void 0:a.databases)??[];return i.length===0?l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No databases."}):l.jsx("div",{children:i.map(c=>l.jsx(Mfe,{label:c.database_name,indentLevel:1,search:n,renderChildren:u=>u&&(t?l.jsx(Tfe,{connection:e,databaseName:c.database_name,search:n,selectedEntities:r,onSelectionChange:s}):l.jsx(d$,{connection:e,databaseName:c.database_name,schemaName:"",search:n,selectedEntities:r,onSelectionChange:s}))},c.database_name))})}function Tfe({connection:e,databaseName:t,search:n,selectedEntities:r,onSelectionChange:s}){var a;const o=dE("/v1/schemas",{connection_id:e.id,database_name:t||"NA"},["schemas",e.id,t],!!e.id);if(o.isLoading)return l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"Loading schemas…"});const i=((a=o.data)==null?void 0:a.schemas)??[];return i.length===0?l.jsx("div",{className:"px-8 py-1.5 text-[11px] text-muted-foreground",children:"No schemas."}):l.jsx("div",{children:i.map(c=>l.jsx(Mfe,{label:c.schema_name,indentLevel:t?2:1,search:n,renderChildren:u=>u&&l.jsx(d$,{connection:e,databaseName:t,schemaName:c.schema_name,search:n,selectedEntities:r,onSelectionChange:s})},c.schema_name))})}function d$({connection:e,databaseName:t,schemaName:n,search:r,selectedEntities:s,onSelectionChange:o}){const i=dE("/v1/tables",{connection_id:e.id,database_name:t||void 0,schema_name:n||void 0},["tables",e.id,t,n]),a=v.useMemo(()=>{var f;const u=((f=i.data)==null?void 0:f.tables)??[];if(!r)return u;const d=r.trim().toLowerCase();return u.filter(h=>h.table_name.toLowerCase().includes(d))},[i.data,r]);if(i.isLoading)return l.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"Loading tables…"});if(a.length===0)return r?null:l.jsx("div",{className:"px-10 py-1.5 text-[11px] text-muted-foreground",children:"No tables."});const c=(u,d)=>{const f={connectionId:e.id,connectionType:e.type,type:"table",dialect:e.dialect,database:t||void 0,schema:n||void 0,name:u,dbObjectType:d==null?void 0:d.toLowerCase()},h=s.some(p=>zr(p,f));o(h?s.filter(p=>!zr(p,f)):[...s,f])};return l.jsx("ul",{children:a.map(u=>{var h;const d={connectionId:e.id,connectionType:e.type,type:"table",dialect:e.dialect,database:t||void 0,schema:n||void 0,name:u.table_name,dbObjectType:(h=u.table_type)==null?void 0:h.toLowerCase()},f=s.some(p=>zr(p,d));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-center gap-2.5 py-1.5 pl-12 pr-4 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:f,onCheckedChange:()=>c(u.table_name,u.table_type),className:"h-3.5 w-3.5 shrink-0"}),l.jsx(m.Table2,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"flex min-w-0 flex-1 items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:u.table_name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:u.table_type??"table"})]})]})},u.table_name)})})}function Eyt({connection:e,search:t,selectedEntities:n,onSelectionChange:r}){const s=dE("/v1/datamodels",{connection_id:e.id},["datamodels",e.id]),o=v.useMemo(()=>{var u;const a=((u=s.data)==null?void 0:u.datamodels)??[];if(!t)return a;const c=t.trim().toLowerCase();return a.filter(d=>`${d.label??""} ${d.name??""} ${d.description??""}`.toLowerCase().includes(c))},[s.data,t]);if(s.isLoading||o.length===0)return null;const i=a=>{const c={id:a.id,name:a.name,label:a.label||"",description:a.description||"",connectionId:e.id,connectionType:e.type,type:"model",dialect:a.dialect??e.dialect,database:a.database||"",schema:a.schema||""},u=n.some(d=>zr(d,c));r(u?n.filter(d=>!zr(d,c)):[...n,c])};return l.jsxs("div",{children:[l.jsx("div",{className:"px-8 pb-1 pt-2",children:l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data models"})}),l.jsx("ul",{children:o.map(a=>{const c={id:a.id,name:a.name,label:a.label||"",description:a.description||"",connectionId:e.id,connectionType:e.type,type:"model",dialect:a.dialect??e.dialect,database:a.database||"",schema:a.schema||""},u=n.some(d=>zr(d,c));return l.jsx("li",{children:l.jsxs("label",{className:"flex cursor-pointer items-start gap-2.5 py-1.5 pl-12 pr-4 transition-colors hover:bg-muted/40",children:[l.jsx(Ln,{checked:u,onCheckedChange:()=>i(a),className:"mt-[2px] h-3.5 w-3.5 shrink-0"}),l.jsx(sme,{className:"mt-[2px] h-3.5 w-3.5 shrink-0 text-muted-foreground",strokeWidth:1.75}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"truncate text-[13px] text-foreground/90",children:a.label||a.name}),l.jsx("span",{className:"shrink-0 font-mono text-[10px] uppercase tracking-[0.06em] text-muted-foreground/70",children:"model"})]}),a.description&&l.jsx("p",{className:"mt-0.5 line-clamp-2 text-[11px] leading-[1.4] text-muted-foreground",children:a.description})]})]})},a.id)})})]})}function Mfe({label:e,indentLevel:t,search:n,renderChildren:r}){const[s,o]=v.useState(!1),i=s||n.length>0,a=t===1?"pl-8":"pl-10";return l.jsxs("div",{children:[l.jsxs("button",{type:"button",onClick:()=>o(c=>!c),className:m.cn("flex h-6 w-full items-center gap-1.5 pr-4 text-left transition-colors hover:bg-muted/40",a),children:[l.jsx(Mr,{className:m.cn("h-2.5 w-2.5 shrink-0 text-muted-foreground transition-transform",i&&"rotate-90"),strokeWidth:1.75}),l.jsx("span",{className:"truncate font-mono text-[11px] text-muted-foreground",children:e})]}),r(i)]})}function dE(e,t,n,r=!0){const{tokenProps:s}=Ct(),o=m.useDashboardStore(a=>a.authToken),i=v.useMemo(()=>Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0)),[t]);return On({queryKey:n,queryFn:()=>m.getRequest(`${s.apiServiceUrl}${e}`,(o==null?void 0:o.accessToken)||"",i),enabled:r&&!!(o!=null&&o.accessToken)&&Object.values(i).every(a=>a.length>0)})}function eW(e){return e.type==="dataset"&&e.label||e.name}function Dyt({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:l.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>l.jsxs("span",{className:"inline-flex items-center gap-1 rounded-control border border-input bg-muted/50 py-0.5 pl-1.5 pr-0.5 text-[11px] text-foreground/80",children:[l.jsx("span",{className:"max-w-[180px] truncate",children:eW(n)}),l.jsx("button",{type:"button",onClick:s=>{s.stopPropagation(),t(n)},"aria-label":`Remove ${eW(n)}`,className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-2.5 w-2.5"})})]},`${n.type}-${n.name}-${r}`))})}function tW(e){const t=new Set;for(const n of e||[])"domainId"in n&&typeof n.domainId=="string"&&t.add(n.domainId);if(t.size===1)return[...t][0]}function u2(e){if(e!=null&&e.length)return e.every(t=>t.type==="dataset")?"semanticDomain":e.every(t=>t.type==="url")?"url":e.every(t=>t.type==="upload"||t.type==="file")?"upload":"database"}function f$({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s,onSaveSelectedEntities:o,saveAsDashboardDefault:i=!1}){var ue,ve;const{tokenProps:a}=Ct(),c=a.config,u=a.semanticDomainAccess||bhe.DEFAULT_SEMANTIC_DOMAIN_ACCESS,[d,f]=v.useState([]),[h,p]=v.useState(void 0),[g,b]=v.useState(""),[x,y]=v.useState("all"),[S,w]=v.useState(void 0),C=v.useRef(!1),{updateDataSource:N}=m.useEditorActions(),k=m.useDashboardStore(xe=>xe.isVisualEditing),_=m.useDashboardStore(xe=>xe.dashboard.aiContext),{setAiContext:E}=m.useDashboardActions(),D=u.mode,j=(c==null?void 0:c.showDirectSource)!==!1,I=D==="include"||D==="exclude"||!j,T=D!=="all",F=j&&!I,P=I?"semanticDomain":n.mode,R=r==="dataSource"&&!j,B=D==="include"&&(((ue=u.domainIds)==null?void 0:ue.length)||0)===1?(ve=u.domainIds)==null?void 0:ve[0]:void 0,z=v.useCallback(xe=>{C.current=!0,N({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:xe,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...xe!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,N]),U=v.useCallback(xe=>{N({...n,...xe})},[n,N]),Y=v.useCallback(xe=>{if(r==="aiContext"){"semanticDomainId"in xe&&p(xe.semanticDomainId);return}U(xe)},[r,U]),O=r==="aiContext"?h:n.semanticDomainId;r==="aiContext"&&{...n},v.useEffect(()=>{if(r==="aiContext"&&!e)return;if(I&&n.mode!=="semanticDomain"&&r==="dataSource"){z("semanticDomain");return}if(!T||P!=="semanticDomain")return;const xe=O,ke=u.domainIds??[],se=r==="aiContext"?d:n.selectedEntities,be=((se==null?void 0:se.length)??0)>0,Ce=((d==null?void 0:d.length)??0)>0;yyt({mode:D,currentDomainId:xe,scopedDomainIds:ke,hasSelectedEntities:be})&&(r==="dataSource"?U({semanticDomainId:void 0,selectedEntities:[]}):p(void 0),Ce&&f([]))},[I,T,P,n.mode,O,n.selectedEntities,r,h,d,e,u.domainIds,D,j,U,z]),v.useEffect(()=>{B&&!O&&Y({semanticDomainId:B})},[B,O,Y]),v.useEffect(()=>{if(!e){C.current=!1,b(""),w(void 0),y(I?"semantic":"all");return}if(C.current)return;f([...s||[]]);const xe=r==="aiContext"?tW(s):void 0;p(n.semanticDomainId||xe),w(u2(s))},[e,r,s,n.semanticDomainId,I]);const K=xe=>{C.current=!0,f(d.filter(ke=>!zr(ke,xe)))},q=v.useCallback((xe,ke)=>{C.current=!0,f(xe),w(ke??u2(xe))},[]),M=()=>{var ke,se;if(r==="aiContext"){if(k&&N(n),i){const be={..._,selectedEntities:d,mode:d.length>0?"fixed":"auto"};E(be)}o==null||o(d),t(!1);return}const xe=u2(d)??S??P;if(xe==="semanticDomain"){const be=tW(d)||h||n.semanticDomainId,Ce=((ke=d==null?void 0:d[0])==null?void 0:ke.connectionId)||n.connectionId,ge=((se=d==null?void 0:d[0])==null?void 0:se.connectionType)||n.connectionType;N({...n,mode:"semanticDomain",semanticDomainId:be,connectionId:Ce,connectionType:ge,selectedEntities:d})}else if(xe==="upload"||xe==="url"){const be=d==null?void 0:d[0];N({...n,mode:xe,semanticDomainId:void 0,connectionId:(be==null?void 0:be.connectionId)||n.connectionId,connectionType:(be==null?void 0:be.connectionType)||n.connectionType,selectedEntities:d})}else{const be=d==null?void 0:d[0];N({...n,mode:"database",semanticDomainId:void 0,connectionId:(be==null?void 0:be.connectionId)||n.connectionId,connectionType:(be==null?void 0:be.connectionType)||n.connectionType,selectedEntities:d})}t(!1)},{semanticDomains:G}=Dfe(),{connections:L}=Xc(),$=xe=>{y(xe),xe==="semantic"||xe.startsWith("domain:")?n.mode!=="semanticDomain"&&z("semanticDomain"):(xe==="direct"||xe.startsWith("conn:"))&&n.mode==="semanticDomain"&&z("database")},V=x.startsWith("domain:"),H=x.startsWith("conn:"),A=V?x.slice(7):void 0,W=H?x.slice(5):void 0,X=!F||x==="all"||x==="semantic"||V,Z=j&&!I&&(x==="all"||x==="direct"||H),J=((s==null?void 0:s.length)??0)>0,re=d.length===0&&!J,fe=d.length===0&&J?"Clear":"Add",de=r==="aiContext"?"Data context":R?"Select dataset":"Add data",Se=r==="aiContext"?"Set the overall data scope for the dashboard":R?"Choose a curated dataset to analyze":"Search your semantic domains and connections";return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{showCloseButton:!1,className:"flex h-[560px] w-[620px] max-w-[620px] flex-col gap-0 overflow-hidden rounded-[6px] border border-border bg-popover p-0",children:[l.jsx(m.VisuallyHidden,{children:l.jsx(go,{children:de})}),l.jsxs("div",{className:"flex items-start justify-between border-b border-border px-4 py-2.5",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-[14px] font-semibold text-foreground",children:de}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:Se})]}),l.jsx("button",{type:"button",onClick:()=>t(!1),"aria-label":"Close",className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3.5 w-3.5"})})]}),l.jsxs("div",{className:"border-b border-border px-4 py-2.5",children:[l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[l.jsx(Ws,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("input",{type:"text",value:g,onChange:xe=>b(xe.target.value),placeholder:"Search datasets, tables, views, models",className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none"}),g&&l.jsx("button",{type:"button",onClick:()=>b(""),"aria-label":"Clear search",className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),F&&l.jsx("div",{className:"-mx-4 mt-2 overflow-x-auto px-4 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:l.jsxs("div",{className:"flex w-max items-center gap-1",children:[l.jsx(ux,{label:"All",active:x==="all",onClick:()=>$("all")}),(G.length>0||L.length>0)&&l.jsxs(l.Fragment,{children:[l.jsx(ux,{label:"Semantic",active:x==="semantic",onClick:()=>$("semantic")}),l.jsx(ux,{label:"Direct",active:x==="direct",onClick:()=>$("direct")}),l.jsx("span",{className:"shrink-0 px-0.5 text-muted-foreground/50",children:"·"})]}),G.map(xe=>l.jsx(ux,{label:xe.label||xe.name,active:x===`domain:${xe.id}`,onClick:()=>$(`domain:${xe.id}`)},`domain:${xe.id}`)),L.map(xe=>l.jsx(ux,{label:xe.name,active:x===`conn:${xe.id}`,onClick:()=>$(`conn:${xe.id}`)},`conn:${xe.id}`))]})})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[X&&l.jsx(vyt,{domainAccess:u,search:g,scopeDomainId:A,selectedEntities:d,onSelectionChange:xe=>q(xe,"semanticDomain")}),Z&&l.jsx(Cyt,{search:g,scopeConnectionId:W,selectedEntities:d,onSelectionChange:xe=>q(xe)})]}),l.jsxs("div",{className:"flex flex-col gap-0.5 border-t border-border px-4 py-2.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[l.jsx("span",{children:"Selected"}),l.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["· ",d.length]})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("button",{type:"button",onClick:()=>t(!1),className:"inline-flex h-7 items-center rounded-control px-2.5 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:"Cancel"}),l.jsxs("button",{type:"button",onClick:M,disabled:re,className:m.cn("inline-flex h-7 items-center gap-1.5 rounded-control bg-primary px-2.5 text-[12px] font-medium text-primary-foreground transition-colors hover:bg-primary/90",re&&"cursor-not-allowed opacity-50 hover:bg-primary"),children:[l.jsx("span",{children:fe}),d.length>0&&l.jsxs("span",{className:"font-mono tabular-nums text-primary-foreground/70",children:["· ",d.length]})]})]})]}),d.length>0&&l.jsx(Dyt,{selectedEntities:d,onDeselectEntity:K})]})]})})}function ux({label:e,active:t,onClick:n}){return l.jsx("button",{type:"button",onClick:n,"aria-pressed":t,className:m.cn("inline-flex h-6 shrink-0 items-center whitespace-nowrap rounded-control px-2 text-[11px] font-medium transition-colors",t?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:e})}function xk(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return l.jsx(vF,{className:r});case"view":return l.jsx(tv,{className:r});case"materialized view":return l.jsx(ume,{className:r});case"model":return l.jsx(nv,{className:r});case"file":return l.jsx(vi,{className:r});case"dataset":return l.jsx(ei,{className:r});case"upload":return l.jsx(m.Upload,{className:r});case"url":return l.jsx(hF,{className:r});default:return l.jsx(gg,{className:r})}}const ZR=e=>e.name||e.name,Iyt=e=>{const t=ZR(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"font-medium",children:t}),n&&l.jsx("div",{className:"text-sm text-muted-foreground",children:n}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function Tyt({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r,className:s}){const[o,i]=v.useState(!1),a=e.length>0;e.length,t.length,e.length<t.length;const c=e.length>=3?e.slice(0,2):e,u=e.length>=3?e.slice(2):[],d=u.length>0;return l.jsx(m.TooltipProvider,{children:l.jsx("div",{className:s,children:a&&l.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.map((f,h)=>{const p="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs(m.Tooltip,{children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsxs(Yr,{variant:"secondary",className:"group relative h-6 cursor-pointer gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors",children:[xk(f.type,{size:"h-3 w-3"}),l.jsx("span",{className:"max-w-24 truncate",children:ZR(f)}),l.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>n(f),children:l.jsx(m.X,{className:"h-3 w-3"})})]})}),l.jsx(m.TooltipContent,{side:"top",className:"max-w-xs",children:Iyt(f)})]},p)}),d&&l.jsxs(m.Tooltip,{open:o,onOpenChange:i,children:[l.jsx(m.TooltipTrigger,{asChild:!0,children:l.jsxs(Yr,{variant:"secondary",className:"flex h-6 cursor-pointer items-center gap-1.5 rounded-control px-2 text-[11px] font-medium transition-colors hover:bg-secondary/80",onClick:()=>i(!0),children:[l.jsx(ja,{className:"h-3 w-3"}),l.jsxs("span",{children:[u.length," more"]}),l.jsx("button",{className:"rounded-control p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",onClick:()=>r(u),children:l.jsx(m.X,{className:"h-3 w-3"})})]})}),l.jsx(m.TooltipContent,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),l.jsx("div",{className:"space-y-2",children:u.map(f=>{const h="id"in f?f.id:`${f.connectionId}-${f.name}`;return l.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:xk(f.type,{size:"h-3 w-3"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium",children:ZR(f)}),l.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[f.type," ",f.database?`• ${f.database}`:""]})]})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(f),u.length===1&&i(!1)},children:l.jsx(m.X,{className:"h-3 w-3"})})]},h)})})]})})]})]})})})}const Afe=Q.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[l.jsx(Ws,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(bo.Input,{ref:n,className:m.cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Afe.displayName=bo.Input.displayName;const bS=e=>e.label||(e==null?void 0:e.name),nW=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function Myt({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:c,onAddContext:u}){const{tokenProps:d}=Ct(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=v.useState(""),[g,b]=v.useState(""),x=s.filter(k=>{if(!h)return!0;const _=bS(k).toLowerCase(),E=(nW(k)||"").toLowerCase(),D=h.toLowerCase();return _.includes(D)||E.includes(D)});v.useEffect(()=>{e||(p(""),b(""))},[e]),v.useEffect(()=>{x.length>0&&!g&&b(bS(x[0]))},[x,g]);const y=()=>{if(!g)return;const k=x.find(_=>bS(_)===g);k&&(o.some(E=>"id"in k&&"id"in E?k.id===E.id:k.name===E.name&&k.connectionId===E.connectionId)||t(k),i(k),r())},S=k=>{(k.key==="Tab"||k.key==="Enter")&&(k.preventDefault(),y())};if(!e)return null;const w=k=>o.some(_=>"id"in k&&"id"in _?k.id===_.id:k.name===_.name&&k.connectionId===_.connectionId),C=o.length===s.length,N=o.length>0;return l.jsx(l.Fragment,{children:l.jsxs(Pj,{shouldFilter:!1,value:g,onValueChange:b,onKeyDown:S,children:[s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[l.jsx(Afe,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),u==null||u()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[l.jsx(dr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&l.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[l.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),a==null||a()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},disabled:C,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),N&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),c==null||c()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[l.jsx(m.X,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),l.jsxs(Oj,{className:"min-h-60",children:[l.jsx(Lj,{children:l.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[l.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&l.jsxs(m.Button,{onClick:k=>{k.preventDefault(),k.stopPropagation(),u==null||u()},onMouseDown:k=>{k.preventDefault(),k.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[l.jsx(dr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),l.jsx($j,{children:x.map((k,_)=>{const E=w(k),D="id"in k?k.id:`${k.connectionId}-${k.name}`,j=bS(k);return l.jsxs(zj,{value:j,onSelect:()=>{E?n==null||n(k):t(k)},onMouseDown:I=>{I.preventDefault(),I.stopPropagation()},className:m.cn("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[l.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:xk(k.type)}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate font-medium",children:j}),l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:nW(k)})]}),E&&l.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:l.jsx(m.Check,{className:"h-3 w-3 text-background"})})]},D)})})]})]})})}function XR({mode:e="full",compact:t=!1,inlineLayout:n=!1,inlineTriggerFirst:r=!1,syncOnOpen:s=!1,open:o,onOpenChange:i,onEntityMention:a,onEntityRemoved:c,onEntitiesRemoved:u,onSelectionChange:d,className:f,triggerClassName:h,triggerVariant:p="secondary",triggerLabel:g="Add entity",triggerIconOnly:b=!0,assistantType:x}){const[y,S]=v.useState(!1),[w,C]=v.useState(!1),N=o??y,k=o!==void 0,_=v.useRef(!1),D=m.useEditorStore(A=>A.card.dataSource)??z0,{selectedEntities:j,availableEntities:I,syncWithGlobalContext:T,setSelectedEntities:F,applyDashboardDefaultEntities:P,isEntitySelected:R}=jj(x),B=e==="full"||e==="display",z=e==="full"||e==="trigger",U=v.useMemo(()=>b&&j.length>0?`Add entity (${j.length})`:g,[j.length,b,g]);v.useEffect(()=>{N&&!_.current&&s&&T(),_.current=N},[N,s,T]);const Y=v.useCallback(A=>{k||S(A),i==null||i(A)},[k,i]),O=v.useCallback(A=>{const W=j.filter(X=>!zr(X,A));F(W),c==null||c(A),d==null||d(W)},[c,d,j,F]),K=v.useCallback(A=>{if(A.length===0)return;const W=j.filter(X=>!A.some(Z=>zr(X,Z)));F(W),u==null||u(A),d==null||d(W)},[u,d,j,F]),q=v.useCallback(A=>{const W=R(A)?j.filter(X=>!zr(X,A)):[...j,A];F(W),d==null||d(W)},[R,d,j,F]),M=v.useCallback(()=>{F(I),d==null||d(I)},[I,d,F]),G=v.useCallback(()=>{F([]),d==null||d([])},[d,F]),L=v.useCallback(A=>{x==="dashboard"?P():F(A),d==null||d(A)},[P,x,d,F]),$=v.useCallback(A=>{const W=j.some(X=>zr(X,A))?j:[...j,A];F(W),a==null||a(A),d==null||d(W),Y(!1)},[a,d,j,Y,F]),V=B?l.jsx(Tyt,{className:m.cn(n?"contents":"space-y-2"),entities:j,availableEntities:I,onRemoveEntity:O,onRemoveEntities:K}):null,H=z?l.jsxs(l.Fragment,{children:[l.jsxs(m.Popover,{open:N,onOpenChange:Y,children:[l.jsx(m.PopoverTrigger,{asChild:!0,children:l.jsxs(m.Button,{variant:p,size:"xs",className:m.cn(t&&"h-6 gap-1.5 px-2 text-[11px] font-medium",h),title:g,children:[l.jsx(QW,{className:"h-3 w-3 text-muted-foreground"}),!b&&l.jsx("span",{children:U})]})}),l.jsx(m.PopoverContent,{className:m.cn("w-80 p-0",t&&"w-72"),align:"start",side:"top",sideOffset:8,onOpenAutoFocus:A=>A.preventDefault(),children:l.jsx(Myt,{isOpen:!0,onSelect:q,onDeselect:q,onClose:()=>Y(!1),availableEntities:I,selectedEntities:j,onTabComplete:$,onSelectAll:M,onRemoveAll:G,onAddContext:()=>{Y(!1),C(!0)}})})]}),l.jsx(f$,{incomingSelectedEntities:j,open:w,onOpenChange:C,dataSource:D,dialogMode:"aiContext",onSaveSelectedEntities:L,saveAsDashboardDefault:x==="dashboard"})]}):null;return l.jsx("div",{className:m.cn(n?"flex flex-wrap items-center gap-1":"",!n&&B?"space-y-2":"",f),children:n&&r?l.jsxs(l.Fragment,{children:[H,V]}):l.jsxs(l.Fragment,{children:[V,H]})})}const h$=v.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:c},u)=>{const[d,f]=v.useState(!1),h=v.useRef(null),{queueMessage:p}=m.useQueueActions(),{addFileAttachment:g,removeFileAttachment:b,clearFileAttachments:x}=m.useFileActions(),y=m.useFileAttachments(c);v.useEffect(()=>{u&&"current"in u&&(u.current=h.current)},[u]);const S=v.useCallback(()=>{const j=h.current;if(j){if(!e||e.length===0){j.style.height="10px";return}j.style.height="auto";const I=Math.min(Math.max(j.scrollHeight,10),200);j.style.height=`${I}px`}},[e]);v.useEffect(()=>{S()},[S]),v.useEffect(()=>{const j=setTimeout(()=>{S()},0);return()=>clearTimeout(j)},[S]);const w=()=>{const j=e.trim();!j&&y.length===0||(a!=="ready"?(p(c,j,y),t(""),x(c)):r({preventDefault:()=>{}}))},C=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),w()),j.key==="@"&&f(!0)},N=v.useCallback(j=>{const I=Cft(j.nativeEvent);I.length>0&&(j.preventDefault(),I.forEach(async T=>{const F=await Z3(T);g(c,F)}))},[g,c]),k=v.useCallback(j=>{j.forEach(I=>{g(c,I)})},[g,c]),_=v.useCallback(j=>{j.forEach(I=>{g(c,I)})},[g,c]),E=v.useCallback(j=>{b(c,j)},[b,c]),D=v.useCallback(j=>{const I=`@${j}`;e.includes(I)&&t(e.replace(I,"").replace(/\s{2,}/g," ").trim())},[e,t]);return l.jsxs(byt,{onFilesDropped:k,currentFileCount:y.length,disabled:s,className:"space-y-4",children:[l.jsx(XR,{mode:"display",assistantType:c,onEntityRemoved:j=>{const I="label"in j?j.label:j.name;D(I)},onEntitiesRemoved:j=>{let I=e;j.forEach(T=>{const F="label"in T?T.label:T.name;I=I.replace(`@${F}`,"")}),I!==e&&t(I.replace(/\s{2,}/g," ").trim())}}),y.length>0&&l.jsx(Rft,{files:y,onRemove:E,showRemove:!s,className:"mb-2"}),l.jsxs("div",{className:"rounded-control border border-border/60 bg-background shadow-sm transition-colors focus-within:border-border focus-within:ring-1 focus-within:ring-ring/20",children:[l.jsx("textarea",{ref:h,value:e,onChange:n,onKeyDown:C,onPaste:N,onFocus:()=>{S(),i==null||i()},placeholder:"Ask a question...",className:"max-h-[200px] min-h-[40px] w-full resize-none overflow-y-auto border-0 bg-transparent px-3 pb-1 pt-3 text-sm text-foreground placeholder:text-muted-foreground/40 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),l.jsxs("div",{className:"flex items-center justify-between px-2 pb-2",children:[l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsx(XR,{mode:"trigger",assistantType:c,syncOnOpen:c==="dashboard",open:d,onOpenChange:f,onEntityMention:j=>{var T;const I="label"in j?j.label:j.name;t(`${e}@${I} `),(T=h.current)==null||T.focus()},triggerVariant:"secondary",triggerIconOnly:!0,triggerClassName:"h-7 px-2",triggerLabel:"Add entity"}),l.jsx(gyt,{onFilesSelected:_,disabled:s,currentFileCount:y.length})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[s&&l.jsx(m.Button,{className:"h-8 w-8 rounded-full p-0",size:"sm",onClick:o,children:l.jsx(_me,{className:"size-3.5"})}),!s&&l.jsx(m.Button,{disabled:!e.trim()&&y.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",className:"h-8 w-8 rounded-full p-0",onClick:w,title:a!=="ready"?"Message will be queued":void 0,children:l.jsx(bF,{className:"size-3.5"})})]})]})]})]})});h$.displayName="ChatInputWithContext";function Rfe({assistantType:e,className:t}){const n=m.useMessageQueue(e),{removeFromQueue:r}=m.useQueueActions();return n.length===0?null:l.jsxs("div",{className:m.cn("space-y-2",t),children:[l.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[l.jsx(fF,{className:"h-3 w-3"}),l.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),l.jsx("div",{className:"space-y-2",children:n.map(s=>l.jsx("div",{className:"group relative rounded-lg border border-dashed border-muted-foreground/30 bg-muted/30 px-3 py-2 text-sm animate-in fade-in-0 slide-in-from-bottom-1",children:l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsx("div",{className:"flex-1 space-y-1",children:l.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 transition-opacity group-hover:opacity-100",onClick:()=>r(e,s.id),title:"Remove from queue",children:l.jsx(m.X,{className:"h-3 w-3"})})]})},s.id))})]})}function Ffe({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=m.useMessageQueue(e),{dequeueMessage:o}=m.useQueueActions();v.useEffect(()=>{if(t!=="ready"||n||!(s&&s.length>0))return;const a=o(e);a&&r({role:"user",parts:[{type:"text",text:a.text}]})},[t,n,s,o,r,e])}function Ayt(e){return e?typeof e=="string"?e:typeof e.text=="string"?e.text:typeof e.content=="string"?e.content:typeof e.value=="string"?e.value:"":""}function Ryt(e){if(!e)return"none";const t=(e==null?void 0:e.id)??(e==null?void 0:e.messageId)??(e==null?void 0:e.createdAt)??(e==null?void 0:e.timestamp)??"unknown";if(!Array.isArray(e.parts)){const r=typeof(e==null?void 0:e.content)=="string"?e.content:typeof(e==null?void 0:e.text)=="string"?e.text:"";return`${t}|${(e==null?void 0:e.role)??"unknown"}|${r.length}|${r.slice(-24)}`}const n=e.parts.map(r=>{const s=typeof(r==null?void 0:r.type)=="string"?r.type:"unknown",o=typeof(r==null?void 0:r.state)=="string"?r.state:"na",i=Ayt(r);return`${s}:${o}:${i.length}:${i.slice(-24)}`}).join("|");return`${t}|${(e==null?void 0:e.role)??"unknown"}|${e.parts.length}|${n}`}function Pfe(e,t={}){const{threshold:n=40,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=v.useRef(null),a=v.useRef(null),[c,u]=v.useState(!0),[d,f]=v.useState(!0),[h,p]=v.useState(!1),[g,b]=v.useState(0),x=v.useRef(!0),y=v.useRef(!0),S=v.useRef(!1),w=v.useRef(!1),C=v.useRef(0),N=v.useRef({count:0,signature:"none"}),k=v.useCallback(()=>{if(i.current)return i.current;const R=a.current;if(!R)return null;const B=R.closest("[data-radix-scroll-area-viewport]");if(B)return i.current=B,B;const z=R.parentElement;return z?(i.current=z,z):null},[]),_=v.useCallback(()=>{const R=k();return R?R.scrollHeight-R.scrollTop-R.clientHeight:0},[k]),E=v.useCallback(()=>_()<=n,[_,n]),D=v.useCallback(R=>{x.current!==R&&(x.current=R,u(R))},[]),j=v.useCallback(R=>{y.current!==R&&(y.current=R,f(R))},[]),I=v.useCallback(()=>{p(R=>R&&!1),b(R=>R===0?R:0)},[]),T=v.useCallback((R={})=>{const B=k();if(!B)return;const{force:z=!1,instant:U=!1}=R;if(!z&&S.current)return;const Y=U||r==="auto"||r==="instant"?"auto":r;w.current=!0,Y==="smooth"&&"scrollTo"in B?B.scrollTo({top:B.scrollHeight,behavior:"smooth"}):B.scrollTop=B.scrollHeight,C.current=B.scrollTop,S.current=!1,D(!0),j(!0),I(),requestAnimationFrame(()=>{w.current=!1})},[r,I,k,D,j]),F=v.useCallback(()=>{b(0),p(!1)},[]),P=v.useCallback(()=>{const R=k();if(!R)return;const B=C.current,z=R.scrollTop,U=z-B;C.current=z;const Y=E();if(w.current){j(Y),Y&&(S.current=!1,D(!0));return}if(U<-1&&!Y){S.current=!0,D(!1),j(!1);return}if(Y){S.current=!1,D(!0),j(!0),I();return}j(!1),S.current&&D(!1)},[I,k,E,D,j]);return v.useEffect(()=>{const R=k();if(!e||e.length===0){N.current={count:0,signature:"none"},R&&(C.current=R.scrollTop),I();return}const B=e[e.length-1],z=Ryt(B),U=N.current,Y=e.length>U.count,O=z!==U.signature;N.current={count:e.length,signature:z};const K=o||s&&(B==null?void 0:B.role)==="assistant"&&O;if(!S.current){D(!0),R&&E()&&j(!0),(Y||O||K)&&T({force:!1,instant:K});return}if(Y){const q=e.length-U.count;q>0&&(p(!0),b(M=>M+q))}else O&&(p(!0),b(q=>q>0?q:1))},[I,o,s,k,E,e,T,D,j]),v.useEffect(()=>{T({force:!0,instant:!0})},[T]),v.useEffect(()=>{if(typeof ResizeObserver>"u")return;const R=a.current;if(!R)return;const B=new ResizeObserver(()=>{S.current||T({force:!1,instant:!0})});return B.observe(R),()=>{B.disconnect()}},[T]),v.useEffect(()=>()=>{w.current=!1},[]),{scrollRef:i,contentRef:a,isAutoScrollEnabled:c,isAtBottom:d,hasNewMessages:h,newMessageCount:g,scrollToBottom:T,handleScroll:P,resetNewMessageCount:F}}function Ofe(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=v.useState(r),a=v.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),c=e.length>o,u=o>=e.length,d=v.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=v.useCallback(()=>{i(r)},[r]);return v.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:c,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}const rW={"tool-getTableColumns":{"input-streaming":"Fetching table columns...","input-available":"Reading column definitions..."},"tool-getChartDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartDataFromCardConfig":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getForecastDataFromSqlAndPython":{"input-streaming":"Planning...","input-available":"Fetching data..."},"tool-getChartSQLSyntax":{"input-streaming":"Generating SQL syntax...","input-available":"SQL syntax generated"},"tool-validateCardConfigFormat":{"input-streaming":"Validating card config format...","input-available":"Card config format validated"},"tool-generateQueryConfig":{"input-streaming":"Generating query config...","input-available":"Sending query config..."},"tool-generateDynamicVisual":{"input-streaming":"Planning dynamic visual...","input-available":"Generating dynamic visual..."},"tool-generateDynamicVisualFromData":{"input-streaming":"Planning dynamic visual...","input-available":"Building visual..."},"tool-askForMoreInfo":{"input-streaming":"Asking for more information...","input-available":"More information requested"},"tool-createChartFromSql":{"input-streaming":"Creating chart...","input-available":"Chart created"},"tool-getUserSql":{"input-streaming":"Getting SQL...","input-available":"SQL retrieved"},"tool-inspectTableData":{"input-streaming":"Inspecting table data...","input-available":"Analyzing data..."},"tool-getDomainRelationships":{"input-streaming":"Getting domain relationships...","input-available":"Analyzing data..."}};function Fyt(e,t){var r;if((r=rW[e])!=null&&r[t])return rW[e][t];const n=e.replace("tool-","").replace(/([A-Z])/g," $1").toLowerCase().trim();return t==="input-streaming"?`Processing ${n}...`:`Preparing ${n} response...`}function Lfe(e){var n;if(!e||e.length===0)return{hasActiveTools:!1};const t=e[e.length-1];if(!(t!=null&&t.parts))return{hasActiveTools:!1};for(const r of t.parts){if(r.type==="reasoning"&&"state"in r&&r.state==="streaming")return{hasActiveTools:!0,activeToolText:"Reasoning...",toolType:"reasoning"};if(((n=r.type)!=null&&n.startsWith("tool-")||r.type==="dynamic-tool")&&"state"in r&&["input-streaming","input-available"].includes(r.state)){const s=r,o=s.state;return{hasActiveTools:!0,activeToolText:Fyt(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const Pyt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Oyt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=v.useState(!1),[a,c]=v.useState(m.isDevEnv),[u,d]=v.useState(!1),[f,h]=v.useState("auto"),[p,g]=v.useState(!1),[b,x]=v.useState(!1),y=n??b,{isLocalDev:S,isConsoleMode:w}=xg(),C=v.useRef(null);m.useDashboardStore(me=>me.dashboard.aiScopeTables),m.useDashboardStore(me=>me.isDashboardEditing);const N=m.useDashboardStore(me=>me.selectedSheetId),{setDataSource:k}=m.useEditorActions(),{setSelectedFrameId:_,setIsDashboardEditing:E}=m.useDashboardActions(),D=OL(),{setReasoningEffort:j,setShowReasoning:I,clearAssistantMessageContexts:T}=m.useAIActions(),{clearQueue:F}=m.useQueueActions(),{clearFileAttachments:P,getFileAttachments:R}=m.useFileActions(),B=m.useFileAttachments("dashboard"),z=m.useEditorStore(me=>me.card.dataSource),{assistantProfile:U}=jfe(),Y=m.useDashboardStore(me=>me.handleOpenAssistantProfile),{selectedEntities:O,applyDashboardDefaultEntities:K}=jj("dashboard"),{sendMessage:q,isLoading:M,messages:G,setMessages:L,status:$,stop:V,errorMessage:H,clearError:A}=myt({dynamicVisualMode:f}),W=v.useCallback(me=>{r==null||r(me),n===void 0&&x(me)},[n,r]),X=v.useCallback(()=>{W(!y)},[y,W]);v.useEffect(()=>{if(!y)return;function me(Ye){Ye.key==="Escape"&&W(!1)}return window.addEventListener("keydown",me),()=>{window.removeEventListener("keydown",me)}},[y,W]);const[Z,J]=v.useState(""),re=me=>{J(me.target.value)};async function fe({sql:me,cardTitle:Ye,connectionId:Ve,cardType:$e,python:Ae,cardConfig:Re,dataSource:He,customVisualPreferences:Ge,visualizationMode:ht,dynamicCardPreferences:lt}){if(!N)return;const st=ht==="dynamic",Fe=m.hasValidCardConfig(Re),Ke=Ve||(He==null?void 0:He.connectionId)||"",_t=He?{...He,connectionId:Ke||He.connectionId,connectionType:He.connectionType||"",mode:He.mode||"database",selectedEntities:He.selectedEntities||[]}:Ke?{connectionId:Ke,connectionType:"",mode:"database",selectedEntities:[]}:z0,Te=!Fe||!st||(lt==null?void 0:lt.provenance)!=="card-config",Ze=Te?me:"",at=Te?Ae:"",bt={id:m.v4(),title:Ye||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:$e==="horizontalBar"?"y":"x"},...st&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:$e,sql:Ze,python:at,dataSource:_t,config:Re,connectionId:Ke,visualizationMode:ht,dynamicCardPreferences:lt,customCardPreferences:Ge?{url:Ge.url,componentName:Ge.componentName,pluginChartType:Ge.pluginChartType,settings:Ge.settings,type:"component"}:void 0},ft={id:m.v4(),cards:[bt],activeCardId:bt.id};try{await D(N,ft,"end"),E(!0),_(ft.id)}catch(Et){console.error("Failed to add assistant visual to dashboard:",Et),ut.error(Et instanceof Error?Et.message:"Failed to prepare semantic metadata for the new visual")}}const de=me=>{me.preventDefault();const Ye=Z.trim();if(!Ye&&B.length===0)return;const Ve=[];Ye&&Ve.push({type:"text",text:Ye}),B.forEach($e=>{$e.data&&Ve.push({type:"file",mediaType:$e.type,filename:$e.name,url:`data:${$e.type};base64,${$e.data}`})}),q({role:"user",parts:Ve}),J(""),P("dashboard"),le({force:!0})};v.useEffect(()=>{var me;e&&((me=C.current)==null||me.focus())},[e]),Ffe({assistantType:"dashboard",status:$,isLoading:M,sendMessage:q});const{hasActiveTools:Se,activeToolText:ue}=Lfe(G),{visibleMessages:ve,hasMoreMessages:xe,totalMessageCount:ke,loadMoreMessages:se,resetMessageWindow:be}=Ofe(G,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Ce,contentRef:ge,isAtBottom:ee,hasNewMessages:te,newMessageCount:ce,scrollToBottom:le,handleScroll:Ee,resetNewMessageCount:ye}=Pfe(ve,{threshold:40,behavior:"smooth",isStreaming:M});function ne(me){const Ye={role:"user",parts:[{type:"text",text:me.title+" "+me.subtitle}]};q(Ye)}function je(me){q({role:"user",parts:[{type:"text",text:me}]})}function Ue(me){q({role:"user",parts:[{type:"text",text:me}]}),le({force:!0})}const Be=v.useCallback(async()=>{const me=JSON.stringify(G??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(me),ut.success("Conversation copied")}catch(Ye){console.error("Failed to copy conversation",Ye),ut.error("Unable to copy conversation")}},[G]),rt=(Z==null?void 0:Z.length)===0&&(G==null?void 0:G.filter(me=>me.role==="user").length)===0;function Xe(){return l.jsx("div",{"data-role":"header",children:l.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function et(){return l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(Lh,{className:"size-3.5"})})}),l.jsxs(fo,{align:"end",children:[l.jsx(kc,{children:"Options"}),l.jsx(Ea,{}),l.jsx(bu,{checked:o,onCheckedChange:i,children:"Token Usage"}),l.jsx(bu,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(bu,{checked:u,onCheckedChange:d,children:"System Message"}),(S||w)&&l.jsxs(l.Fragment,{children:[l.jsx(Ea,{}),l.jsx(kc,{children:"Dynamic Visuals"}),l.jsx(bu,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(bu,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(bu,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const tt=l.jsxs("div",{"data-role":"dashboard-assistant",className:m.cn("flex h-full grow flex-col justify-between break-words px-6 py-4",y&&"rounded-card border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[l.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[Xe(),Y&&l.jsx(m.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:Y,children:(U==null?void 0:U.name)||"Default Profile"}),l.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[w&&et(),a&&l.jsx(m.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Be,children:"Copy Conversation"}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:y?"Exit Fullscreen":"Expand",onClick:X,children:y?l.jsx(pF,{className:"size-4"}):l.jsx(_k,{className:"size-4"})}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{const me=G.filter(Ye=>Ye.role==="assistant").map(Ye=>Ye.id).filter(Ye=>!!Ye);L([]),F("dashboard"),A(),T(me),be()},children:l.jsx(jk,{className:"size-4"})}),l.jsx(Vu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:l.jsx(m.X,{className:"size-4"})})]})]}),l.jsxs(zl,{"data-role":"dashboard-assistant-scroll-area",ref:Ce,className:"mt-4 flex min-w-0 flex-1 basis-0 flex-col justify-end pr-2",onScroll:Ee,children:[l.jsxs("div",{ref:ge,className:"min-w-0 space-y-3 pb-4",children:[xe&&l.jsx("div",{className:"flex justify-center py-2",children:l.jsxs(m.Button,{variant:"outline",size:"sm",onClick:se,className:"text-xs",children:["Load ",Math.min(5,ke-ve.length)," ","more messages (",ke-ve.length," ","hidden)"]})}),l.jsx(cde,{showTools:a,showSystemMessage:u,messages:ve,onAddToDashboard:fe,onQuickReply:Ue,disableQuickReplies:M}),l.jsx(lde,{status:$,errorMessage:H,activeToolText:M&&Se?ue:void 0})]}),l.jsx(m.ScrollBar,{orientation:"horizontal"})]}),e&&!ee&&l.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:l.jsxs(m.Button,{onClick:()=>{le({force:!0}),ye()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[l.jsx(m.ChevronDown,{className:"h-4 w-4"}),te&&ce>0&&l.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:ce>9?"9+":ce})]})}),l.jsxs("div",{className:"space-y-3",children:[!U&&rt&&l.jsx(ude,{onClick:ne,placeholders:Pyt}),l.jsx("div",{children:rt&&U&&l.jsx(Efe,{seedQuestions:U.seedQuestions||[],handleSeedQuestionClick:je})}),l.jsx(Rfe,{assistantType:"dashboard",className:"mb-3"}),l.jsx(h$,{ref:C,setInput:J,stop:V,input:Z,handleInputChange:re,handleSubmit:me=>{de(me),le({force:!0})},isLoading:M,status:$,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(f$,{incomingSelectedEntities:O,open:p,onOpenChange:g,dataSource:z||z0,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:me=>K()})]});return y&&s?Sr.createPortal(l.jsx(sb,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:l.jsx("div",{className:"flex h-full w-full",children:tt})}),s):tt}function Lyt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=m.useDashboardActions(),s=Iie(),o=m.useDashboardStore(d=>d.dashboard.sheets),a=m.useDashboardStore(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),c=m.useDashboardStore(d=>d.isDashboardEditing),u=m.useDashboardStore(d=>d.isVisualEditing);v.useEffect(()=>{if(!c||u)return;async function d(p){if($yt(p.target))return;const g=p.ctrlKey||p.metaKey;g&&p.key==="c"?(await f(),ut.success("Card copied to clipboard"),p.preventDefault()):g&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText(),g=zyt(p);if(g!=null&&g.id){const b=jie(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await s(a,b),r(b.id),ut.success("Card pasted from clipboard")}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[s,n,r,a,c,u,t])}function $yt(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.closest("[contenteditable]");return t&&t.getAttribute("contenteditable")!=="false"?!0:!!e.closest('input, textarea, select, [role="textbox"]')}function zyt(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.id=="string"&&Array.isArray(t.cards)?t:null}catch{return null}}function Byt(e,t){switch(e.interactionMode){case"drillToDetail":Vyt(e,t);break;case"drillThrough":Hyt(e,t);break;case"drillToURL":Uyt(e);break;case"inlineDrill":console.warn("Inline drill execution not yet implemented");break;case"clickFilter":case"drillDown":case"dynamicDrill":break;default:console.warn("Unknown interaction mode:",e.interactionMode)}}function Vyt(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function Hyt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Uyt(e){const{url:t}=e;if(!t){console.warn("drillToURL event missing url");return}try{new URL(t)}catch(n){console.error("Invalid URL:",t,n);return}window.open(t,"_blank","noopener,noreferrer")}function Wyt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return l.jsx(Oo,{open:e,onOpenChange:t,children:l.jsxs(mo,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[l.jsxs(na,{children:[l.jsx(go,{children:i||"Insight Detail"}),l.jsx(si,{children:a||"View detailed insight data with applied filters"})]}),l.jsx(Aie,{filters:r,filterDefinitions:s,contextMode:o}),l.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?l.jsx(Gie,{insightId:n,filters:r,contextMode:o}):l.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function qyt(){const e=m.useInteractionStore(C=>C.interactionStates),t=m.useInteractionStore(C=>C.setInteractionState),n=m.useInteractionStore(C=>C.clearLastInteractionEvent),r=m.useInteractionStore(C=>C.replaceCardWithInsight),s=m.useInteractionStore(C=>C.setPendingDrillThrough),o=m.useInteractionStore(C=>C.pendingDrillThrough),i=m.useInteractionStore(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=m.useDashboardActions(),{selectDashboard:u}=Ph(),d=m.useDashboardStore(C=>C.dashboard),f=m.useDashboardStore(C=>C.filterValues),{data:h,isLoading:p}=LY((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[g,b]=v.useState({open:!1,insightId:""}),x=Kie(g.insightId,{enabled:g.open&&!!g.insightId}),y=v.useRef(new Set),S=v.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:N,contextMode:k})=>{b({open:!0,insightId:C,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:k})},replaceCardContent:({cardId:C,insightId:N,filters:k,contextMode:_})=>{r(C,N,k,_)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:E})=>{const D={filters:C},j={sourceCardId:m.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[D]},I={...m.createInitialInteractionState(),appliedClickFilters:[j],contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:E};t(m.DRILL_CONTEXT_CARD_ID,I)}}),[a,r,f,c,d,s,t]);v.useEffect(()=>{Object.entries(e).forEach(([C,N])=>{if(N!=null&&N.lastInteractionEvent){const k=N.lastInteractionEvent,_=`${C}-${k.interactionMode}-${k.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{Byt(k,S)}catch(E){console.error("Error executing interaction event:",E)}finally{n(C),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,S]),v.useEffect(()=>{if(!(!o||!h||p))try{u(h),c(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,p,u,c,i]);const w=()=>{b({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Wyt,{open:g.open,onOpenChange:w,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&p&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[l.jsx(m.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Yyt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=Gyt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function Gyt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function Kyt(e){return e?`Back to ${e}`:"Back"}function Zyt(){var y,S,w,C,N;const e=m.useInteractionStore(k=>k.interactionStates[m.DRILL_CONTEXT_CARD_ID]),t=m.useDashboardStore(k=>k.actions.goBackFromDrill),n=m.useDashboardStore(k=>k.actions.clearDrillContext),{selectDashboard:r}=Ph(),[s,o]=v.useState({x:16,y:16}),[i,a]=v.useState(!1),c=v.useRef({x:0,y:0});v.useEffect(()=>{if(!i)return;const k=E=>{o({x:E.clientX-c.current.x,y:E.clientY-c.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",k),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",k),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(w=(S=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:S.filterGroups)==null?void 0:w[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(k){console.error("[DrillBack] Error during back navigation:",k)}},g=()=>{n()},b=k=>{k.target.closest("button")||(a(!0),c.current={x:k.clientX-s.x,y:k.clientY-s.y})};Yyt(f);const x=Kyt(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:b,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((k,_)=>{const E=k.field.label||k.field.name,D=String(k.value);return l.jsxs(Yr,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",D]},_)})})]}),l.jsx(m.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(m.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(m.Button,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(ev,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Xyt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Qyt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:p,transition:g,isDragging:b}=db({id:`filter:${e.id}`,disabled:n||!t}),x={transform:_i.Translate.toString(p),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return l.jsx("div",{ref:h,style:x,...d,children:l.jsx(bL,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u})})}const sW="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Jyt=[];function $fe({open:e,onOpenChange:t}){var L,$,V;const[n,r]=v.useState(!1),[s,o]=v.useState(!1),[i,a]=v.useState({sheetSelection:"current",protectPdf:!1,password:""}),c=m.useDashboardStore(H=>{var A;return(A=H.dashboard)==null?void 0:A.sheets}),u=m.useDashboardStore(H=>H.dashboard),d=m.useDashboardStore(H=>H.dashboardInputValues),f=m.useDashboardStore(H=>H.filterValues),h=m.useDashboardStore(H=>H.controlValues),p=m.useDashboardStore(H=>H.inlineFilterValuesMap),g=m.useDashboardStore(H=>H.cardControlValuesMap),b=m.useDashboardStore(H=>H.selectedSheetId),x=m.useDashboardStore(H=>H.selectedSheetId?H.documentInputRuntimeBySheetId[H.selectedSheetId]:void 0),y=m.useDashboardStore(H=>H.isDownloadingPdf),{authToken:S,tokenProps:w}=Ct(),C=c==null?void 0:c.find(H=>H.id===b),N=v.useMemo(()=>m.getDashboardExportSheets(c),[c]),k=m.isDocumentSheet(C),_=k&&C?C.document:void 0,E=v.useMemo(()=>k&&C?dw(u,C.id):[],[C,k,u]),D=E.length>0,j=v.useMemo(()=>k&&C?Tce(u,C.id):!1,[C,k,u]),I=v.useMemo(()=>D?E.map(fw):(_==null?void 0:_.inputs)||Jyt,[_,E,D]),T=(($=(L=w==null?void 0:w.params)==null?void 0:L.calendarContext)==null?void 0:$.tz)||((V=w==null?void 0:w.params)==null?void 0:V.timezone)||(typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),F=v.useMemo(()=>Tle(I),[I]),P=v.useMemo(()=>Dle(I,T),[I,T]),R=v.useMemo(()=>Ile(I),[I]),B=x?x.filterValuesByInputId:P,z=x?x.controlValuesByInputId:R,U=v.useMemo(()=>k?j&&C&&_?VZ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(H=>H.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},timezone:T}):Rle(I,B,z,F,F):[],[_,I,C,k,u,g,h,f,p,d,z,B,F,T,j]),Y=!!C,O=N.length>0,K=((c==null?void 0:c.length)||0)>1||k,q=i.sheetSelection==="current"&&(!Y||k&&U.length>0)||i.sheetSelection==="all"&&!O;v.useEffect(()=>{e&&i.sheetSelection==="all"&&!O&&a(H=>({...H,sheetSelection:"current"}))},[O,e,i.sheetSelection]);const M=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function G(){if(y){ut.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){ut.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!Y){ut.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!O){ut.error("No dashboard sheets are available to export");return}o(!0);const H=i.sheetSelection==="current"&&k,A=H?i.protectPdf?"Generating protected document PDF... may take up to 60 seconds":"Generating document PDF... may take up to 60 seconds":i.sheetSelection==="all"?"Generating PDF for all dashboard sheets... This may take a while.":i.protectPdf?"Generating protected PDF... may take up to 60 seconds":"Generating PDF... may take up to 60 seconds",W=ut.loading(A);try{if(H){if(!_||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){ut.dismiss(W),ut.error(`Set ${U.join(", ")} before exporting`);return}const Z=new Date().toISOString(),J=j?UZ({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(re=>re.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:p,cardControlValuesMap:g},generatedAt:Z,timezone:T}).snapshot:void 0;await PP(w.apiServiceUrl,S,{sheetId:C.id,title:C.title||"Document",pageSize:_.page.size,orientation:_.page.orientation,timezone:T,password:i.protectPdf?i.password:void 0,inputSnapshot:J,...J?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:B,controlValuesByInputId:z,generatedAt:Z}}})}else{const Z=xee();await XZ(w.apiServiceUrl,S,i.protectPdf?i.password:void 0,i.sheetSelection,Z)}ut.dismiss(W);const X=H?i.protectPdf?"Protected document PDF downloaded successfully!":"Document PDF downloaded successfully!":i.sheetSelection==="all"?"Dashboard sheets PDF downloaded successfully!":i.protectPdf?"Protected PDF downloaded successfully!":"PDF downloaded successfully!";ut.success(X,{duration:2e3}),M()}catch(X){ut.dismiss(W),ut.error("Failed to download PDF",{description:m_(X,"Please try again or contact support."),descriptionClassName:p_,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",X)}finally{o(!1)}}return l.jsx(Oo,{open:e,onOpenChange:H=>{if(!H){M();return}t(!0)},children:l.jsxs(mo,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[l.jsxs(na,{children:[l.jsx(go,{className:"text-[15px]",children:k?"Export document":"Export dashboard"}),l.jsx(si,{className:"text-[13px] leading-5",children:k?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),l.jsxs("div",{className:"space-y-4 py-1",children:[K&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(m.Label,{className:sW,children:"Export scope"}),l.jsxs(Ia,{value:i.sheetSelection,onValueChange:H=>a({...i,sheetSelection:H}),className:"gap-1.5",children:[l.jsxs(m.Label,{htmlFor:"scope-current",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!Y&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(js,{value:"current",id:"scope-current",disabled:!Y}),k?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),l.jsxs(m.Label,{htmlFor:"scope-all",className:m.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!O&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(js,{value:"all",id:"scope-all",disabled:!O}),"Dashboard sheets (",N.length," ",N.length===1?"sheet":"sheets",")"]})]}),k&&l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:U.length>0?`Set ${U.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),l.jsx(m.Separator,{className:"bg-border/60"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs(m.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[l.jsx(Ln,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:H=>{a({...i,protectPdf:H,password:H?i.password:""}),H||r(!1)}}),l.jsx(kk,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&l.jsxs("div",{className:"ml-6 space-y-1.5",children:[l.jsx(m.Label,{htmlFor:"pdf-password",className:sW,children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(m.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:H=>a({...i,password:H.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:H=>{H.key==="Enter"&&i.password&&G()}}),l.jsx("button",{type:"button",className:"absolute right-1 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>r(!n),"aria-label":n?"Hide password":"Show password",children:n?l.jsx(Nk,{className:"h-3.5 w-3.5"}):l.jsx(tv,{className:"h-3.5 w-3.5"})})]}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),l.jsxs(Gc,{children:[l.jsx(m.Button,{variant:"outline",size:"xs",onClick:M,disabled:s,children:"Cancel"}),l.jsx(m.Button,{size:"xs",onClick:G,disabled:s||y||q,children:s?l.jsxs(l.Fragment,{children:[l.jsx(m.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):l.jsxs(l.Fragment,{children:[l.jsx(qc,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function zfe({iconClassName:e,open:t,onOpenChange:n}){const[r,s]=v.useState(!1),o=t!==void 0,i=o?t:r,a=u=>{o||s(u),n==null||n(u)},c=m.useDashboardStore(u=>u.isDownloadingPdf);return l.jsxs(l.Fragment,{children:[o?null:l.jsx(m.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:c,onClick:()=>a(!0),children:l.jsx(qc,{className:m.cn("size-4",e)})}),l.jsx($fe,{open:i,onOpenChange:a})]})}function oW(e,t,n){const r=new Set(t),s=[...n];return e.map(o=>r.has(o.id)?s.shift()??o.id:o.id)}function e0t({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:c,isDragging:u}=db({id:`control:${e.id}`,disabled:!n}),d={transform:_i.Translate.toString(a),transition:c,opacity:u?.5:1,zIndex:u?10:void 0};return l.jsx("div",{ref:i,style:d,...s,children:l.jsx(Gle,{control:e,value:t,isEditing:n,dragListeners:n?o:void 0,onChange:r})})}function iW(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function aW(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function t0t(e,t,n){const r=new Set([...t.map(a=>`filter:${a.id}`),...n.map(a=>`control:${a.id}`)]);if(!(e!=null&&e.length))return aW(t,n);const s=e.filter(a=>r.has(a)),o=new Set(s),i=aW(t,n).filter(a=>!o.has(a));return[...s,...i]}function n0t(e,t){return m.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function r0t(e){return zm(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>zm(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function lW(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function s0t(e){const t={sheetId:e.selectedSheetId},n=m.getDashboardInputRuntimeSlot(e.dashboardInputValues,e.dashboardInput,t);if(n)return n;const r=m.getDashboardInputRuntimeSlot(e.defaultInputValues,e.dashboardInput,t);return r||m.getBackingDefaultSlot(e.dashboardInput)}function o0t(e){return Bfe(e).filter(t=>{var n,r;return t.filter.hide||t.filter.location==="frame"?!1:((n=t.compatibility)==null?void 0:n.source)==="dashboardFilter"?!0:(((r=t.presentation)==null?void 0:r.placement)||"toolbar")==="toolbar"})}function Bfe(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=n0t(e.dashboard,t);return lZ(a_({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!r0t({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function i0t(e,t){return"toolbar"}function a0t(){const e=Zc("interactive"),t=m.useDashboardStore($=>$.selectedSheetId),n=m.useDashboardStore($=>$.dashboard.filters),r=m.useDashboardStore($=>$.dashboard.filterLayout),s=m.useDashboardStore($=>$.isDashboardEditing),o=m.useDashboardStore($=>$.controlValues),i=m.useDashboardStore($=>$.filterValues);m.useDashboardStore($=>$.filteringCards);const a=m.useDashboardStore($=>$.inlineFilterValuesMap),c=m.useDashboardStore($=>$.dashboardInputValues),u=m.useInteractionStore($=>$.clearAllClickFilters),d=m.useInteractionStore($=>Object.entries($.interactionStates).reduce((V,[H,A])=>{var W;return H===m.DRILL_CONTEXT_CARD_ID?V:V+(((W=A.appliedClickFilters)==null?void 0:W.length)??0)},0)),f=m.useDashboardStore($=>$.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:p,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:S,setFilteringCards:w,upsertDashboardInput:C}=m.useDashboardActions(),N=Tj(cg(cb,{activationConstraint:{distance:5}})),k=m.useDashboardStore($=>$.dashboard),_=o0t({dashboard:k,selectedSheetId:t}).filter($=>i0t($.filter)==="toolbar"),E=Bfe({dashboard:k,selectedSheetId:t}),D=_.map($=>$.filter),j=new Map(_.map($=>[`filter:${$.filter.id}`,$])),I=wKe(k),T=I.filter($=>!$.hidden&&C0($)==="toolbar"),F=I.filter($=>!$.hidden&&C0($)==="advanced"),P=t0t(r==null?void 0:r.toolbarItemOrder,D,T),R=new Map(D.map($=>[`filter:${$.id}`,$])),B=new Map(T.map($=>[`control:${$.id}`,$]));function z($){const{active:V,over:H}=$;if(!H||V.id===H.id)return;const A=String(V.id),W=String(H.id),X=P.findIndex(ve=>ve===A),Z=P.findIndex(ve=>ve===W);if(X===-1||Z===-1)return;const J=ub(P,X,Z);y({toolbarItemOrder:J});const re=new Set((n||[]).map(ve=>ve.id)),fe=P.filter(ve=>ve.startsWith("filter:")).map(ve=>ve.replace("filter:","")).filter(ve=>re.has(ve)),de=J.filter(ve=>ve.startsWith("filter:")).map(ve=>ve.replace("filter:","")).filter(ve=>re.has(ve)),Se=P.filter(ve=>ve.startsWith("control:")).map(ve=>ve.replace("control:","")),ue=J.filter(ve=>ve.startsWith("control:")).map(ve=>ve.replace("control:",""));h(oW(n||[],fe,de)),g(oW(k.controls||[],Se,ue))}const U=(r==null?void 0:r.toolbarWrap)??!1,Y=(r==null?void 0:r.showDownloadButton)??!1,O=(i==null?void 0:i.filter($=>iW($)).length)??0,K=E.filter(lW),q=K.filter($=>{const V=s0t({dashboardInput:$,dashboardInputValues:c,defaultInputValues:k.defaultInputValues,selectedSheetId:t});return(V==null?void 0:V.status)==="set"&&V.value.kind==="filter"&&iW(V.value.filterValue)}).length,M=a?Object.values(a).reduce(($,V)=>$+((V==null?void 0:V.length)??0),0):0,G=O+q+M+d,L=()=>{S([]),K.forEach($=>{p($,{sheetId:t})}),w([]),u(),a&&Object.entries(a).forEach(([$,V])=>{V==null||V.forEach(H=>{f($,H.filterId)})})};return!D.length&&!T.length&&!F.length&&!Y&&G===0?null:l.jsx("div",{className:"z-20 border-b border-border/60 bg-background/95 px-3 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/85",style:e.containerStyle,role:"toolbar","aria-label":"Dashboard filters and controls",children:l.jsx(ow,{sensors:N,collisionDetection:nw,onDragEnd:z,children:l.jsxs("div",{className:m.cn("flex items-center",U?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[l.jsx(iw,{items:P,strategy:qL,children:l.jsx(NR,{className:"gap-3 pr-0",wrap:U,children:P.map($=>{const V=R.get($);if(V){const A=j.get($),W=A&&lW(A);return l.jsx(Qyt,{filter:V,isEditing:s,storageOptions:W?{storageTarget:"dashboardInput",dashboardInput:A,sheetId:t??void 0}:void 0,inputVariableName:W?A.variableName:void 0,onUpdateFilter:W?(X,Z)=>{C({...A,variableName:(Z==null?void 0:Z.variableName)||A.variableName,filter:X})}:void 0,onRemoveFilter:W?()=>{S((i||[]).filter(X=>X.filterId!==V.id)),b(A.id)}:void 0},$)}const H=B.get($);return H?l.jsx(e0t,{control:H,value:o==null?void 0:o[H.id],isEditing:s,onChange:A=>x(H.id,A)},$):null})})}),F.length>0&&l.jsx(Hie,{title:"",controls:F,values:o,onChange:($,V)=>x($.id,V),immediatePlacement:"toolbar",advancedLabel:"More controls"}),G>0&&l.jsxs("button",{type:"button",onClick:L,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(m.X,{className:"h-3 w-3"}),"Clear all",l.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:G})]}),Y&&l.jsx("div",{className:m.cn(G>0?"ml-1.5":"ml-auto"),children:l.jsx(zfe,{})})]})})})}function Vfe(){var te,ce;const{showAssistant:e,tokenProps:t,renderMode:n}=Ct(),r=Xyt((te=t.config)==null?void 0:te.showDashboardAssistant,e),{preferences:s,isConsoleMode:o}=xg(),i=(ce=s==null?void 0:s.cardDisplay)==null?void 0:ce.mode,a=Wh(i),c=_Z({displayMode:i,renderMode:n}),u=v.useRef(null),d=v.useRef(null),[f,h]=v.useState(!1),{handleDragStart:p,isDraggingRef:g,getStyle:b,getPositionClasses:x}=Sot({initialPosition:"bottom-right"}),y=Hf(le=>le.setFullscreen),S=Hf(le=>le.setPanelOpen),w=Hf(le=>le.setContainer),C=mK("dashboard"),N=gK(),k=bK("dashboard"),_=C.isOpen,E=N==="dashboard",D=m.useDashboardStore(le=>le.isVisualEditing),j=m.useDashboardStore(le=>le.themeStyle),I=Rl(),T=m.useDashboardStore(le=>{var Ee;return(Ee=le.dashboard)==null?void 0:Ee.sheets}),F=m.useDashboardStore(le=>le.showFilters),P=m.useDashboardStore(le=>le.isDashboardEditing),R=m.useDashboardStore(le=>le.selectedSheetId),B=T==null?void 0:T.find(le=>le.id===R),z=m.useDashboardStore(le=>{var Ee,ye,ne;return(ne=(ye=(Ee=le.dashboard)==null?void 0:Ee.sheets)==null?void 0:ye.find(je=>je.id===le.selectedSheetId))==null?void 0:ne.kind}),U=m.useDashboardStore(le=>{var Ee,ye;return((ye=(Ee=le.dashboard)==null?void 0:Ee.summary)==null?void 0:ye.position)||"top"}),Y=z==="document",O=m.useDashboardStore(le=>{var Ee;return(Ee=le.dashboard)==null?void 0:Ee.id}),K=m.useDashboardStore(le=>le.isDashboardPanelOpen),q=m.useDashboardStore(le=>le.actions.setIsDashboardPanelOpen),{getDefaultSheetId:M,setDefaultSheetId:G,clearDefaultSheetId:L}=YW(O),[$,V]=v.useState(null);Rk(Xr.DASHBOARD);const{setSelectedSheetId:H,setSheetTitle:A,addSheet:W,setSheets:X}=m.useDashboardActions();Lyt(d);const{setActiveAssistantType:Z}=m.useAIActions();v.useEffect(()=>{if(O){const le=M();V(le)}},[O,M]),v.useEffect(()=>{_?Z("dashboard"):N==="dashboard"&&y(null)},[_,Z,N,y]),v.useEffect(()=>{var le;_||(le=u.current)==null||le.resize(0)},[_]);function J(le){var Ee,ye;le?((Ee=u.current)==null||Ee.resize(40),S("dashboard",!0),y("dashboard"),Z("dashboard")):(S("dashboard",!1),y(null),(ye=u.current)==null||ye.resize(0),Z(null))}function re(le="dashboard"){const Ee={id:m.v4(),title:le==="document"?"New Document":"New Sheet",...le==="document"?{kind:le,document:m.createDefaultDocumentDefinition()}:{}};W(Ee),H(Ee.id)}function fe(le,Ee){if(!O)return;$===le?(L(),V(null),ut.success("Default sheet cleared")):(G(le),V(le),ut.success(`"${Ee}" set as default sheet`))}function de(le){var Ee;le<1?(S("dashboard",!1),y(null),Z(null),(Ee=u.current)==null||Ee.resize(0)):(_||S("dashboard",!0),Z("dashboard"))}function Se(){return(j==null?void 0:j.canvasTheme)==="muted"||!(j!=null&&j.canvasTheme)?"hsl(var(--semaphor-muted))":(j==null?void 0:j.canvasTheme)==="clear"?"":j==null?void 0:j.canvasTheme}const ue=(le,Ee)=>{le.dataTransfer.setData("tabIndex",Ee.toString())},ve=le=>{le.preventDefault()},xe=(le,Ee)=>{const ye=le.dataTransfer.getData("tabIndex");if(ye===Ee.toString())return;const ne=Array.from(T||[]),[je]=ne.splice(parseInt(ye),1);ne.splice(Ee,0,je),X(ne)},ke=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,se=r===!0&&!a&&!_&&!D&&!F;function be(){if(T&&T.length>1||P)return l.jsxs("div",{className:"relative flex w-full items-stretch border-b border-border",children:[o&&ke&&!K&&l.jsx("button",{type:"button","aria-label":"Toggle dashboards panel",onClick:()=>{q(!K)},className:"group/panel mx-2 inline-flex h-9 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",children:l.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-[4px] group-hover/panel:bg-muted",children:l.jsx(mF,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),l.jsxs("div",{className:"relative min-w-0 flex-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-4 bg-gradient-to-r from-background to-transparent"}),l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-4 bg-gradient-to-l from-background to-transparent"}),l.jsxs(m.TabsList,{role:"tab-list",className:"flex w-0 min-w-full items-stretch justify-start overflow-x-auto rounded-none bg-transparent p-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[T==null?void 0:T.map((le,Ee)=>{const ye=R===le.id,ne=$===le.id;return l.jsxs(m.TabsTrigger,{draggable:!0,onDragStart:je=>ue(je,Ee),onDragOver:ve,onDrop:je=>xe(je,Ee),onClick:()=>H(le.id),className:m.cn("group relative inline-flex h-9 shrink-0 items-center gap-1.5 rounded-none bg-transparent px-3 py-0 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-transparent hover:text-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none","after:pointer-events-none after:absolute after:inset-x-2 after:-bottom-px after:h-0.5 after:bg-transparent data-[state=active]:after:bg-foreground"),value:le.id,children:[le.kind==="document"&&l.jsx(vi,{className:"h-3 w-3 text-muted-foreground"}),l.jsx(ON,{enabled:P&&ye,text:le.title,onSave:je=>A(le.id,je),children:le.title},le.id),l.jsx("span",{role:"button",tabIndex:0,"aria-label":ne?"Clear default sheet":"Set as default sheet",title:ne?"Clear default sheet":"Set as default sheet",onClick:je=>{je.stopPropagation(),fe(le.id,le.title||"Sheet")},onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(je.preventDefault(),je.stopPropagation(),fe(le.id,le.title||"Sheet"))},className:m.cn("inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] transition-opacity hover:bg-muted focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",ye||ne?"opacity-100":"opacity-0 group-hover:opacity-100"),children:l.jsx(yF,{className:m.cn("h-3 w-3 transition-colors",ne?"fill-current text-amber-500":"text-muted-foreground")})}),P&&ye&&T.length>1&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Delete sheet",className:"inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",onClick:je=>{je.stopPropagation(),h(!0)},onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(je.preventDefault(),je.stopPropagation(),h(!0))},children:l.jsx(m.X,{className:"h-3 w-3"})})]},le.id)}),P&&l.jsxs(Ao,{children:[l.jsx(Ro,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add sheet",className:"ml-1 inline-flex h-9 shrink-0 items-center gap-1 px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(dr,{className:"h-3 w-3"}),"Sheet"]})}),l.jsxs(fo,{align:"start",className:"w-48",children:[l.jsxs(jn,{onSelect:()=>re("dashboard"),children:[l.jsx(Rm,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),l.jsxs(jn,{onSelect:()=>re("document"),children:[l.jsx(vi,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})]})}function Ce(){return l.jsx("div",{ref:d,style:{},className:"h-full min-h-0 grow",children:T==null?void 0:T.map(le=>l.jsx(m.TabsContent,{style:{backgroundColor:Se(),...I.dashboardCanvasStyle},className:m.cn("mt-0 h-full min-h-0",{}),value:le.id,children:l.jsx(xH,{sheet:le})},le.id))})}function ge(){return l.jsxs(m.Tabs,{"data-role":"dashboard-tabs-container",className:m.cn("relative flex h-full flex-col",j==null?void 0:j.dashboardTabsContainer),onValueChange:le=>{H(le)},value:R||void 0,children:[be(),U==="top"&&!Y&&l.jsx(sR,{}),R&&!Y&&l.jsx(a0t,{}),Y?l.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:Ce()}):l.jsx(zl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:Ce()}),U==="bottom"&&!Y&&l.jsx(sR,{}),l.jsx(Cot,{open:f,setOpen:h})]})}const ee=v.useCallback(le=>{w("dashboard",le)},[w]);return T?c&&R&&!Y?l.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',R,'" was not found or is not a document sheet in the loaded dashboard.']}):c&&Y&&B?l.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:l.jsx(xH,{sheet:B})}):l.jsxs(l.Fragment,{children:[l.jsx(qyt,{}),l.jsx(Zyt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(UF,{className:m.cn("flex-1 basis-0 overflow-y-auto transition-opacity",E&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(Ry,{children:ge()}),r===!0&&l.jsxs(l.Fragment,{children:[l.jsx(wot,{open:_,onTabClick:J,withHandle:!0,disabled:!_}),l.jsx(Ry,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:de,defaultSize:_?40:0,ref:u,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Oyt,{open:_,setOpen:J,isFullscreen:E,onFullscreenChange:le=>y(le?"dashboard":null),fullscreenContainer:k})})})]})]}),l.jsx("div",{ref:ee,className:m.cn("absolute inset-0",!E&&"pointer-events-none")}),se&&l.jsx("div",{className:m.cn("absolute z-50 transition-all duration-300 ease-in-out",x().horizontal,x().vertical),style:b(),children:l.jsx(m.Button,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{g.current||J(!0)},onMouseDown:p,onTouchStart:p,title:"Open Assistant (drag to move)",children:l.jsx(vme,{className:"h-5 w-5"})})})]})]}):null}const Hfe=v.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:s,children:o,className:i,style:a,...c},u)=>{const d=v.useId(),f=v.useMemo(()=>l0t(d),[d]),{theme:h}=nF(),p=c0t(h),g=v.useMemo(()=>s??Wc.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,s,n]),b=v.useMemo(()=>m.compileAppearance({spec:g,systemMode:p}),[g,p]),x=v.useMemo(()=>m.createAppearanceContextValue(f,b),[b,f]);return l.jsx(m.AppearanceContext.Provider,{value:x,children:l.jsx(sb,{...c,ref:u,className:i,style:a,children:o})})});Hfe.displayName="AppearanceProvider";function l0t(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function c0t(e){const t=hC(e),[n,r]=v.useState(()=>u0t());return v.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const s=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!s)return;const o=()=>{r(s.matches?"dark":"light")};return o(),typeof s.addEventListener=="function"?(s.addEventListener("change",o),()=>s.removeEventListener("change",o)):((a=s.addListener)==null||a.call(s,o),()=>{var c;return(c=s.removeListener)==null?void 0:c.call(s,o)})},[t]),t==="system"?n:t}function u0t(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const Ufe=v.createContext({openBrandStudioPreview:()=>{}}),d0t=Ufe.Provider;function f0t(){return v.useContext(Ufe)}function h0t({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const s=hC(t),[o,i]=v.useState(()=>p0t(n)||s),a=v.useCallback(u=>{const d=hC(u);m0t(n,d),i(d)},[n]),c=v.useMemo(()=>({theme:o,setTheme:a}),[o,a]);return l.jsx(kW.Provider,{...r,value:c,children:e})}function p0t(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=hC(t,"system");return n===t?n:null}catch{return null}}function m0t(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const g0t=v.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function p$({appearance:e,children:t}){var I,T;const{authToken:n,id:r,tokenProps:s}=Ct(),o=Q0(),i=(I=o.data)==null?void 0:I.organizationAppearance,a=(T=s.config)==null?void 0:T.appearance,[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,p]=v.useState(null),[g,b]=v.useState(null),[x,y]=v.useState(null),S=`${s.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,w=On({queryKey:AY({resourceType:Xr.DASHBOARD,apiServiceUrl:s.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>m.getRequest(`${s.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:F=>(F==null?void 0:F.organizationAppearance)??null,enabled:!o.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});v.useEffect(()=>{i!==void 0&&y({scopeKey:S,appearance:i})},[i,S]),v.useEffect(()=>{w.data!==void 0&&y({scopeKey:S,appearance:w.data})},[w.data,S]);const C=(x==null?void 0:x.scopeKey)===S?x.appearance:null,N=i!==void 0?i:w.data!==void 0?w.data:C,k=v.useMemo(()=>Wc.resolveAppearance({organizationAppearance:N,tokenAppearance:a,reactAppearance:e}),[e,N,a]),_=v.useCallback(()=>{f(g??h??k),u(!0)},[g,h,k]),E=v.useCallback(()=>{u(!1)},[]);v.useEffect(()=>{f(null),p(null),b(null),u(!1)},[r]);const D=v.useMemo(()=>({openBrandStudioPreview:_}),[_]),j=g??h??e;return l.jsx(h0t,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(d0t,{value:D,children:l.jsx(Hfe,{organizationAppearance:N,tokenAppearance:a,reactAppearance:j,style:{height:"100%",width:"100%"},children:l.jsxs(m.TooltipProvider,{delayDuration:0,children:[t,c&&l.jsx("aside",{"aria-label":"Brand Studio","aria-modal":"false",role:"dialog",className:"fixed bottom-0 right-0 top-0 z-50 flex w-[min(520px,100vw)] flex-col border-l border-border bg-background text-foreground shadow-sm",children:l.jsx(v.Suspense,{fallback:l.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:l.jsx(g0t,{appearance:d,onDraftChange:b,onSave:F=>{p(F),b(F),f(F)},onCancel:E})})})]})})})})}function Wfe({children:e,preferences:t}){const{currentUser:n}=ta(),r=v.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return l.jsx(IY.Provider,{value:r,children:l.jsx(kj,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function b0t(e=2e3,t=500){const n=Ipe(),[r,s]=v.useState(!1),[o,i]=v.useState(!1),a=v.useRef(null);return v.useEffect(()=>{const c=setTimeout(()=>s(!0),e);return()=>clearTimeout(c)},[e]),v.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function m$({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=b0t(e,t);return v.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function qfe(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Aa,{FallbackComponent:Cj,children:l.jsxs(lF,{dashboardProps:e,children:[l.jsx(m$,{componentType:"dashboard",componentId:e.id}),l.jsx(p$,{appearance:e.appearance,children:l.jsx(Wfe,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(YF,{...e,type:"dashboard",children:l.jsx(Vfe,{})})})})})]})})}function x0t(e=[]){const t=v.useRef(null),n=v.useRef(null),r=v.useRef(null),[s,o]=v.useState(),i=v.useCallback(()=>{var p,g,b;const a=((p=t.current)==null?void 0:p.clientWidth)??0,c=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);o(x=>x===h?x:h)},[]);return v.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function y0t({filter:e}){var g;const t=m.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=xg(),r=Wh((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),s=m.useDashboardStore(b=>b.filterValues),o=s==null?void 0:s.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=m.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:p}=x0t([t,o,r]);return v.useEffect(()=>{p()},[e.title,p]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(m.Label,{className:"my-1 block w-full text-sm",children:l.jsx(Zi,{value:e.title||e.column,onSave:b=>c({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(gL,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(m.X,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function v0t(){const e=m.useDashboardStore(r=>r.dashboard.filters),t=m.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:m.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(y0t,{filter:r}),l.jsx(gj,{filter:r})]},r.id))}):null}function w0t(){var i;const e=m.useDashboardStore(a=>a.dashboard),t=m.useDashboardStore(a=>a.selectedSheetId),n=m.useDashboardStore(a=>a.isVisualEditing),r=m.useDashboardStore(a=>a.isDashboardEditing),s=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),o=m.isDocumentSheet(s);return l.jsx("div",{role:"dashboard-plus-main",className:m.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:l.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!o&&l.jsx(v0t,{}),l.jsx(Vfe,{})]})})}const S0t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CilLVS_Q.js"))),C0t=v.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-C_3NYnPz.js"))),N0t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-ClH0kTga.js"))),k0t=v.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-N5iUOE89.js")).then(e=>({default:e.ResourceManagementPanel})));function _0t({showControls:e=!1,showFooter:t=!0,...n}){const r=m.useDashboardStore(u=>u.isDashboardPanelOpen),s=m.useDashboardStore(u=>u.isVisualEditing),o=m.useDashboardStore(u=>u.showDashboardJSON),i=m.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{appearance:a,preferences:c}=n;return l.jsx(Aa,{FallbackComponent:Cj,children:l.jsxs(lF,{dashboardProps:n,children:[l.jsx(m$,{componentType:"surfboard",componentId:n.id}),l.jsxs(p$,{appearance:a,children:[l.jsx(Ebe,{toastOptions:{classNames:{toast:"max-w-[calc(100vw-2rem)] overflow-x-hidden !items-start [--toast-close-button-end:0.5rem] [--toast-close-button-start:auto] [--toast-close-button-transform:translate(0,0)] sm:max-w-[44rem]",content:"min-w-0 flex-1",icon:"mt-0.5 shrink-0",title:"max-w-full break-words pr-8",description:"max-w-full break-words",closeButton:"!top-2 h-6 w-6 rounded-md border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"}}}),l.jsxs(Wfe,{preferences:c,children:[o&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(N0t,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(S0t,{})}),l.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(k0t,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(YF,{...n,type:"dashboard",children:[s&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(C0t,{})}),l.jsx(w0t,{})]})})]})]})]})]})]})})}var j0t=Object.defineProperty,E0t=(e,t,n)=>t in e?j0t(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xS=(e,t,n)=>E0t(e,typeof t!="symbol"?t+"":t,n);const D0t={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},I0t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{if(typeof window<"u"&&e in window)return window[e];if(typeof global<"u"&&e in global)return global[e]})();return typeof r=="function"?r.bind(n):void 0}},T0t={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function M0t(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function Yfe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const A0t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=Yfe(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},R0t={stringify:e=>`${e}`,parse:e=>parseFloat(e)},F0t={stringify:e=>e,parse:e=>e},d2={string:F0t,number:R0t,boolean:D0t,function:I0t,method:A0t,json:T0t},dx=Symbol.for("r2wc.render"),yS=Symbol.for("r2wc.connected"),Xd=Symbol.for("r2wc.context"),li=Symbol.for("r2wc.props");function P0t(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const p of i){c[p]=Array.isArray(t.props)?"string":t.props[p];const g=M0t(p);d[p]=g,f[g]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),xS(this,o,!0),xS(this,s),xS(this,r,{}),xS(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[li].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=c[g],S=y?d2[y]:null;if(y==="method"){const w=Yfe(b);Object.defineProperty(this[li].container,w,{enumerable:!0,configurable:!0,get(){return this[li][w]},set(C){this[li][w]=C,this[dx]()}}),this[li][g]=S.parse(x,b,this)}S!=null&&S.parse&&x&&(this[li][g]=S.parse(x,b,this))}for(const g of a)this[li][g]=b=>{const x=g.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:b,...u[g]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[yS]=!0,this[dx]()}disconnectedCallback(){this[yS]=!1,this[Xd]&&n.unmount(this[Xd]),delete this[Xd]}attributeChangedCallback(g,b,x){const y=f[g],S=c[y],w=S?d2[S]:null;y in c&&w!=null&&w.parse&&x&&(this[li][y]=w.parse(x,g,this),this[dx]())}[(o=yS,s=Xd,r=li,dx)](){this[yS]&&(this[Xd]?n.update(this[Xd],this[li]):this[Xd]=n.mount(this.container,e,this[li]))}}for(const p of i){const g=d[p],b=c[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[li][p]},set(x){this[li][p]=x;const y=b?d2[b]:null;if(y!=null&&y.stringify){const S=y.stringify(x,g,this);this.getAttribute(g)!==S&&this.setAttribute(g,S)}else this[dx]()}})}return h}function O0t(e,t,n){const r=CW.createRoot(e),s=v.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function L0t({root:e,ReactComponent:t},n){const r=v.createElement(t,n);e.render(r)}function $0t({root:e}){e.unmount()}function z0t(e,t={}){return P0t(e,t,{mount:O0t,update:L0t,unmount:$0t})}const B0t={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},V0t=z0t(qfe,{props:B0t}),H0t=v.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(g3,{context:t})," "]})}),Gfe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),U0t=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),W0t=Array.from(Gfe).join(", "),q0t=3,Y0t="Self-heal",G0t=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function K0t({card:e}){var Y,O,K,q,M;const[t,n]=v.useState({}),{authToken:r}=Ct(),s=m.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:o}=m.useAppearance(),i=v.useMemo(()=>Yv(o),[o]),a=m.useEditorStore(G=>G.frame),c=m.useEditorStore(G=>G.inlineFilterValuesMap[e.id]),u=m.useEditorStore(G=>G.actions.setCardInlineFilterValue),d=m.useEditorStore(G=>G.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:p}=Qh(((Y=f.customCardPreferences)==null?void 0:Y.url)||""),g=(O=p==null?void 0:p.visuals)==null?void 0:O.find(G=>{var L;return G.name===((L=f.customCardPreferences)==null?void 0:L.componentName)}),b=Gv(f,g)??"single",x=v.useMemo(()=>wL({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=v.useMemo(()=>{const G=x.findIndex(L=>(L==null?void 0:L.id)===e.id);return G<0?-1:y0(e,G)},[x,e]),S=v.useMemo(()=>b!=="multiple"||y<0?e.type:pm(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),w=v.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:S!==e.type?{...e,type:S}:e,[e,S,b]),{data:C}=f_(w),N=m.useInteractionStore(G=>G.interactionStates),k=m.useDashboardStore(G=>{var L;return(L=G.dashboard)==null?void 0:L.id}),_=m.useDashboardStore(G=>G.dashboard.filters),E=m.useDashboardStore(G=>G.filterValues),D=m.useDashboardStore(G=>G.selectedSheetId),j=v.useMemo(()=>xL({card:e,sheetId:D||"",inlineFilterValues:c,setInlineFilterValue:G=>u(e.id,G),removeInlineFilterValue:G=>d(e.id,G)}),[e,D,c,u,d]),{cardFilters:I,cardFilterValues:T}=v.useMemo(()=>dv({card:e,interactionStates:N,currentDashboardId:k,filters:_,filterValues:E,selectedSheetId:D}),[e,N,k,_,E,D]),F=v.useCallback((G,L)=>{const $=CL(L);n(V=>({...V,[G]:$}))},[]),P=(K=f.customCardPreferences)==null?void 0:K.componentName,R=P?h(P):null,B=FN((q=f.customCardPreferences)==null?void 0:q.settings,f),z=v.useMemo(()=>vL(x),[x]),U=v.useMemo(()=>z.map((G,L)=>pm(G,L,g==null?void 0:g.slots)),[z,g==null?void 0:g.slots]);return P?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(v.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[R&&b==="single"&&l.jsx(R,{editing:!0,params:s,theme:i,settings:B,cardMetadata:oie({card:e,dataMetadata:C==null?void 0:C.metadata}),onDataChange:F,data:(C==null?void 0:C.records)||[],filters:I,filterValues:[...T||[],...c||[]],inlineFilters:j}),R&&b==="multiple"&&l.jsxs(l.Fragment,{children:[x.map((G,L)=>{if(!G)return null;const $=y0(G,L),V=pm(G,$,g==null?void 0:g.slots);return l.jsx(U5,{onDataChange:F,card:G,effectiveCardType:V},`${G.id}-${$}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(R,{editing:!0,onDataChange:F,...NL({configCard:f,slotOrderedCards:z,slotTypes:U,multiInputData:t,params:s,theme:i,chartSettings:B,filters:I,filterValues:[...T||[],...c||[]],inlineFilters:j})})})]})]},(M=f.customCardPreferences)==null?void 0:M.componentName)}):null}const Z0t=v.memo(K0t,(e,t)=>{var n,r,s,o,i,a,c,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((c=e.card.customCardPreferences)==null?void 0:c.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),X0t=m.create()(m.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var Kfe=["PageUp","PageDown"],Zfe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Xfe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},bb="Slider",[QR,Q0t,J0t]=m.createCollection(bb),[Qfe]=m.createContextScope(bb,[J0t]),[evt,fE]=Qfe(bb),Jfe=Q.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:p=!1,form:g,...b}=e,x=Q.useRef(new Set),y=Q.useRef(0),w=i==="horizontal"?tvt:nvt,[C=[],N]=m.useControllableState({prop:d,defaultProp:u,onChange:I=>{var F;(F=[...x.current][y.current])==null||F.focus(),f(I)}}),k=Q.useRef(C);function _(I){const T=avt(C,I);j(I,T)}function E(I){j(I,y.current)}function D(){const I=k.current[y.current];C[y.current]!==I&&h(C)}function j(I,T,{commit:F}={commit:!1}){const P=dvt(o),R=fvt(Math.round((I-r)/o)*o+r,P),B=m.clamp(R,[r,s]);N((z=[])=>{const U=ovt(z,B,T);if(uvt(U,c*o)){y.current=U.indexOf(B);const Y=String(U)!==String(z);return Y&&F&&h(U),Y?U:z}else return z})}return l.jsx(evt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:y,thumbs:x.current,values:C,orientation:i,form:g,children:l.jsx(QR.Provider,{scope:e.__scopeSlider,children:l.jsx(QR.Slot,{scope:e.__scopeSlider,children:l.jsx(w,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:m.composeEventHandlers(b.onPointerDown,()=>{a||(k.current=C)}),min:r,max:s,inverted:p,onSlideStart:a?void 0:_,onSlideMove:a?void 0:E,onSlideEnd:a?void 0:D,onHomeKeyDown:()=>!a&&j(r,0,{commit:!0}),onEndKeyDown:()=>!a&&j(s,C.length-1,{commit:!0}),onStepKeyDown:({event:I,direction:T})=>{if(!a){const R=Kfe.includes(I.key)||I.shiftKey&&Zfe.includes(I.key)?10:1,B=y.current,z=C[B],U=o*R*T;j(z+U,B,{commit:!0})}}})})})})});Jfe.displayName=bb;var[ehe,the]=Qfe(bb,{startEdge:"left",endEdge:"right",size:"width",direction:1}),tvt=Q.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=Q.useState(null),p=m.useComposedRefs(t,w=>h(w)),g=Q.useRef(void 0),b=m.useDirection(s),x=b==="ltr",y=x&&!o||!x&&o;function S(w){const C=g.current||f.getBoundingClientRect(),N=[0,C.width],_=g$(N,y?[n,r]:[r,n]);return g.current=C,_(w-C.left)}return l.jsx(ehe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:l.jsx(nhe,{dir:b,"data-orientation":"horizontal",...d,ref:p,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:w=>{const C=S(w.clientX);i==null||i(C)},onSlideMove:w=>{const C=S(w.clientX);a==null||a(C)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:w=>{const N=Xfe[y?"from-left":"from-right"].includes(w.key);u==null||u({event:w,direction:N?-1:1})}})})}),nvt=Q.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=Q.useRef(null),f=m.useComposedRefs(t,d),h=Q.useRef(void 0),p=!s;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],w=g$(y,p?[r,n]:[n,r]);return h.current=x,w(b-x.top)}return l.jsx(ehe,{scope:e.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:l.jsx(nhe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);o==null||o(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Xfe[p?"from-bottom":"from-top"].includes(b.key);c==null||c({event:b,direction:y?-1:1})}})})}),nhe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=fE(bb,n);return l.jsx(m.Primitive.span,{...u,ref:t,onKeyDown:m.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):Kfe.concat(Zfe).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:m.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:m.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&s(f)}),onPointerUp:m.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),rhe="SliderTrack",she=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=fE(rhe,n);return l.jsx(m.Primitive.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});she.displayName=rhe;var JR="SliderRange",ohe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=fE(JR,n),o=the(JR,n),i=Q.useRef(null),a=m.useComposedRefs(t,i),c=s.values.length,u=s.values.map(h=>lhe(h,s.min,s.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(m.Primitive.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});ohe.displayName=JR;var eF="SliderThumb",ihe=Q.forwardRef((e,t)=>{const n=Q0t(e.__scopeSlider),[r,s]=Q.useState(null),o=m.useComposedRefs(t,a=>s(a)),i=Q.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return l.jsx(rvt,{...e,ref:o,index:i})}),rvt=Q.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=fE(eF,n),a=the(eF,n),[c,u]=Q.useState(null),d=m.useComposedRefs(t,S=>u(S)),f=c?i.form||!!c.closest("form"):!0,h=m.useSize(c),p=i.values[r],g=p===void 0?0:lhe(p,i.min,i.max),b=ivt(r,i.values.length),x=h==null?void 0:h[a.size],y=x?lvt(x,g,a.direction):0;return Q.useEffect(()=>{if(c)return i.thumbs.add(c),()=>{i.thumbs.delete(c)}},[c,i.thumbs]),l.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[l.jsx(QR.ItemSlot,{scope:e.__scopeSlider,children:l.jsx(m.Primitive.span,{role:"slider","aria-label":e["aria-label"]||b,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...o,ref:d,style:p===void 0?{display:"none"}:e.style,onFocus:m.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&l.jsx(ahe,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:p},r)]})});ihe.displayName=eF;var svt="RadioBubbleInput",ahe=Q.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=Q.useRef(null),o=m.useComposedRefs(s,r),i=m.usePrevious(t);return Q.useEffect(()=>{const a=s.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),l.jsx(m.Primitive.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});ahe.displayName=svt;function ovt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function lhe(e,t,n){const o=100/(n-t)*(e-t);return m.clamp(o,[0,100])}function ivt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function avt(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function lvt(e,t,n){const r=e/2,o=g$([0,50],[0,r]);return(r-o(t)*n)*n}function cvt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function uvt(e,t){if(t>0){const n=cvt(e);return Math.min(...n)>=t}return!0}function g$(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function dvt(e){return(String(e).split(".")[1]||"").length}function fvt(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var che=Jfe,hvt=she,pvt=ohe,mvt=ihe;const uhe=Q.forwardRef(({className:e,...t},n)=>l.jsxs(che,{ref:n,className:m.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx(hvt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(pvt,{className:"absolute h-full bg-primary"})}),l.jsx(mvt,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));uhe.displayName=che.displayName;const dhe=["SUN","MON","TUE","WED","THU","FRI","SAT"],gvt=dhe.reduce((e,t,n)=>({...e,[t]:n}),{}),tc={repeats:"weekly",hour:9,minute:0,weekdays:[1,2,3,4,5],isCustom:!1};function bvt(e){if(!e||!e.trim())return{...tc};const t=e.trim(),r=(t.startsWith("cron(")&&t.endsWith(")")?t.slice(5,-1):t).trim().split(/\s+/);if(r.length<5||r.length>6)return{...tc,isCustom:!0};const[s,o,i,a,c]=r,u=Number(s),d=Number(o);if(!Number.isInteger(u)||u<0||u>59||!Number.isInteger(d)||d<0||d>23)return{...tc,isCustom:!0};if(i==="*"&&(c==="?"||c==="*"))return{...tc,repeats:"daily",hour:d,minute:u};if(i==="?"&&c!=="?"&&c!=="*"){const h=c.split(",").map(p=>p.toUpperCase()).map(p=>gvt[p]).filter(p=>typeof p=="number");if(h.length>0)return{...tc,repeats:"weekly",hour:d,minute:u,weekdays:h}}return i==="1,15"&&(c==="?"||c==="*")?{...tc,repeats:"biweekly",hour:d,minute:u}:i==="1"&&(c==="?"||c==="*")?{...tc,repeats:"monthly",hour:d,minute:u}:{...tc,hour:d,minute:u,isCustom:!0}}function xvt(e){const t=e.minute,n=e.hour;switch(e.repeats){case"daily":return`cron(${t} ${n} * * ? *)`;case"weekly":{const r=e.weekdays.length>0?e.weekdays.slice().sort((s,o)=>s-o).map(s=>dhe[s]).join(","):"MON";return`cron(${t} ${n} ? * ${r} *)`}case"biweekly":return`cron(${t} ${n} 1,15 * ? *)`;case"monthly":return`cron(${t} ${n} 1 * ? *)`}}function fhe(e,t){const n=e<12?"AM":"PM",r=e%12===0?12:e%12,s=t.toString().padStart(2,"0");return`${r}:${s} ${n}`}function yvt(e){return!e||e==="UTC"?"UTC":(e.split("/").pop()??e).replace(/_/g," ")}function vvt(e){if(e.length===7)return"every day";const t=e.slice().sort((s,o)=>s-o);if(t.length===5&&t.every(s=>s>=1&&s<=5))return"weekdays";const r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return t.map(s=>r[s]).join(", ")}function wvt(e,t,n,r){const s=fhe(e.hour,e.minute),o=yvt(t);let i;if(e.isCustom)i=`Custom schedule · ${s} ${o}`;else switch(e.repeats){case"daily":i=`Daily at ${s} ${o}`;break;case"weekly":i=`Weekly · ${vvt(e.weekdays)} at ${s} ${o}`;break;case"biweekly":i=`Every two weeks (1st and 15th) at ${s} ${o}`;break;case"monthly":i=`Monthly on the 1st at ${s} ${o}`;break}const a=[];return n&&n!=="Today"&&a.push(`from ${n}`),r&&a.push(`until ${r}`),a.length>0?`${i}, ${a.join(" ")}`:i}const Svt=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Berlin","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];exports.Accordion=l3;exports.AccordionContent=T0;exports.AccordionItem=D0;exports.AccordionTrigger=I0;exports.AddDataPicker=f$;exports.AggregateTable=W_;exports.Alert=zP;exports.AlertDescription=BP;exports.AlertDialog=Lc;exports.AlertDialogAction=kl;exports.AlertDialogCancel=_l;exports.AlertDialogContent=vl;exports.AlertDialogDescription=Nl;exports.AlertDialogFooter=Sl;exports.AlertDialogHeader=wl;exports.AlertDialogTitle=Cl;exports.AlertDialogTrigger=V2;exports.AlertTitle=wX;exports.ArrowDown=Js;exports.ArrowDownIcon=wqe;exports.ArrowLeft=ev;exports.ArrowRight=Sk;exports.ArrowUp=eo;exports.ArrowUpIcon=Cqe;exports.AssistantContextEntityControls=XR;exports.AssistantStatus=lde;exports.AtSign=QW;exports.AxisConfigurator=jg;exports.Badge=Yr;exports.Bell=SS;exports.BookType=eq;exports.BulletChartIcon=ade;exports.COMMON_TIMEZONES=Svt;exports.CSS=_i;exports.CalculatedFieldEditor=yle;exports.Calculator=nq;exports.Calendar=gi;exports.Calendar$1=ZS;exports.CalendarRange=rq;exports.Card=Tm;exports.CardContent=wk;exports.CardHeader=vk;exports.CardSummary=dR;exports.CardTitle=mg;exports.ChartArea=F2;exports.ChartColumnIncreasing=sq;exports.ChartColumnStacked=oq;exports.ChartJsVisual=$v;exports.ChartLine=iq;exports.ChartNoAxesGantt=lq;exports.ChartPie=cq;exports.ChartScatter=uq;exports.ChatInputWithContext=h$;exports.Checkbox=Ln;exports.ChevronLeft=Oh;exports.ChevronRight=Mr;exports.Circle=Ck;exports.CircleAlert=ih;exports.CircleCheck=hq;exports.CircleHelp=pq;exports.Clock=fF;exports.CodeHighlighter=Uu;exports.CodeXml=Bf;exports.Collapsible=Vc;exports.CollapsibleContent=Uc;exports.CollapsibleTrigger=Hc;exports.ColorField=Bi;exports.Command=Pj;exports.CommandEmpty=Lj;exports.CommandGroup=$j;exports.CommandInput=ZL;exports.CommandItem=zj;exports.CommandList=Oj;exports.CommandSeparator=$ae;exports.ComparisonMetadataBadge=Wee;exports.Container=YF;exports.ControlDefaultValueEditor=Ble;exports.ControlDefinitionOptionsEditor=zle;exports.ControlIdInput=Ple;exports.ControlVisibilitySettings=$tt;exports.Copy=Pc;exports.CopyButton=Ac;exports.CopyPlus=O2;exports.Cross2Icon=jqe;exports.CustomFilterPopover=gL;exports.CustomScrollArea=zl;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=GJ;exports.DEFAULT_SCHEDULE_VM=tc;exports.Dashboard=qfe;exports.DashboardActionsMenu=TY;exports.DashboardCard=Wie;exports.DashboardCreateDialogBase=aG;exports.DashboardExportDialog=$fe;exports.DashboardPlus=_0t;exports.DashboardWC=V0t;exports.DataAppBuilder=pK;exports.DataTableConditionalFormattingSettings=Dce;exports.DataTablePagination=z_;exports.Database=ei;exports.DateRangePicker=Z5;exports.DefaultChatTransport=c$;exports.Dialog=Oo;exports.DialogContent=mo;exports.DialogDescription=si;exports.DialogFooter=Gc;exports.DialogHeader=na;exports.DialogTitle=go;exports.DialogTrigger=oG;exports.DisplayPreferencesProvider=kj;exports.DndContext=ow;exports.Donut=mq;exports.Download=qc;exports.DownloadPdf=zfe;exports.DragOverlay=kae;exports.DropdownMenu=Ao;exports.DropdownMenuCheckboxItem=bu;exports.DropdownMenuContent=fo;exports.DropdownMenuItem=jn;exports.DropdownMenuLabel=kc;exports.DropdownMenuRadioGroup=tbe;exports.DropdownMenuRadioItem=DY;exports.DropdownMenuSeparator=Ea;exports.DropdownMenuSub=TF;exports.DropdownMenuSubContent=Tk;exports.DropdownMenuSubTrigger=Ik;exports.DropdownMenuTrigger=Ro;exports.EMPTY_DATA_SOURCE=z0;exports.Editable=ON;exports.EditableText=Zi;exports.EditorCustomVisual=Z0t;exports.Ellipsis=ja;exports.EllipsisVertical=Lh;exports.ErrorBoundary=Aa;exports.ExportError=Rg;exports.ExternalLink=Am;exports.Eye=tv;exports.EyeOff=Nk;exports.Fallback=Cj;exports.FallbackVisual=w0;exports.FeedbackCategory=xd;exports.FeedbackDialog=L0;exports.FieldsList=g3;exports.FieldsSection=H0t;exports.FileSpreadsheet=gq;exports.FileText=vi;exports.Filter=ah;exports.FilterComponent=gj;exports.FilterInfo=aR;exports.FilterableFieldsPanel=wle;exports.Globe=gg;exports.Grid3x3=bq;exports.GripVertical=Yc;exports.HEATMAP_PRESET_PALETTES=YM;exports.Hash=xq;exports.House=yq;exports.HoverCard=Pg;exports.HoverCardContent=cd;exports.HoverCardTrigger=Og;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=Gfe;exports.INLINE_ALLOWED_TOOL_LIST=W0t;exports.INLINE_BLOCKED_MUTATING_TOOLS=U0t;exports.IconButton=Vu;exports.IconForFieldType=rC;exports.InfoHover=LL;exports.InlineFilterBar=Fie;exports.KPICard=Th;exports.KeyboardSensor=rw;exports.Layers=nv;exports.LayoutDashboard=Rm;exports.Link=hF;exports.LoadingDots=dd;exports.Lock=kk;exports.MAX_SELF_HEAL_ATTEMPTS=q0t;exports.Map=Sq;exports.Markdown=bue;exports.Maximize2=_k;exports.MdStackedLineChart=ode;exports.Minimize2=pF;exports.MultiInputEmptyRenderer=U5;exports.PYTHON_DEFAULT_CODE=tF;exports.PanelLeft=mF;exports.PanelResizeHandle=qk;exports.Paperclip=Nq;exports.PenLine=L2;exports.Pencil=$2;exports.PendingMessagesDisplay=Rfe;exports.PersistedDynamicVisual=Nj;exports.PiChartPolar=tde;exports.PivotTableTanstack=rb;exports.Placeholders=ude;exports.Play=kq;exports.Plus=dr;exports.PointerSensor=cb;exports.PrintMessages=cde;exports.Progress=J3;exports.RECOVERABLE_SQL_ERROR_CODES=G0t;exports.Radar=_q;exports.RadioGroup=Ia;exports.RadioGroupItem=js;exports.RefreshCw=Oc;exports.ResizableHandle=uK;exports.ResizablePanel=Ry;exports.ResizablePanelGroup=UF;exports.ResourceEditDialog=LG;exports.ResourceType=Xr;exports.SELF_HEAL_TIMELINE_STEP=Y0t;exports.Search=Ws;exports.SeedQuestions=Efe;exports.SemaphorContext=pg;exports.SemaphorContextProvider=lF;exports.SemaphorQueryClient=qW;exports.SemaphorReadyIndicator=m$;exports.SemaphorStyleWrapper=sb;exports.Send=bF;exports.Settings=xF;exports.Settings2=bg;exports.Share2=jq;exports.ShareDialog=OG;exports.Sheet=Aee;exports.SheetContent=BO;exports.SheetDescription=HO;exports.SheetHeader=Fee;exports.SheetTitle=VO;exports.SheetTrigger=DOe;exports.Slider=uhe;exports.SortableContext=iw;exports.Sparkles=Fm;exports.Square=Eq;exports.SquarePen=jk;exports.Star=yF;exports.StructuralParticipantSelector=Ole;exports.SummaryCard=sR;exports.TABLE_PRESENTATION_DEFAULT_STYLE=Xu;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=Ui;exports.TableBody=xh;exports.TableCell=sr;exports.TableColumnVisibilitySettings=bce;exports.TableHead=Ko;exports.TableHeader=Fg;exports.TablePresentationSettings=yce;exports.TableRow=Kr;exports.TableSkeleton=$L;exports.TableVisual=ud;exports.TbChartBubble=nde;exports.TbChartFunnel=rde;exports.TbChartTreemap=sde;exports.TextCard=og;exports.Textarea=Bh;exports.TiSortNumerically=ide;exports.Toggle=wj;exports.Tornado=Dq;exports.Trash2=yl;exports.TreePalm=wF;exports.TrendingUp=Iq;exports.TriangleAlert=ba;exports.TypeGlyph=Qv;exports.UXProvider=p$;exports.User=Mq;exports.UserRound=Tq;exports.Users=SF;exports.applyFilterOverridesToDashboardInputSlots=BZ;exports.areContextEntitiesEqual=zr;exports.areEntitiesJoined=JJ;exports.arrayMove=ub;exports.buildCardControlUsageById=Btt;exports.buildCustomCardTheme=Yv;exports.buildDashboardCardExecutionSnapshot=zZ;exports.buildDashboardControlUsageById=ztt;exports.buildDashboardExecutionSnapshot=RP;exports.buildDashboardInputExecutionSnapshot=Wu;exports.buildDashboardSheetsInputExecutionSnapshot=HZ;exports.buildDashboardStructuralParticipantIdsByControlId=Ule;exports.buildFilterFieldMeta=n3;exports.buildFilterSemanticContext=r3;exports.buildInlineFilterNodes=xL;exports.buildMultiInputCustomVisualProps=NL;exports.buildScheduleExpr=xvt;exports.buildSchedulePreview=wvt;exports.buildSlotOrderedCards=vL;exports.calculateContextAwareFilters=dv;exports.calculateFieldState=MO;exports.canUserAccessVisuals=bKe;exports.canUserCreateDashboards=gKe;exports.canUserEdit=hKe;exports.canUserManageDashboards=mKe;exports.canUserManageGroups=xKe;exports.canUserUseFilters=pKe;exports.cancelExport=bPe;exports.chartSupportsDataLabels=WQ;exports.chartSupportsLegend=HQ;exports.chartTypes=iE;exports.cleanupKpiMetricComparisonMode=Yae;exports.cloneDeep=Zo;exports.cloneLinkedFrameWithSourceMapping=LGe;exports.closestCenter=nw;exports.commitSharedCalculatedFields=af;exports.createAssistantConversationId=qp;exports.createAssistantRequestId=_fe;exports.createCardsFromSlots=eYe;exports.createChartConfig=Ag;exports.createDashboardControlInputFromControl=Pst;exports.createDefaultGlobalDateFilter=ZCe;exports.createExport=yee;exports.createUniqueDashboardInputVariableNameFromName=Ju;exports.dedup=Jxt;exports.doesStoredFilterMatchField=ug;exports.downloadDocumentPdf=PP;exports.downloadPdf=XZ;exports.extractSqlParamReferences=Yse;exports.extractTableMetadata=t3;exports.fieldAlreadyExists=tee;exports.findCustomVisualConfigCard=SL;exports.findDashboardFrameById=BCe;exports.flexRender=Qo;exports.formatDisplayFormula=AJe;exports.formatFileSize=vPe;exports.formatFilterLine=CX;exports.formatTimeLabel=fhe;exports.getAutoDetectedChartIcon=Wft;exports.getChartGridStyle=v_e;exports.getChartIconByType=qft;exports.getColorForValue=uM;exports.getConfigSlotExpectedType=Jqe;exports.getCoreRowModel=O_;exports.getCustomVisualInputCards=wL;exports.getDateFormatOptionsForGranularity=j0;exports.getDefaultAxisConfig=fM;exports.getDefaultChartColors=qh;exports.getDefaultDataLabelsConfig=Cv;exports.getDefaultExportFormat=zX;exports.getDefaultFilterSql=tL;exports.getDefaultLegendConfig=mO;exports.getDefaultRunningTotalPartitionByFieldIds=vy;exports.getDocumentSectionEditorCard=xtt;exports.getDocumentSheetDashboardInputs=dw;exports.getDownloadUrl=gPe;exports.getEffectiveCardTypeForSlot=pm;exports.getEntityIcon=xk;exports.getErrorMessage=xfe;exports.getExportStatus=mPe;exports.getExports=pPe;exports.getExpressionFieldKind=bd;exports.getFieldExpressionAnnotation=s3;exports.getFilterCount=VN;exports.getGlobalDateFilter=wg;exports.getGlobalDateFilterCoverage=XCe;exports.getGranularityOptionsForFieldType=S3;exports.getKeys=pr;exports.getMetricDisplayLabel=PFe;exports.getNewField=iee;exports.getObjectDiff=_W;exports.getPaginationRowModel=L_;exports.getRoleBasedDisplayOverrides=Rie;exports.getRunningTotalOrderByCandidates=nJe;exports.getSelectedDateFilterColumn=Kse;exports.getSheetScopedFilterValues=Ly;exports.getSlotDefinitionForIndex=yL;exports.getSlotExpectedChartType=yj;exports.getSlotIndexForCard=y0;exports.getSortedRowModel=Mee;exports.getSupportedExportFormats=$X;exports.getTableConditionalFormattingColumnOptions=Cce;exports.getTableOutputColumnOptions=Nce;exports.getTablePageSizeOptions=gee;exports.handleAggregationChange=lR;exports.handleAggregationLabelChange=Mie;exports.hasFlatTableTotalsBehavior=WNe;exports.horizontalListSortingStrategy=qL;exports.isCalculatedFilterField=E0;exports.isCardSummaryVisibleOnCard=kL;exports.isCustomVisualConfigCard=nR;exports.isDefaultColor=eke;exports.isEligibleFlatTableTotalsCard=Sg;exports.isExportComplete=yPe;exports.isExportInProgress=xPe;exports.isInAiScopeArray=Qxt;exports.isManagedCalculatedExpressionField=ka;exports.isMetricTransformEnabled=eJe;exports.isPromiseLike=KR;exports.isSubtotalEnabledAggregateTable=e3;exports.isSupportedDocumentTableCardType=ytt;exports.lastAssistantMessageIsCompleteWithToolCalls=pfe;exports.merge=xl;exports.mergeAxisConfig=hM;exports.normalizeConditionalFormatting=jP;exports.normalizeContextFormatMode=DX;exports.normalizeDashboardInputVariableName=J0;exports.normalizeMultiInputPayload=CL;exports.parseScheduleExpr=bvt;exports.pivotData=gv;exports.prepareFeedbackData=oE;exports.purify=PA;exports.reindexSlotCards=Qqe;exports.remarkGfm=Bue;exports.removeFromScopeArray=eyt;exports.resolveDashboardInputContext=$l;exports.resolveDomainCalculatedFieldForEdit=Iet;exports.resolveMultiInputType=Gv;exports.resolveMultiInputTypeFromVisual=tYe;exports.resolveTablePageSize=R_;exports.resolveTablePresentationStyle=JO;exports.sanitizeAIScope=bfe;exports.saveCalculatedFieldToCardScope=vR;exports.saveCalculatedFieldToSharedScope=vle;exports.saveCalculatedFieldToSheetScope=wR;exports.seedSemanticMetricFormatDefaults=Kae;exports.setTableColumnVisibility=See;exports.setupEditorWithCard=h_;exports.showAllTableColumns=NPe;exports.showJoinRequiredNotification=eee;exports.sortByColumnsToSortState=tte;exports.sortStateToSortByColumns=nte;exports.sortableKeyboardCoordinates=GL;exports.supportsMetricTransformForMetric=Gae;exports.supportsTableConditionalFormatting=vce;exports.toEntityArray=Na;exports.ue=ut;exports.useActiveExports=awe;exports.useActiveToolStatus=Lfe;exports.useAddFrameWithFreshSemanticExecutionPayload=OL;exports.useAddNewFrame=tae;exports.useAssistantContainer=bK;exports.useAssistantContextEntities=jj;exports.useAssistantLayoutStore=Hf;exports.useAssistantPanel=mK;exports.useAssistantProfile=jfe;exports.useAutoScroll=Pfe;exports.useAutoSubmitQueue=Ffe;exports.useBrandStudioPreview=f0t;exports.useCard=GFe;exports.useCardFilterValues=lee;exports.useCardSummary=_L;exports.useChat=gfe;exports.useColumns=XL;exports.useCreateVisualWithFrame=Ybe;exports.useCurrentUserInfo=ta;exports.useCustomVisual=Qh;exports.useCustomVisualsQuery=mL;exports.useDashboardAppearance=Rl;exports.useDashboardById=LY;exports.useDashboardCreation=BY;exports.useDashboardManagement=zY;exports.useDashboardPreferences=xg;exports.useDashboardQuery=Q0;exports.useDashboardStructuralParticipants=Wle;exports.useDashboardSummary=pie;exports.useDataColumns=Xae;exports.useDateFilterHook=M7e;exports.useDebounce=py;exports.useDefaultDashboardMutation=MY;exports.useDisplayPreferences=Ll;exports.useDroppable=Nae;exports.useEditorAside=Bj;exports.useEditorCardQuery=f_;exports.useEnsureReactGlobals=Sse;exports.useExportActions=xK;exports.useExportStore=Yk;exports.useFieldManagement=Zae;exports.useFilterableFields=Uae;exports.useFullscreenAssistant=gK;exports.useGroupMembers=Vxe;exports.useGroups=DG;exports.useHasDashboardId=yK;exports.useInProgressExportsCount=lwe;exports.useIsDashboardSelected=Rpe;exports.useIsVisualSelected=Fpe;exports.useJoinabilityMap=JL;exports.useManagementActions=Ph;exports.useManagementStore=is;exports.useMessageWindow=Ofe;exports.useMutation=co;exports.usePivotTableConfig=Gh;exports.usePluginQuery=eie;exports.useQuery=On;exports.useQueryClient=ns;exports.useReactTable=$_;exports.useResolveExistingFrameSemanticExecutionPayload=VGe;exports.useResourceManagement=Rk;exports.useResourceUpdateState=$Y;exports.useScopedFields=Hae;exports.useSelectedVisual=Ape;exports.useSemaphorContext=Ct;exports.useSensor=cg;exports.useSensors=Tj;exports.useSortable=db;exports.useStarredChartsStore=X0t;exports.useSurfaceAppearance=Zc;exports.useTableQueryState=qee;exports.useTextFilterHook=H7e;exports.useTheme=nF;exports.useTopoJson=kv;exports.useUnifiedUsers=OF;exports.useUpdateResource=RY;exports.useUpdateVisualMutation=Gbe;exports.useUserPreferences=lG;exports.useVisualById=Ak;exports.useVisualManagement=qbe;exports.validateFieldForChartType=qae;exports.verticalListSortingStrategy=YL;