react-semaphor 0.1.191 → 0.1.192
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{calendar-preferences-dialog-8DbVu7qv.js → calendar-preferences-dialog-CMM-uye9.js} +1 -1
- package/dist/chunks/{calendar-preferences-dialog-C58Ao0Su.js → calendar-preferences-dialog-wu_fGBRY.js} +1 -1
- package/dist/chunks/{dashboard-controls-DGNpPquj.js → dashboard-controls-CZiglER8.js} +5 -5
- package/dist/chunks/{dashboard-controls-DJZwTob9.js → dashboard-controls-DZ3RdkPp.js} +1 -1
- package/dist/chunks/{dashboard-json-2sYazVkw.js → dashboard-json-CBLwtP5m.js} +1 -1
- package/dist/chunks/{dashboard-json-DMe62kZm.js → dashboard-json-DxsH7NvN.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-3P029C4A.js → edit-dashboard-visual-CdR2ywTB.js} +2 -2
- package/dist/chunks/{edit-dashboard-visual-ZMOTcM3N.js → edit-dashboard-visual-DyvG8L5y.js} +1 -1
- package/dist/chunks/{editor-action-buttons-Bz5hRTxe.js → editor-action-buttons-BvRPaQoF.js} +2 -2
- package/dist/chunks/{editor-action-buttons-CgyWdNoq.js → editor-action-buttons-DRX64gHq.js} +1 -1
- package/dist/chunks/{index-Ce7gjui_.js → index-BmPlQ_Vy.js} +2 -2
- package/dist/chunks/{index-9MuaW8XF.js → index-C5wrl3dy.js} +41 -11
- package/dist/chunks/{notification-bell-BIXQYsXD.js → notification-bell-C4cn4uYe.js} +3 -3
- package/dist/chunks/{notification-bell-CR-I7Xa7.js → notification-bell-sAl4kF0A.js} +1 -1
- package/dist/chunks/{resource-management-panel-L-xXWN55.js → resource-management-panel-DNffk7G6.js} +1 -1
- package/dist/chunks/{resource-management-panel-mS3sZyxK.js → resource-management-panel-DRpbtjWO.js} +3 -3
- package/dist/chunks/{use-role-aware-display-preferences-DEY-dIuJ.js → use-role-aware-display-preferences-BIAB5o80.js} +1 -1
- package/dist/chunks/{use-role-aware-display-preferences-Bl22q1yS.js → use-role-aware-display-preferences-DEWoTnfO.js} +1 -1
- package/dist/chunks/{use-visual-utils-C7z9XFum.js → use-visual-utils-BMqAflAg.js} +1 -1
- package/dist/chunks/{use-visual-utils-B210AVkx.js → use-visual-utils-BfZLkFD4.js} +1 -1
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +6 -6
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/dist/types/dashboard.d.ts +8 -0
- package/dist/types/main.d.ts +8 -0
- package/dist/types/surfboard.d.ts +8 -0
- package/dist/types/types.d.ts +8 -0
- package/package.json +1 -1
|
@@ -750,7 +750,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/alert-
|
|
|
750
750
|
*/class Npe{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=TV.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,l;for(;i>=0;--i)l=o[i],l._active?(l._total>r.duration&&(r.duration=l._total),l.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 cl=new Npe;const zO="transparent",kpe={boolean(e,t,n){return n>.5?t:e},color(e,t,n){const r=MO(e||zO),s=r.valid&&MO(t||zO);return s&&s.valid?s.mix(r,n).hexString():t},number(e,t,n){return e+(t-e)*n}};let Epe=class{constructor(t,n,r,s){const o=n[r];s=Kn([t.to,s,o,t.from]);const i=Kn([t.from,o,s]);this._active=!0,this._fn=t.fn||kpe[t.type||typeof i],this._easing=Rg[t.easing]||Rg.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=Kn([t.to,n,s,t.from]),this._from=Kn([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 l;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}l=n/r%2,l=i&&l>1?2-l:l,l=this._easing(Math.min(1,Math.max(0,l))),this._target[s]=this._fn(o,a,l)}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 YV{constructor(t,n){this._chart=t,this._properties=new Map,this.configure(n)}configure(t){if(!Pt(t))return;const n=Object.keys(Qn.animation),r=this._properties;Object.getOwnPropertyNames(t).forEach(s=>{const o=t[s];if(!Pt(o))return;const i={};for(const a of n)i[a]=o[a];(Pn(o.properties)&&o.properties||[s]).forEach(a=>{(a===s||!r.has(a))&&r.set(a,i)})})}_animateOptions(t,n){const r=n.options,s=Tpe(t,r);if(!s)return[];const o=this._createAnimations(s,r);return r.$shared&&_pe(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 l;for(l=i.length-1;l>=0;--l){const u=i[l];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 Epe(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 cl.add(this._chart,r),!0}}function _pe(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 Tpe(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 BO(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 Mpe(e,t,n){if(n===!1)return!1;const r=BO(e,n),s=BO(t,n);return{top:s.end,right:r.end,bottom:s.start,left:r.start}}function Dpe(e){let t,n,r,s;return Pt(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 GV(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 VO(e,t,n,r={}){const s=e.keys,o=r.mode==="single";let i,a,l,u;if(t===null)return;let d=!1;for(i=0,a=s.length;i<a;++i){if(l=+s[i],l===n){if(d=!0,r.all)continue;break}u=e.values[l],br(u)&&(o||t===0||Pa(t)===Pa(u))&&(t+=u)}return!d&&!r.all?0:t}function Ipe(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 l,u,d;for(l=0,u=i.length;l<u;++l)d=i[l],a[l]={[s]:d,[o]:e[d]};return a}function $j(e,t){const n=e&&e.options.stacked;return n||n===void 0&&t.stack!==void 0}function Rpe(e,t,n){return`${e.id}.${t.id}.${n.stack||n.type}`}function Ape(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 Ppe(e,t,n){const r=e[t]||(e[t]={});return r[n]||(r[n]={})}function HO(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 UO(e,t){const{chart:n,_cachedMeta:r}=e,s=n._stacks||(n._stacks={}),{iScale:o,vScale:i,index:a}=r,l=o.axis,u=i.axis,d=Rpe(o,i,r),f=t.length;let h;for(let m=0;m<f;++m){const p=t[m],{[l]:g,[u]:b}=p,x=p._stacks||(p._stacks={});h=x[u]=Ppe(s,d,g),h[a]=b,h._top=HO(h,i,!0,r.type),h._bottom=HO(h,i,!1,r.type);const y=h._visualValues||(h._visualValues={});y[a]=b}}function Lj(e,t){const n=e.scales;return Object.keys(n).filter(r=>n[r].axis===t).shift()}function Ope(e,t){return ju(e,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function Fpe(e,t,n){return ju(e,{active:!1,dataIndex:t,parsed:void 0,raw:void 0,element:n,index:t,mode:"default",type:"data"})}function Lp(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 zj=e=>e==="reset"||e==="none",WO=(e,t)=>t?e:Object.assign({},e),$pe=(e,t,n)=>e&&!t.hidden&&t._stacked&&{keys:GV(n,!0),values:null};class Co{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=$j(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&&Lp(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,n=this._cachedMeta,r=this.getDataset(),s=(f,h,m,p)=>f==="x"?h:f==="r"?p:m,o=n.xAxisID=mt(r.xAxisID,Lj(t,"x")),i=n.yAxisID=mt(r.yAxisID,Lj(t,"y")),a=n.rAxisID=mt(r.rAxisID,Lj(t,"r")),l=n.indexAxis,u=n.iAxisID=s(l,o,i,a),d=n.vAxisID=s(l,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&&EO(this._data,this),t._stacked&&Lp(t)}_dataCheck(){const t=this.getDataset(),n=t.data||(t.data=[]),r=this._data;if(Pt(n)){const s=this._cachedMeta;this._data=Ipe(n,s)}else if(r!==n){if(r){EO(r,this);const s=this._cachedMeta;Lp(s),s._parsed=[]}n&&Object.isExtensible(n)&&Cme(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=$j(n.vScale,n),n.stack!==r.stack&&(s=!0,Lp(n),n.stack=r.stack),this._resyncElements(t),(s||o!==n._stacked)&&(UO(this,n._parsed),n._stacked=$j(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 l=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{Pn(s[t])?h=this.parseArrayData(r,s,t,n):Pt(s[t])?h=this.parseObjectData(r,s,t,n):h=this.parsePrimitiveData(r,s,t,n);const m=()=>f[a]===null||u&&f[a]<u[a];for(d=0;d<n;++d)r._parsed[d+t]=f=h[d],l&&(m()&&(l=!1),u=f);r._sorted=l}i&&UO(this,h)}parsePrimitiveData(t,n,r,s){const{iScale:o,vScale:i}=t,a=o.axis,l=i.axis,u=o.getLabels(),d=o===i,f=new Array(s);let h,m,p;for(h=0,m=s;h<m;++h)p=h+r,f[h]={[a]:d||o.parse(u[p],p),[l]:i.parse(n[p],p)};return f}parseArrayData(t,n,r,s){const{xScale:o,yScale:i}=t,a=new Array(s);let l,u,d,f;for(l=0,u=s;l<u;++l)d=l+r,f=n[d],a[l]={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:l="y"}=this._parsing,u=new Array(s);let d,f,h,m;for(d=0,f=s;d<f;++d)h=d+r,m=n[h],u[d]={x:o.parse(ru(m,a),h),y:i.parse(ru(m,l),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:GV(s,!0),values:n._stacks[t.axis]._visualValues};return VO(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=VO(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),l=$pe(n,r,this.chart),u={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:d,max:f}=Ape(a);let h,m;function p(){m=s[h];const g=m[a.axis];return!br(m[t.axis])||d>g||f<g}for(h=0;h<i&&!(!p()&&(this.updateRangeFromParsed(u,t,m,l),o));++h);if(o){for(h=i-1;h>=0;--h)if(!p()){this.updateRangeFromParsed(u,t,m,l);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],br(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=Dpe(mt(this.options.clip,Mpe(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,l=this._drawCount||s.length-a,u=this.options.drawActiveElementsOnTop;let d;for(r.dataset&&r.dataset.draw(t,o,a,l),d=a;d<a+l;++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=Fpe(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=Ope(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],l=this.enableOptionSharing&&lm(r);if(a)return WO(a,l);const u=this.chart.config,d=u.datasetElementScopeKeys(this._type,t),f=s?[`${t}Hover`,"hover",t,""]:[t,""],h=u.getOptionScopes(this.getDataset(),d),m=Object.keys(Qn.elements[t]),p=()=>this.getContext(r,s,n),g=u.resolveNamedOptions(h,m,p,f);return g.$shared&&(g.$shared=l,o[i]=Object.freeze(WO(g,l))),g}_resolveAnimations(t,n,r){const s=this.chart,o=this._cachedDataOpts,i=`animation-${n}`,a=o[i];if(a)return a;let l;if(s.options.animation!==!1){const d=this.chart.config,f=d.datasetAnimationScopeKeys(this._type,n),h=d.getOptionScopes(this.getDataset(),f);l=d.createResolver(h,this.getContext(t,r,n))}const u=new YV(s,l&&l.animations);return l&&l._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||zj(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){zj(s)?Object.assign(t,r):this._resolveAnimations(n,s).update(t,r)}updateSharedOptions(t,n,r){t&&!zj(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,l,u]of this._syncList)this[a](l,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 l=u=>{for(u.length+=n,a=u.length-1;a>=i;a--)u[a]=u[a-n]};for(l(o),a=t;a<i;++a)o[a]=new this.dataElementType;this._parsing&&l(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&&Lp(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])}}Ue(Co,"defaults",{}),Ue(Co,"datasetElementType",null),Ue(Co,"dataElementType",null);function Lpe(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=_V(r.sort((s,o)=>s-o))}return e._cache.$bar}function zpe(e){const t=e.iScale,n=Lpe(t,e.type);let r=t._length,s,o,i,a;const l=()=>{i===32767||i===-32768||(lm(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]),l();for(a=void 0,s=0,o=t.ticks.length;s<o;++s)i=t.getPixelForTick(s),l();return r}function Bpe(e,t,n,r){const s=n.barThickness;let o,i;return _t(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 Vpe(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 l=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*l;return{chunk:Math.abs(a-i)/2*l/r,ratio:n.barPercentage,start:u}}function Hpe(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 l=i,u=a;Math.abs(i)>Math.abs(a)&&(l=a,u=i),t[n.axis]=u,t._custom={barStart:l,barEnd:u,start:s,end:o,min:i,max:a}}function KV(e,t,n,r){return Pn(e)?Hpe(e,t,n,r):t[n.axis]=n.parse(e,r),t}function qO(e,t,n,r){const s=e.iScale,o=e.vScale,i=s.getLabels(),a=s===o,l=[];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),l.push(KV(h,f,o,u));return l}function Bj(e){return e&&e.barStart!==void 0&&e.barEnd!==void 0}function Upe(e,t,n){return e!==0?Pa(e):(t.isHorizontal()?1:-1)*(t.min>=n?1:-1)}function Wpe(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 qpe(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:l,top:u,bottom:d}=Wpe(e);s==="middle"&&n&&(e.enableBorderRadius=!0,(n._top||0)===r?s=u:(n._bottom||0)===r?s=d:(o[YO(d,i,a,l)]=!0,s=u)),o[YO(s,i,a,l)]=!0,e.borderSkipped=o}function YO(e,t,n,r){return r?(e=Ype(e,t,n),e=GO(e,n,t)):e=GO(e,t,n),e}function Ype(e,t,n){return e===t?n:e===n?t:e}function GO(e,t,n){return e==="start"?t:e==="end"?n:e}function Gpe(e,{inflateAmount:t},n){e.inflateAmount=t==="auto"?n===1?.33:0:t}class Id extends Co{parsePrimitiveData(t,n,r,s){return qO(t,n,r,s)}parseArrayData(t,n,r,s){return qO(t,n,r,s)}parseObjectData(t,n,r,s){const{iScale:o,vScale:i}=t,{xAxisKey:a="x",yAxisKey:l="y"}=this._parsing,u=o.axis==="x"?a:l,d=i.axis==="x"?a:l,f=[];let h,m,p,g;for(h=r,m=r+s;h<m;++h)g=n[h],p={},p[o.axis]=o.parse(ru(g,u),h),f.push(KV(ru(g,d),p,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=Bj(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,l=a.getBasePixel(),u=a.isHorizontal(),d=this._getRuler(),{sharedOptions:f,includeOptions:h}=this._getSharedOptions(n,s);for(let m=n;m<n+r;m++){const p=this.getParsed(m),g=o||_t(p[a.axis])?{base:l,head:l}:this._calculateBarValuePixels(m),b=this._calculateBarIndexPixels(m,d),x=(p._stacks||{})[a.axis],y={horizontal:u,base:g.base,enableBorderRadius:!x||Bj(p._custom)||i===x._top||i===x._bottom,x:u?g.head:b.center,y:u?b.center:g.head,height:u?b.size:Math.abs(g.size),width:u?Math.abs(g.size):b.size};h&&(y.options=f||this.resolveDataElementOptions(m,t[m].active?"active":s));const v=y.options||t[m].options;qpe(y,v,x,i),Gpe(y,v,d.ratio),this.updateElement(t[m],m,y,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),l=a&&a[r.axis],u=d=>{const f=d._parsed.find(m=>m[r.axis]===l),h=f&&f[d.vScale.axis];if(_t(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[mt(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||zpe(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,l=this.getParsed(t),u=l._custom,d=Bj(u);let f=l[n.axis],h=0,m=r?this.applyStack(n,l,r):f,p,g;m!==f&&(h=m-f,m=f),d&&(f=u.barStart,m=u.barEnd-u.barStart,f!==0&&Pa(f)!==Pa(u.barEnd)&&(h=0),h+=f);const b=!_t(o)&&!d?o:h;let x=n.getPixelForValue(b);if(this.chart.getDataVisibility(t)?p=n.getPixelForValue(h+m):p=x,g=p-x,Math.abs(g)<i){g=Upe(g,n,a)*i,f===a&&(x-=g/2);const y=n.getPixelForDecimal(0),v=n.getPixelForDecimal(1),w=Math.min(y,v),j=Math.max(y,v);x=Math.max(Math.min(x,j),w),p=x+g,r&&!d&&(l._stacks[n.axis]._visualValues[s]=n.getValueForPixel(p)-n.getValueForPixel(x))}if(x===n.getPixelForValue(a)){const y=Pa(g)*n.getLineWidthForValue(a)/2;x+=y,g-=y}return{size:g,base:x,head:p,center:p+g/2}}_calculateBarIndexPixels(t,n){const r=n.scale,s=this.options,o=s.skipNull,i=mt(s.maxBarThickness,1/0);let a,l;const u=this._getAxisCount();if(n.grouped){const d=o?this._getStackCount(t):n.stackCount,f=s.barThickness==="flex"?Vpe(t,n,s,d*u):Bpe(t,n,s,d*u),h=this.chart.options.indexAxis==="x"?this.getDataset().xAxisID:this.getDataset().yAxisID,m=this._getAxis().indexOf(mt(h,this.getFirstScaleIdForIndexAxis())),p=this._getStackIndex(this.index,this._cachedMeta.stack,o?t:void 0)+m;a=f.start+f.chunk*p+f.chunk/2,l=Math.min(i,f.chunk*f.ratio)}else a=r.getPixelForValue(this.getParsed(t)[r.axis],t),l=Math.min(i,n.min*n.ratio);return{base:a-l/2,head:a+l/2,center:a,size:l}}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)}}Ue(Id,"id","bar"),Ue(Id,"defaults",{datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}}),Ue(Id,"overrides",{scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}});class Sv extends Co{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=mt(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=mt(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),l=o.getLabelForValue(i.y),u=i._custom;return{label:r[t]||"",value:"("+a+", "+l+(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:l,includeOptions:u}=this._getSharedOptions(n,s),d=i.axis,f=a.axis;for(let h=n;h<n+r;h++){const m=t[h],p=!o&&this.getParsed(h),g={},b=g[d]=o?i.getPixelForDecimal(.5):i.getPixelForValue(p[d]),x=g[f]=o?a.getBasePixel():a.getPixelForValue(p[f]);g.skip=isNaN(b)||isNaN(x),u&&(g.options=l||this.resolveDataElementOptions(h,m.active?"active":s),o&&(g.options.radius=0)),this.updateElement(m,h,g,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+=mt(r&&r._custom,o),s}}Ue(Sv,"id","bubble"),Ue(Sv,"defaults",{datasetElementType:!1,dataElementType:"point",animations:{numbers:{type:"number",properties:["x","y","borderWidth","radius"]}}}),Ue(Sv,"overrides",{scales:{x:{type:"linear"},y:{type:"linear"}}});function Kpe(e,t,n){let r=1,s=1,o=0,i=0;if(t<Xn){const a=e,l=a+t,u=Math.cos(a),d=Math.sin(a),f=Math.cos(l),h=Math.sin(l),m=(v,w,j)=>wb(v,a,l,!0)?1:Math.max(w,w*n,j,j*n),p=(v,w,j)=>wb(v,a,l,!0)?-1:Math.min(w,w*n,j,j*n),g=m(0,u,f),b=m(_r,d,h),x=p(hn,u,f),y=p(hn+_r,d,h);r=(g-x)/2,s=(b-y)/2,o=-(g+x)/2,i=-(b+y)/2}return{ratioX:r,ratioY:s,offsetX:o,offsetY:i}}class dd extends Co{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=l=>+r[l];if(Pt(r[t])){const{key:l="value"}=this._parsing;o=u=>+ru(r[u],l)}let i,a;for(i=t,a=t+n;i<a;++i)s._parsed[i]=o(i)}}_getRotation(){return Bi(this.options.rotation-90)}_getCircumference(){return Bi(this.options.circumference)}_getRotationExtents(){let t=Xn,n=-Xn;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),l=Math.min(ame(this.options.cutout,a),1),u=this._getRingWeight(this.index),{circumference:d,rotation:f}=this._getRotationExtents(),{ratioX:h,ratioY:m,offsetX:p,offsetY:g}=Kpe(f,d,l),b=(r.width-i)/h,x=(r.height-i)/m,y=Math.max(Math.min(b,x)/2,0),v=SV(this.options.radius,y),w=Math.max(v*l,0),j=(v-w)/this._getVisibleDatasetWeightTotal();this.offsetX=p*v,this.offsetY=g*v,s.total=this.calculateTotal(),this.outerRadius=v-j*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-j*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/Xn)}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,m=h?0:this.innerRadius,p=h?0:this.outerRadius,{sharedOptions:g,includeOptions:b}=this._getSharedOptions(n,s);let x=this._getRotation(),y;for(y=0;y<n;++y)x+=this._circumference(y,o);for(y=n;y<n+r;++y){const v=this._circumference(y,o),w=t[y],j={x:d+this.offsetX,y:f+this.offsetY,startAngle:x,endAngle:x+v,circumference:v,outerRadius:p,innerRadius:m};b&&(j.options=g||this.resolveDataElementOptions(y,w.active?"active":s)),x+=v,this.updateElement(w,y,j,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)?Xn*(Math.abs(t)/n):0}getLabelAndValue(t){const n=this._cachedMeta,r=this.chart,s=r.data.labels||[],o=Bx(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,l;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)l=a.resolveDataElementOptions(s),l.borderAlign!=="inner"&&(n=Math.max(n,l.borderWidth||0,l.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(mt(this.chart.data.datasets[t].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}Ue(dd,"id","doughnut"),Ue(dd,"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"}),Ue(dd,"descriptors",{_scriptable:t=>t!=="spacing",_indexable:t=>t!=="spacing"&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")}),Ue(dd,"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((l,u)=>{const f=t.getDatasetMeta(0).controller.getStyle(u);return{text:l,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 jv extends Co{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:l}=DV(n,s,i);this._drawStart=a,this._drawCount=l,IV(n)&&(a=0,l=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,l,t)}updateElements(t,n,r,s){const o=s==="reset",{iScale:i,vScale:a,_stacked:l,_dataset:u}=this._cachedMeta,{sharedOptions:d,includeOptions:f}=this._getSharedOptions(n,s),h=i.axis,m=a.axis,{spanGaps:p,segment:g}=this.options,b=Qd(p)?p:Number.POSITIVE_INFINITY,x=this.chart._animationsDisabled||o||s==="none",y=n+r,v=t.length;let w=n>0&&this.getParsed(n-1);for(let j=0;j<v;++j){const S=t[j],N=x?S:{};if(j<n||j>=y){N.skip=!0;continue}const E=this.getParsed(j),_=_t(E[m]),k=N[h]=i.getPixelForValue(E[h],j),M=N[m]=o||_?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,E,l):E[m],j);N.skip=isNaN(k)||isNaN(M)||_,N.stop=j>0&&Math.abs(E[h]-w[h])>b,g&&(N.parsed=E,N.raw=u.data[j]),f&&(N.options=d||this.resolveDataElementOptions(j,S.active?"active":s)),x||this.updateElement(S,j,N,s),w=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()}}Ue(jv,"id","line"),Ue(jv,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),Ue(jv,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});class Pg extends Co{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=Bx(n._parsed[t].r,r.options.locale);return{label:s[t]||"",value:o}}parseObjectData(t,n,r,s){return LV.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,l=i.options.animation,u=this._cachedMeta.rScale,d=u.xCenter,f=u.yCenter,h=u.getIndexAngle(0)-.5*hn;let m=h,p;const g=360/this.countVisibleElements();for(p=0;p<n;++p)m+=this._computeAngle(p,s,g);for(p=n;p<n+r;p++){const b=t[p];let x=m,y=m+this._computeAngle(p,s,g),v=i.getDataVisibility(p)?u.getDistanceFromCenterForValue(this.getParsed(p).r):0;m=y,o&&(l.animateScale&&(v=0),l.animateRotate&&(x=y=h));const w={x:d,y:f,innerRadius:0,outerRadius:v,startAngle:x,endAngle:y,options:this.resolveDataElementOptions(p,b.active?"active":s)};this.updateElement(b,p,w,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)?Bi(this.resolveDataElementOptions(t,n).angle||r):0}}Ue(Pg,"id","polarArea"),Ue(Pg,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),Ue(Pg,"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 l=t.getDatasetMeta(0).controller.getStyle(i);return{text:o,fillStyle:l.backgroundColor,strokeStyle:l.borderColor,fontColor:s,lineWidth:l.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 sE extends dd{}Ue(sE,"id","pie"),Ue(sE,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});class Nv extends Co{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 LV.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 l=t[a],u=this.resolveDataElementOptions(a,l.active?"active":s),d=o.getPointPositionForValue(a,this.getParsed(a).r),f=i?o.xCenter:d.x,h=i?o.yCenter:d.y,m={x:f,y:h,angle:d.angle,skip:isNaN(f)||isNaN(h),options:u};this.updateElement(l,a,m,s)}}}Ue(Nv,"id","radar"),Ue(Nv,"defaults",{datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}}),Ue(Nv,"overrides",{aspectRatio:1,scales:{r:{type:"radialLinear"}}});class kv extends Co{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),l=o.getLabelForValue(i.y);return{label:r[t]||"",value:"("+a+", "+l+")"}}update(t){const n=this._cachedMeta,{data:r=[]}=n,s=this.chart._animationsDisabled;let{start:o,count:i}=DV(n,r,s);if(this._drawStart=o,this._drawCount=i,IV(n)&&(o=0,i=r.length),this.options.showLine){this.datasetElementType||this.addElements();const{dataset:a,_dataset:l}=n;a._chart=this.chart,a._datasetIndex=this.index,a._decimated=!!l._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:l,_dataset:u}=this._cachedMeta,d=this.resolveDataElementOptions(n,s),f=this.getSharedOptions(d),h=this.includeOptions(s,f),m=i.axis,p=a.axis,{spanGaps:g,segment:b}=this.options,x=Qd(g)?g:Number.POSITIVE_INFINITY,y=this.chart._animationsDisabled||o||s==="none";let v=n>0&&this.getParsed(n-1);for(let w=n;w<n+r;++w){const j=t[w],S=this.getParsed(w),N=y?j:{},E=_t(S[p]),_=N[m]=i.getPixelForValue(S[m],w),k=N[p]=o||E?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,S,l):S[p],w);N.skip=isNaN(_)||isNaN(k)||E,N.stop=w>0&&Math.abs(S[m]-v[m])>x,b&&(N.parsed=S,N.raw=u.data[w]),h&&(N.options=f||this.resolveDataElementOptions(w,j.active?"active":s)),y||this.updateElement(j,w,N,s),v=S}this.updateSharedOptions(f,s,d)}getMaxOverflow(){const t=this._cachedMeta,n=t.data||[];if(!this.options.showLine){let a=0;for(let l=n.length-1;l>=0;--l)a=Math.max(a,n[l].size(this.resolveDataElementOptions(l))/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}}Ue(kv,"id","scatter"),Ue(kv,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),Ue(kv,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});var Zpe=Object.freeze({__proto__:null,BarController:Id,BubbleController:Sv,DoughnutController:dd,LineController:jv,PieController:sE,PolarAreaController:Pg,RadarController:Nv,ScatterController:kv});function Vu(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class oD{constructor(t){Ue(this,"options");this.options=t||{}}static override(t){Object.assign(oD.prototype,t)}init(){}formats(){return Vu()}parse(){return Vu()}format(){return Vu()}add(){return Vu()}diff(){return Vu()}startOf(){return Vu()}endOf(){return Vu()}}var Xpe={_date:oD};function Qpe(e,t,n,r){const{controller:s,data:o,_sorted:i}=e,a=s._cachedMeta.iScale,l=e.dataset&&e.dataset.options?e.dataset.options.spanGaps:null;if(a&&t===a.axis&&t!=="r"&&i&&o.length){const u=a._reversePixels?vme:Tl;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),m=u(o,t,n+f);return{lo:h.lo,hi:m.hi}}}}else{const d=u(o,t,n);if(l){const{vScale:f}=s._cachedMeta,{_parsed:h}=e,m=h.slice(0,d.lo+1).reverse().findIndex(g=>!_t(g[f.axis]));d.lo-=Math.max(0,m);const p=h.slice(d.hi).findIndex(g=>!_t(g[f.axis]));d.hi+=Math.max(0,p)}return d}}return{lo:0,hi:o.length-1}}function vC(e,t,n,r,s){const o=e.getSortedVisibleDatasetMetas(),i=n[t];for(let a=0,l=o.length;a<l;++a){const{index:u,data:d}=o[a],{lo:f,hi:h}=Qpe(o[a],t,i,s);for(let m=f;m<=h;++m){const p=d[m];p.skip||r(p,u,m)}}}function Jpe(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 Vj(e,t,n,r,s){const o=[];return!s&&!e.isPointInArea(t)||vC(e,n,t,function(a,l,u){!s&&!Ml(a,e.chartArea,0)||a.inRange(t.x,t.y,r)&&o.push({element:a,datasetIndex:l,index:u})},!0),o}function ege(e,t,n,r){let s=[];function o(i,a,l){const{startAngle:u,endAngle:d}=i.getProps(["startAngle","endAngle"],r),{angle:f}=kV(i,{x:t.x,y:t.y});wb(f,u,d)&&s.push({element:i,datasetIndex:a,index:l})}return vC(e,n,t,o),s}function tge(e,t,n,r,s,o){let i=[];const a=Jpe(n);let l=Number.POSITIVE_INFINITY;function u(d,f,h){const m=d.inRange(t.x,t.y,s);if(r&&!m)return;const p=d.getCenterPoint(s);if(!(!!o||e.isPointInArea(p))&&!m)return;const b=a(t,p);b<l?(i=[{element:d,datasetIndex:f,index:h}],l=b):b===l&&i.push({element:d,datasetIndex:f,index:h})}return vC(e,n,t,u),i}function Hj(e,t,n,r,s,o){return!o&&!e.isPointInArea(t)?[]:n==="r"&&!r?ege(e,t,n,s):tge(e,t,n,r,s,o)}function KO(e,t,n,r,s){const o=[],i=n==="x"?"inXRange":"inYRange";let a=!1;return vC(e,n,t,(l,u,d)=>{l[i]&&l[i](t[n],s)&&(o.push({element:l,datasetIndex:u,index:d}),a=a||l.inRange(t.x,t.y,s))}),r&&!a?[]:o}var nge={modes:{index(e,t,n,r){const s=Zu(t,e),o=n.axis||"x",i=n.includeInvisible||!1,a=n.intersect?Vj(e,s,o,r,i):Hj(e,s,o,!1,r,i),l=[];return a.length?(e.getSortedVisibleDatasetMetas().forEach(u=>{const d=a[0].index,f=u.data[d];f&&!f.skip&&l.push({element:f,datasetIndex:u.index,index:d})}),l):[]},dataset(e,t,n,r){const s=Zu(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;let a=n.intersect?Vj(e,s,o,r,i):Hj(e,s,o,!1,r,i);if(a.length>0){const l=a[0].datasetIndex,u=e.getDatasetMeta(l).data;a=[];for(let d=0;d<u.length;++d)a.push({element:u[d],datasetIndex:l,index:d})}return a},point(e,t,n,r){const s=Zu(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;return Vj(e,s,o,r,i)},nearest(e,t,n,r){const s=Zu(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;return Hj(e,s,o,n.intersect,r,i)},x(e,t,n,r){const s=Zu(t,e);return KO(e,s,"x",n.intersect,r)},y(e,t,n,r){const s=Zu(t,e);return KO(e,s,"y",n.intersect,r)}}};const ZV=["left","top","right","bottom"];function zp(e,t){return e.filter(n=>n.pos===t)}function ZO(e,t){return e.filter(n=>ZV.indexOf(n.pos)===-1&&n.box.axis===t)}function Bp(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 rge(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 sge(e){const t={};for(const n of e){const{stack:r,pos:s,stackWeight:o}=n;if(!r||!ZV.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 oge(e,t){const n=sge(e),{vBoxMaxWidth:r,hBoxMaxHeight:s}=t;let o,i,a;for(o=0,i=e.length;o<i;++o){a=e[o];const{fullSize:l}=a.box,u=n[a.stack],d=u&&a.stackWeight/u.weight;a.horizontal?(a.width=d?d*r:l&&t.availableWidth,a.height=s):(a.width=r,a.height=d?d*s:l&&t.availableHeight)}return n}function ige(e){const t=rge(e),n=Bp(t.filter(u=>u.box.fullSize),!0),r=Bp(zp(t,"left"),!0),s=Bp(zp(t,"right")),o=Bp(zp(t,"top"),!0),i=Bp(zp(t,"bottom")),a=ZO(t,"x"),l=ZO(t,"y");return{fullSize:n,leftAndTop:r.concat(o),rightAndBottom:s.concat(l).concat(i).concat(a),chartArea:zp(t,"chartArea"),vertical:r.concat(s).concat(l),horizontal:o.concat(i).concat(a)}}function XO(e,t,n,r){return Math.max(e[n],t[n])+Math.max(e[r],t[r])}function XV(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 age(e,t,n,r){const{pos:s,box:o}=n,i=e.maxPadding;if(!Pt(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&&XV(i,o.getPadding());const a=Math.max(0,t.outerWidth-XO(i,e,"left","right")),l=Math.max(0,t.outerHeight-XO(i,e,"top","bottom")),u=a!==e.w,d=l!==e.h;return e.w=a,e.h=l,n.horizontal?{same:u,other:d}:{same:d,other:u}}function lge(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 cge(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 ag(e,t,n,r){const s=[];let o,i,a,l,u,d;for(o=0,i=e.length,u=0;o<i;++o){a=e[o],l=a.box,l.update(a.width||t.w,a.height||t.h,cge(a.horizontal,t));const{same:f,other:h}=age(t,n,a,r);u|=f&&s.length,d=d||h,l.fullSize||s.push(a)}return u&&ag(s,t,n,r)||d}function a0(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 QO(e,t,n,r){const s=n.padding;let{x:o,y:i}=t;for(const a of e){const l=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||l.height;lm(u.start)&&(i=u.start),l.fullSize?a0(l,s.left,i,n.outerWidth-s.right-s.left,h):a0(l,t.left+u.placed,i,f,h),u.start=i,u.placed+=f,i=l.bottom}else{const f=t.h*d,h=u.size||l.width;lm(u.start)&&(o=u.start),l.fullSize?a0(l,o,s.top,h,n.outerHeight-s.bottom-s.top):a0(l,o,t.top+u.placed,h,f),u.start=o,u.placed+=f,o=l.right}}t.x=o,t.y=i}var Ts={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=bs(e.options.layout.padding),o=Math.max(t-s.width,0),i=Math.max(n-s.height,0),a=ige(e.boxes),l=a.vertical,u=a.horizontal;Nn(e.boxes,g=>{typeof g.beforeLayout=="function"&&g.beforeLayout()});const d=l.reduce((g,b)=>b.box.options&&b.box.options.display===!1?g:g+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);XV(h,bs(r));const m=Object.assign({maxPadding:h,w:o,h:i,x:s.left,y:s.top},s),p=oge(l.concat(u),f);ag(a.fullSize,m,f,p),ag(l,m,f,p),ag(u,m,f,p)&&ag(l,m,f,p),lge(m),QO(a.leftAndTop,m,f,p),m.x+=m.w,m.y+=m.h,QO(a.rightAndBottom,m,f,p),e.chartArea={left:m.left,top:m.top,right:m.left+m.w,bottom:m.top+m.h,height:m.h,width:m.w},Nn(a.chartArea,g=>{const b=g.box;Object.assign(b,e.chartArea),b.update(m.w,m.h,{left:0,top:0,right:0,bottom:0})})}};class QV{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 uge extends QV{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const Ev="$chartjs",dge={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},JO=e=>e===null||e==="";function fge(e,t){const n=e.style,r=e.getAttribute("height"),s=e.getAttribute("width");if(e[Ev]={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",JO(s)){const o=OO(e,"width");o!==void 0&&(e.width=o)}if(JO(r))if(e.style.height==="")e.height=e.width/(t||2);else{const o=OO(e,"height");o!==void 0&&(e.height=o)}return e}const JV=hpe?{passive:!0}:!1;function hge(e,t,n){e&&e.addEventListener(t,n,JV)}function mge(e,t,n){e&&e.canvas&&e.canvas.removeEventListener(t,n,JV)}function pge(e,t){const n=dge[e.type]||e.type,{x:r,y:s}=Zu(e,t);return{type:n,chart:t,native:e,x:r!==void 0?r:null,y:s!==void 0?s:null}}function bw(e,t){for(const n of e)if(n===t||n.contains(t))return!0}function gge(e,t,n){const r=e.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||bw(a.addedNodes,r),i=i&&!bw(a.removedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}function bge(e,t,n){const r=e.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||bw(a.removedNodes,r),i=i&&!bw(a.addedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}const Cb=new Map;let eF=0;function eH(){const e=window.devicePixelRatio;e!==eF&&(eF=e,Cb.forEach((t,n)=>{n.currentDevicePixelRatio!==e&&t()}))}function xge(e,t){Cb.size||window.addEventListener("resize",eH),Cb.set(e,t)}function yge(e){Cb.delete(e),Cb.size||window.removeEventListener("resize",eH)}function vge(e,t,n){const r=e.canvas,s=r&&sD(r);if(!s)return;const o=MV((a,l)=>{const u=s.clientWidth;n(a,l),u<s.clientWidth&&n()},window),i=new ResizeObserver(a=>{const l=a[0],u=l.contentRect.width,d=l.contentRect.height;u===0&&d===0||o(u,d)});return i.observe(s),xge(e,o),i}function Uj(e,t,n){n&&n.disconnect(),t==="resize"&&yge(e)}function wge(e,t,n){const r=e.canvas,s=MV(o=>{e.ctx!==null&&n(pge(o,e))},e);return hge(r,t,s),s}class Cge extends QV{acquireContext(t,n){const r=t&&t.getContext&&t.getContext("2d");return r&&r.canvas===t?(fge(t,n),r):null}releaseContext(t){const n=t.canvas;if(!n[Ev])return!1;const r=n[Ev].initial;["height","width"].forEach(o=>{const i=r[o];_t(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[Ev],!0}addEventListener(t,n,r){this.removeEventListener(t,n);const s=t.$proxies||(t.$proxies={}),i={attach:gge,detach:bge,resize:vge}[n]||wge;s[n]=i(t,n,r)}removeEventListener(t,n){const r=t.$proxies||(t.$proxies={}),s=r[n];if(!s)return;({attach:Uj,detach:Uj,resize:Uj}[n]||mge)(t,n,s),r[n]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,n,r,s){return fpe(t,n,r,s)}isAttached(t){const n=t&&sD(t);return!!(n&&n.isConnected)}}function Sge(e){return!rD()||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas?uge:Cge}var gv;let wi=(gv=class{constructor(){Ue(this,"x");Ue(this,"y");Ue(this,"active",!1);Ue(this,"options");Ue(this,"$animations")}tooltipPosition(t){const{x:n,y:r}=this.getProps(["x","y"],t);return{x:n,y:r}}hasValue(){return Qd(this.x)&&Qd(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}},Ue(gv,"defaults",{}),Ue(gv,"defaultRoutes"),gv);function jge(e,t){const n=e.options.ticks,r=Nge(e),s=Math.min(n.maxTicksLimit||r,r),o=n.major.enabled?Ege(t):[],i=o.length,a=o[0],l=o[i-1],u=[];if(i>s)return _ge(t,u,o,i/s),u;const d=kge(o,t,s);if(i>0){let f,h;const m=i>1?Math.round((l-a)/(i-1)):null;for(l0(t,u,d,_t(m)?0:a-m,a),f=0,h=i-1;f<h;f++)l0(t,u,d,o[f],o[f+1]);return l0(t,u,d,l,_t(m)?t.length:l+m),u}return l0(t,u,d),u}function Nge(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 kge(e,t,n){const r=Tge(e),s=t.length/n;if(!r)return Math.max(s,1);const o=pme(r);for(let i=0,a=o.length-1;i<a;i++){const l=o[i];if(l>s)return l}return Math.max(s,1)}function Ege(e){const t=[];let n,r;for(n=0,r=e.length;n<r;n++)e[n].major&&t.push(n);return t}function _ge(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 l0(e,t,n,r,s){const o=mt(r,0),i=Math.min(mt(s,e.length),e.length);let a=0,l,u,d;for(n=Math.ceil(n),s&&(l=s-r,n=l/Math.floor(l/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 Tge(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 Mge=e=>e==="left"?"right":e==="right"?"left":e,tF=(e,t,n)=>t==="top"||t==="left"?e[t]+n:e[t]-n,nF=(e,t)=>Math.min(t||e,e);function rF(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 Dge(e,t,n){const r=e.ticks.length,s=Math.min(t,r-1),o=e._startPixel,i=e._endPixel,a=1e-6;let l=e.getPixelForTick(s),u;if(!(n&&(r===1?u=Math.max(l-o,i-l):t===0?u=(e.getPixelForTick(1)-l)/2:u=(l-e.getPixelForTick(s-1))/2,l+=s<t?u:-u,l<o-a||l>i+a)))return l}function Ige(e,t){Nn(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 Vp(e){return e.drawTicks?e.tickLength:0}function sF(e,t){if(!e.display)return 0;const n=Un(e.font,t),r=bs(e.padding);return(Pn(e.text)?e.text.length:1)*n.lineHeight+r.height}function Rge(e,t){return ju(e,{scale:t,type:"scale"})}function Age(e,t,n){return ju(e,{tick:n,index:t,type:"tick"})}function Pge(e,t,n){let r=ZM(e);return(n&&t!=="right"||!n&&t==="right")&&(r=Mge(r)),r}function Oge(e,t,n,r){const{top:s,left:o,bottom:i,right:a,chart:l}=e,{chartArea:u,scales:d}=l;let f=0,h,m,p;const g=i-s,b=a-o;if(e.isHorizontal()){if(m=Ss(r,o,a),Pt(n)){const x=Object.keys(n)[0],y=n[x];p=d[x].getPixelForValue(y)+g-t}else n==="center"?p=(u.bottom+u.top)/2+g-t:p=tF(e,n,t);h=a-o}else{if(Pt(n)){const x=Object.keys(n)[0],y=n[x];m=d[x].getPixelForValue(y)-b+t}else n==="center"?m=(u.left+u.right)/2-b+t:m=tF(e,n,t);p=Ss(r,i,s),f=n==="left"?-_r:_r}return{titleX:m,titleY:p,maxWidth:h,rotation:f}}class Nu extends wi{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=Io(t,Number.POSITIVE_INFINITY),n=Io(n,Number.NEGATIVE_INFINITY),r=Io(r,Number.POSITIVE_INFINITY),s=Io(s,Number.NEGATIVE_INFINITY),{min:Io(t,r),max:Io(n,s),minDefined:br(t),maxDefined:br(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 l=0,u=a.length;l<u;++l)i=a[l].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:Io(n,Io(r,n)),max:Io(r,Io(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(){In(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=Ume(this,o,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const l=a<this.ticks.length;this._convertTicksToLabels(l?rF(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),i.display&&(i.autoSkip||i.source==="auto")&&(this.ticks=jge(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),l&&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(){In(this.options.afterUpdate,[this])}beforeSetDimensions(){In(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(){In(this.options.afterSetDimensions,[this])}_callHooks(t){this.chart.notifyPlugins(t,this.getContext()),In(this.options[t],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){In(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=In(n.callback,[o.value,r,t],this)}afterTickToLabelConversion(){In(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){In(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const t=this.options,n=t.ticks,r=nF(this.ticks.length,t.ticks.maxTicksLimit),s=n.minRotation||0,o=n.maxRotation;let i=s,a,l,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,m=rs(this.chart.width-f,0,this.maxWidth);a=t.offset?this.maxWidth/r:m/(r-1),f+6>a&&(a=m/(r-(t.offset?.5:1)),l=this.maxHeight-Vp(t.grid)-n.padding-sF(t.title,this.chart.options.font),u=Math.sqrt(f*f+h*h),i=GM(Math.min(Math.asin(rs((d.highest.height+6)/a,-1,1)),Math.asin(rs(l/u,-1,1))-Math.asin(rs(h/u,-1,1)))),i=Math.max(s,Math.min(o,i))),this.labelRotation=i}afterCalculateLabelRotation(){In(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){In(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 l=sF(s,n.options.font);if(a?(t.width=this.maxWidth,t.height=Vp(o)+l):(t.height=this.maxHeight,t.width=Vp(o)+l),r.display&&this.ticks.length){const{first:u,last:d,widest:f,highest:h}=this._getLabelSizes(),m=r.padding*2,p=Bi(this.labelRotation),g=Math.cos(p),b=Math.sin(p);if(a){const x=r.mirror?0:b*f.width+g*h.height;t.height=Math.min(this.maxHeight,t.height+x+m)}else{const x=r.mirror?0:g*f.width+b*h.height;t.width=Math.min(this.maxWidth,t.width+x+m)}this._calculatePadding(u,d,b,g)}}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,l=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,m=0;l?u?(h=s*t.width,m=r*n.height):(h=r*t.height,m=s*n.width):o==="start"?m=n.width:o==="end"?h=t.width:o!=="inner"&&(h=t.width/2,m=n.width/2),this.paddingLeft=Math.max((h-d+i)*this.width/(this.width-d),0),this.paddingRight=Math.max((m-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(){In(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++)_t(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=rF(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=[],l=Math.floor(n/nF(n,r));let u=0,d=0,f,h,m,p,g,b,x,y,v,w,j;for(f=0;f<n;f+=l){if(p=t[f].label,g=this._resolveTickFontOptions(f),s.font=b=g.string,x=o[b]=o[b]||{data:{},gc:[]},y=g.lineHeight,v=w=0,!_t(p)&&!Pn(p))v=mw(s,x.data,x.gc,v,p),w=y;else if(Pn(p))for(h=0,m=p.length;h<m;++h)j=p[h],!_t(j)&&!Pn(j)&&(v=mw(s,x.data,x.gc,v,j),w+=y);i.push(v),a.push(w),u=Math.max(v,u),d=Math.max(w,d)}Ige(o,n);const S=i.indexOf(u),N=a.indexOf(d),E=_=>({width:i[_]||0,height:a[_]||0});return{first:E(0),last:E(n-1),widest:E(S),highest:E(N),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 yme(this._alignToPixels?Bu(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=Age(this.getContext(),t,r))}return this.$context||(this.$context=Rge(this.chart.getContext(),this))}_tickSize(){const t=this.options.ticks,n=Bi(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,l=o?o.highest.height+i:0;return this.isHorizontal()?l*r>a*s?a/r:l/s:l*s<a*r?l/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,l=o.offset,u=this.isHorizontal(),f=this.ticks.length+(l?1:0),h=Vp(o),m=[],p=a.setContext(this.getContext()),g=p.display?p.width:0,b=g/2,x=function($){return Bu(r,$,g)};let y,v,w,j,S,N,E,_,k,M,T,P;if(i==="top")y=x(this.bottom),N=this.bottom-h,_=y-b,M=x(t.top)+b,P=t.bottom;else if(i==="bottom")y=x(this.top),M=t.top,P=x(t.bottom)-b,N=y+b,_=this.top+h;else if(i==="left")y=x(this.right),S=this.right-h,E=y-b,k=x(t.left)+b,T=t.right;else if(i==="right")y=x(this.left),k=t.left,T=x(t.right)-b,S=y+b,E=this.left+h;else if(n==="x"){if(i==="center")y=x((t.top+t.bottom)/2+.5);else if(Pt(i)){const $=Object.keys(i)[0],V=i[$];y=x(this.chart.scales[$].getPixelForValue(V))}M=t.top,P=t.bottom,N=y+b,_=N+h}else if(n==="y"){if(i==="center")y=x((t.left+t.right)/2);else if(Pt(i)){const $=Object.keys(i)[0],V=i[$];y=x(this.chart.scales[$].getPixelForValue(V))}S=y-b,E=S-h,k=t.left,T=t.right}const O=mt(s.ticks.maxTicksLimit,f),I=Math.max(1,Math.ceil(f/O));for(v=0;v<f;v+=I){const $=this.getContext(v),V=o.setContext($),W=a.setContext($),L=V.lineWidth,R=V.color,z=W.dash||[],F=W.dashOffset,A=V.tickWidth,H=V.tickColor,B=V.tickBorderDash||[],Y=V.tickBorderDashOffset;w=Dge(this,v,l),w!==void 0&&(j=Bu(r,w,L),u?S=E=k=T=j:N=_=M=P=j,m.push({tx1:S,ty1:N,tx2:E,ty2:_,x1:k,y1:M,x2:T,y2:P,width:L,color:R,borderDash:z,borderDashOffset:F,tickWidth:A,tickColor:H,tickBorderDash:B,tickBorderDashOffset:Y}))}return this._ticksLength=f,this._borderValue=y,m}_computeLabelItems(t){const n=this.axis,r=this.options,{position:s,ticks:o}=r,i=this.isHorizontal(),a=this.ticks,{align:l,crossAlign:u,padding:d,mirror:f}=o,h=Vp(r.grid),m=h+d,p=f?-d:m,g=-Bi(this.labelRotation),b=[];let x,y,v,w,j,S,N,E,_,k,M,T,P="middle";if(s==="top")S=this.bottom-p,N=this._getXAxisLabelAlignment();else if(s==="bottom")S=this.top+p,N=this._getXAxisLabelAlignment();else if(s==="left"){const I=this._getYAxisLabelAlignment(h);N=I.textAlign,j=I.x}else if(s==="right"){const I=this._getYAxisLabelAlignment(h);N=I.textAlign,j=I.x}else if(n==="x"){if(s==="center")S=(t.top+t.bottom)/2+m;else if(Pt(s)){const I=Object.keys(s)[0],$=s[I];S=this.chart.scales[I].getPixelForValue($)+m}N=this._getXAxisLabelAlignment()}else if(n==="y"){if(s==="center")j=(t.left+t.right)/2-m;else if(Pt(s)){const I=Object.keys(s)[0],$=s[I];j=this.chart.scales[I].getPixelForValue($)}N=this._getYAxisLabelAlignment(h).textAlign}n==="y"&&(l==="start"?P="top":l==="end"&&(P="bottom"));const O=this._getLabelSizes();for(x=0,y=a.length;x<y;++x){v=a[x],w=v.label;const I=o.setContext(this.getContext(x));E=this.getPixelForTick(x)+o.labelOffset,_=this._resolveTickFontOptions(x),k=_.lineHeight,M=Pn(w)?w.length:1;const $=M/2,V=I.color,W=I.textStrokeColor,L=I.textStrokeWidth;let R=N;i?(j=E,N==="inner"&&(x===y-1?R=this.options.reverse?"left":"right":x===0?R=this.options.reverse?"right":"left":R="center"),s==="top"?u==="near"||g!==0?T=-M*k+k/2:u==="center"?T=-O.highest.height/2-$*k+k:T=-O.highest.height+k/2:u==="near"||g!==0?T=k/2:u==="center"?T=O.highest.height/2-$*k:T=O.highest.height-M*k,f&&(T*=-1),g!==0&&!I.showLabelBackdrop&&(j+=k/2*Math.sin(g))):(S=E,T=(1-M)*k/2);let z;if(I.showLabelBackdrop){const F=bs(I.backdropPadding),A=O.heights[x],H=O.widths[x];let B=T-F.top,Y=0-F.left;switch(P){case"middle":B-=A/2;break;case"bottom":B-=A;break}switch(N){case"center":Y-=H/2;break;case"right":Y-=H;break;case"inner":x===y-1?Y-=H:x>0&&(Y-=H/2);break}z={left:Y,top:B,width:H+F.width,height:A+F.height,color:I.backdropColor}}b.push({label:w,font:_,textOffset:T,options:{rotation:g,color:V,strokeColor:W,strokeWidth:L,textAlign:R,textBaseline:P,translation:[j,S],backdrop:z}})}return b}_getXAxisLabelAlignment(){const{position:t,ticks:n}=this.options;if(-Bi(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,l=i.widest.width;let u,d;return n==="left"?s?(d=this.right+o,r==="near"?u="left":r==="center"?(u="center",d+=l/2):(u="right",d+=l)):(d=this.right-a,r==="near"?u="right":r==="center"?(u="center",d-=l/2):(u="left",d=this.left)):n==="right"?s?(d=this.left+o,r==="near"?u="right":r==="center"?(u="center",d-=l/2):(u="left",d-=l)):(d=this.left+a,r==="near"?u="left":r==="center"?(u="center",d+=l/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=(l,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(l.x,l.y),r.lineTo(u.x,u.y),r.stroke(),r.restore())};if(n.display)for(o=0,i=s.length;o<i;++o){const l=s[o];n.drawOnChartArea&&a({x:l.x1,y:l.y1},{x:l.x2,y:l.y2},l),n.drawTicks&&a({x:l.tx1,y:l.ty1},{x:l.tx2,y:l.ty2},{color:l.tickColor,width:l.tickWidth,borderDash:l.tickBorderDash,borderDashOffset:l.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,l=this._borderValue;let u,d,f,h;this.isHorizontal()?(u=Bu(t,this.left,i)-i/2,d=Bu(t,this.right,a)+a/2,f=h=l):(f=Bu(t,this.top,i)-i/2,h=Bu(t,this.bottom,a)+a/2,u=d=l),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&&Kc(r,s);const o=this.getLabelItems(t);for(const i of o){const a=i.options,l=i.font,u=i.label,d=i.textOffset;ef(r,u,0,d,l,a)}s&&Zc(r)}drawTitle(){const{ctx:t,options:{position:n,title:r,reverse:s}}=this;if(!r.display)return;const o=Un(r.font),i=bs(r.padding),a=r.align;let l=o.lineHeight/2;n==="bottom"||n==="center"||Pt(n)?(l+=i.bottom,Pn(r.text)&&(l+=o.lineHeight*(r.text.length-1))):l+=i.top;const{titleX:u,titleY:d,maxWidth:f,rotation:h}=Oge(this,l,n,a);ef(t,r.text,0,0,o,{color:r.color,maxWidth:f,rotation:h,textAlign:Pge(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=mt(t.grid&&t.grid.z,-1),s=mt(t.border&&t.border.z,0);return!this._isVisible()||this.draw!==Nu.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 Un(n.font)}_maxDigits(){const t=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/t}}class c0{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;Lge(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,Fge(t,i,r),this.override&&Qn.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 Qn[s]&&(delete Qn[s][r],this.override&&delete Jd[r])}}function Fge(e,t,n){const r=Or(Object.create(null),[n?Qn.get(n):{},Qn.get(t),e.defaults]);Qn.set(t,r),e.defaultRoutes&&$ge(t,e.defaultRoutes),e.descriptors&&Qn.describe(t,e.descriptors)}function $ge(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(),l=i.join(".");Qn.route(o,s,l,a)})}function Lge(e){return"id"in e&&"defaults"in e}class zge{constructor(){this.controllers=new c0(Co,"datasets",!0),this.elements=new c0(wi,"elements"),this.plugins=new c0(Object,"plugins"),this.scales=new c0(Nu,"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):Nn(s,i=>{const a=r||this._getRegistryForType(i);this._exec(t,a,i)})})}_exec(t,n,r){const s=YM(t);In(r["before"+s],[],r),n[t](r),In(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 hr=new zge;class Bge{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],l=[n,s,o.options];if(In(a,l,i)===!1&&s.cancelable)return!1}return!0}invalidate(){_t(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=mt(r.options&&r.options.plugins,{}),o=Vge(r);return s===!1&&!n?[]:Uge(t,o,s,n)}_notifyStateChanges(t){const n=this._oldCache||[],r=this._cache,s=(o,i)=>o.filter(a=>!i.some(l=>a.plugin.id===l.plugin.id));this._notify(s(n,r),t,"stop"),this._notify(s(r,n),t,"start")}}function Vge(e){const t={},n=[],r=Object.keys(hr.plugins.items);for(let o=0;o<r.length;o++)n.push(hr.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 Hge(e,t){return!t&&e===!1?null:e===!0?{}:e}function Uge(e,{plugins:t,localIds:n},r,s){const o=[],i=e.getContext();for(const a of t){const l=a.id,u=Hge(r[l],s);u!==null&&o.push({plugin:a,options:Wge(e.config,{plugin:a,local:n[l]},u,i)})}return o}function Wge(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 oE(e,t){const n=Qn.datasets[e]||{};return((t.datasets||{})[e]||{}).indexAxis||t.indexAxis||n.indexAxis||"x"}function qge(e,t){let n=e;return e==="_index_"?n=t:e==="_value_"&&(n=t==="x"?"y":"x"),n}function Yge(e,t){return e===t?"_index_":"_value_"}function oF(e){if(e==="x"||e==="y"||e==="r")return e}function Gge(e){if(e==="top"||e==="bottom")return"x";if(e==="left"||e==="right")return"y"}function iE(e,...t){if(oF(e))return e;for(const n of t){const r=n.axis||Gge(n.position)||e.length>1&&oF(e[0].toLowerCase());if(r)return r}throw new Error(`Cannot determine type of '${e}' axis. Please provide 'axis' or 'position' option.`)}function iF(e,t,n){if(n[t+"AxisID"]===e)return{axis:t}}function Kge(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 iF(e,"x",n[0])||iF(e,"y",n[0])}return{}}function Zge(e,t){const n=Jd[e.type]||{scales:{}},r=t.scales||{},s=oE(e.type,t),o=Object.create(null);return Object.keys(r).forEach(i=>{const a=r[i];if(!Pt(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 l=iE(i,a,Kge(i,e),Qn.scales[a.type]),u=Yge(l,s),d=n.scales||{};o[i]=Dg(Object.create(null),[{axis:l},a,d[l],d[u]])}),e.data.datasets.forEach(i=>{const a=i.type||e.type,l=i.indexAxis||oE(a,t),d=(Jd[a]||{}).scales||{};Object.keys(d).forEach(f=>{const h=qge(f,l),m=i[h+"AxisID"]||h;o[m]=o[m]||Object.create(null),Dg(o[m],[{axis:h},r[m],d[f]])})}),Object.keys(o).forEach(i=>{const a=o[i];Dg(a,[Qn.scales[a.type],Qn.scale])}),o}function tH(e){const t=e.options||(e.options={});t.plugins=mt(t.plugins,{}),t.scales=Zge(e,t)}function nH(e){return e=e||{},e.datasets=e.datasets||[],e.labels=e.labels||[],e}function Xge(e){return e=e||{},e.data=nH(e.data),tH(e),e}const aF=new Map,rH=new Set;function u0(e,t){let n=aF.get(e);return n||(n=t(),aF.set(e,n),rH.add(n)),n}const Hp=(e,t,n)=>{const r=ru(t,n);r!==void 0&&e.add(r)};class Qge{constructor(t){this._config=Xge(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=nH(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(),tH(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return u0(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,n){return u0(`${t}.transition.${n}`,()=>[[`datasets.${t}.transitions.${n}`,`transitions.${n}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,n){return u0(`${t}-${n}`,()=>[[`datasets.${t}.elements.${n}`,`datasets.${t}`,`elements.${n}`,""]])}pluginScopeKeys(t){const n=t.id,r=this.type;return u0(`${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 l=new Set;n.forEach(d=>{t&&(l.add(t),d.forEach(f=>Hp(l,t,f))),d.forEach(f=>Hp(l,s,f)),d.forEach(f=>Hp(l,Jd[o]||{},f)),d.forEach(f=>Hp(l,Qn,f)),d.forEach(f=>Hp(l,rE,f))});const u=Array.from(l);return u.length===0&&u.push(Object.create(null)),rH.has(n)&&i.set(n,u),u}chartOptionScopes(){const{options:t,type:n}=this;return[t,Jd[n]||{},Qn.datasets[n]||{},{type:n},Qn,rE]}resolveNamedOptions(t,n,r,s=[""]){const o={$shared:!0},{resolver:i,subPrefixes:a}=lF(this._resolverCache,t,s);let l=i;if(ebe(i,n)){o.$shared=!1,r=su(r)?r():r;const u=this.createResolver(t,r,a);l=cm(i,r,u)}for(const u of n)o[u]=l[u];return o}createResolver(t,n,r=[""],s){const{resolver:o}=lF(this._resolverCache,t,r);return Pt(n)?cm(o,n,void 0,s):o}}function lF(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:eD(t,n),subPrefixes:n.filter(a=>!a.toLowerCase().includes("hover"))},r.set(s,o)),o}const Jge=e=>Pt(e)&&Object.getOwnPropertyNames(e).some(t=>su(e[t]));function ebe(e,t){const{isScriptable:n,isIndexable:r}=PV(e);for(const s of t){const o=n(s),i=r(s),a=(i||o)&&e[s];if(o&&(su(a)||Jge(a))||i&&Pn(a))return!0}return!1}var tbe="4.5.1";const nbe=["top","bottom","left","right","chartArea"];function cF(e,t){return e==="top"||e==="bottom"||nbe.indexOf(e)===-1&&t==="x"}function uF(e,t){return function(n,r){return n[e]===r[e]?n[t]-r[t]:n[e]-r[e]}}function dF(e){const t=e.chart,n=t.options.animation;t.notifyPlugins("afterRender"),In(n&&n.onComplete,[e],t)}function rbe(e){const t=e.chart,n=t.options.animation;In(n&&n.onProgress,[e],t)}function sH(e){return rD()&&typeof e=="string"?e=document.getElementById(e):e&&e.length&&(e=e[0]),e&&e.canvas&&(e=e.canvas),e}const _v={},fF=e=>{const t=sH(e);return Object.values(_v).filter(n=>n.canvas===t).pop()};function sbe(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 obe(e,t,n,r){return!n||e.type==="mouseout"?null:r?t:e}class Xt{static register(...t){hr.add(...t),hF()}static unregister(...t){hr.remove(...t),hF()}constructor(t,n){const r=this.config=new Qge(n),s=sH(t),o=fF(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||Sge(s)),this.platform.updateConfig(r);const a=this.platform.acquireContext(s,i.aspectRatio),l=a&&a.canvas,u=l&&l.height,d=l&&l.width;if(this.id=ime(),this.ctx=a,this.canvas=l,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 Bge,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=Sme(f=>this.update(f),i.resizeDelay||0),this._dataChanges=[],_v[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}cl.listen(this,"complete",dF),cl.listen(this,"progress",rbe),this._initialize(),this.attached&&this.update()}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:n},width:r,height:s,_aspectRatio:o}=this;return _t(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 hr}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():PO(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return IO(this.canvas,this.ctx),this}stop(){return cl.stop(this),this}resize(t,n){cl.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(),l=this.width?"resize":"attach";this.width=i.width,this.height=i.height,this._aspectRatio=this.aspectRatio,PO(this,a,!0)&&(this.notifyPlugins("resize",{size:i}),In(r.onResize,[this,i],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){const n=this.options.scales||{};Nn(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],l=iE(i,a),u=l==="r",d=l==="x";return{options:a,dposition:u?"chartArea":d?"bottom":"left",dtype:u?"radialLinear":d?"category":"linear"}}))),Nn(o,i=>{const a=i.options,l=a.id,u=iE(l,a),d=mt(a.type,i.dtype);(a.position===void 0||cF(a.position,u)!==cF(i.dposition))&&(a.position=i.dposition),s[l]=!0;let f=null;if(l in r&&r[l].type===d)f=r[l];else{const h=hr.getScale(d);f=new h({id:l,type:d,ctx:this.ctx,chart:this}),r[f.id]=f}f.init(a,t)}),Nn(s,(i,a)=>{i||delete r[a]}),Nn(r,i=>{Ts.configure(this,i,i.options),Ts.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(uF("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||oE(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 l=hr.getController(a),{datasetElementType:u,dataElementType:d}=Qn.datasets[a];Object.assign(l,{dataElementType:hr.getElement(d),datasetElementType:u&&hr.getElement(u)}),i.controller=new l(this,r),t.push(i.controller)}}return this._updateMetasets(),t}_resetElements(){Nn(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||Nn(o,u=>{u.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(uF("z","_idx"));const{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){Nn(this.scales,t=>{Ts.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,n=new Set(Object.keys(this._listeners)),r=new Set(t.events);(!SO(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;sbe(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(!SO(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;Ts.update(this,this.width,this.height,t);const n=this.chartArea,r=n.width<=0||n.height<=0;this._layers=[],Nn(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,su(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&&(cl.has(this)?this.attached&&!cl.running(this)&&cl.start(this):(this.draw(),dF({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=qV(this,t);this.notifyPlugins("beforeDatasetDraw",r)!==!1&&(s&&Kc(n,s),t.controller.draw(),s&&Zc(n),r.cancelable=!1,this.notifyPlugins("afterDatasetDraw",r))}isPointInArea(t){return Ml(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,n,r,s){const o=nge.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=ju(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);lm(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(),cl.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(),IO(t,n),this.platform.releaseContext(n),this.canvas=null,this.ctx=null),delete _v[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)};Nn(this.options.events,o=>r(o,s))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,n=this.platform,r=(l,u)=>{n.addEventListener(this,l,u),t[l]=u},s=(l,u)=>{t[l]&&(n.removeEventListener(this,l,u),delete t[l])},o=(l,u)=>{this.canvas&&this.resize(l,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(){Nn(this._listeners,(t,n)=>{this.platform.removeEventListener(this,n,t)}),this._listeners={},Nn(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,l;for(n==="dataset"&&(o=this.getDatasetMeta(t[0].datasetIndex),o.controller["_"+s+"DatasetHoverStyle"]()),a=0,l=t.length;a<l;++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}});!dw(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=(l,u)=>l.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),l=fme(t),u=obe(t,this._lastEvent,r,l);r&&(this._lastEvent=null,In(o.onHover,[t,a,this],this),l&&In(o.onClick,[t,a,this],this));const d=!dw(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)}}Ue(Xt,"defaults",Qn),Ue(Xt,"instances",_v),Ue(Xt,"overrides",Jd),Ue(Xt,"registry",hr),Ue(Xt,"version",tbe),Ue(Xt,"getChart",fF);function hF(){return Nn(Xt.instances,e=>e._plugins.invalidate())}function ibe(e,t,n){const{startAngle:r,x:s,y:o,outerRadius:i,innerRadius:a,options:l}=t,{borderWidth:u,borderJoinStyle:d}=l,f=Math.min(u/i,ks(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,ks(r-n));e.arc(s,o,a+u/2,n-h/2,r+h/2,!0)}else{const h=Math.min(u/2,i*ks(r-n));if(d==="round")e.arc(s,o,h,n-hn/2,r+hn/2,!0);else if(d==="bevel"){const m=2*h*h,p=-m*Math.cos(n+hn/2)+s,g=-m*Math.sin(n+hn/2)+o,b=m*Math.cos(r+hn/2)+s,x=m*Math.sin(r+hn/2)+o;e.lineTo(p,g),e.lineTo(b,x)}}e.closePath(),e.moveTo(0,0),e.rect(0,0,e.canvas.width,e.canvas.height),e.clip("evenodd")}function abe(e,t,n){const{startAngle:r,pixelMargin:s,x:o,y:i,outerRadius:a,innerRadius:l}=t;let u=s/a;e.beginPath(),e.arc(o,i,a,r-u,n+u),l>s?(u=s/l,e.arc(o,i,l,n+u,r-u,!0)):e.arc(o,i,s,n+_r,r-_r),e.closePath(),e.clip()}function lbe(e){return QM(e,["outerStart","outerEnd","innerStart","innerEnd"])}function cbe(e,t,n,r){const s=lbe(e.options.borderRadius),o=(n-t)/2,i=Math.min(o,r*t/2),a=l=>{const u=(n-Math.min(o,l))*r/2;return rs(l,0,Math.min(o,u))};return{outerStart:a(s.outerStart),outerEnd:a(s.outerEnd),innerStart:rs(s.innerStart,0,i),innerEnd:rs(s.innerEnd,0,i)}}function Wf(e,t,n,r){return{x:n+e*Math.cos(t),y:r+e*Math.sin(t)}}function xw(e,t,n,r,s,o){const{x:i,y:a,startAngle:l,pixelMargin:u,innerRadius:d}=t,f=Math.max(t.outerRadius+r+n-u,0),h=d>0?d+r+n+u:0;let m=0;const p=s-l;if(r){const I=d>0?d-r:0,$=f>0?f-r:0,V=(I+$)/2,W=V!==0?p*V/(V+r):p;m=(p-W)/2}const g=Math.max(.001,p*f-n/hn)/f,b=(p-g)/2,x=l+b+m,y=s-b-m,{outerStart:v,outerEnd:w,innerStart:j,innerEnd:S}=cbe(t,h,f,y-x),N=f-v,E=f-w,_=x+v/N,k=y-w/E,M=h+j,T=h+S,P=x+j/M,O=y-S/T;if(e.beginPath(),o){const I=(_+k)/2;if(e.arc(i,a,f,_,I),e.arc(i,a,f,I,k),w>0){const L=Wf(E,k,i,a);e.arc(L.x,L.y,w,k,y+_r)}const $=Wf(T,y,i,a);if(e.lineTo($.x,$.y),S>0){const L=Wf(T,O,i,a);e.arc(L.x,L.y,S,y+_r,O+Math.PI)}const V=(y-S/h+(x+j/h))/2;if(e.arc(i,a,h,y-S/h,V,!0),e.arc(i,a,h,V,x+j/h,!0),j>0){const L=Wf(M,P,i,a);e.arc(L.x,L.y,j,P+Math.PI,x-_r)}const W=Wf(N,x,i,a);if(e.lineTo(W.x,W.y),v>0){const L=Wf(N,_,i,a);e.arc(L.x,L.y,v,x-_r,_)}}else{e.moveTo(i,a);const I=Math.cos(_)*f+i,$=Math.sin(_)*f+a;e.lineTo(I,$);const V=Math.cos(k)*f+i,W=Math.sin(k)*f+a;e.lineTo(V,W)}e.closePath()}function ube(e,t,n,r,s){const{fullCircles:o,startAngle:i,circumference:a}=t;let l=t.endAngle;if(o){xw(e,t,n,r,l,s);for(let u=0;u<o;++u)e.fill();isNaN(a)||(l=i+(a%Xn||Xn))}return xw(e,t,n,r,l,s),e.fill(),l}function dbe(e,t,n,r,s){const{fullCircles:o,startAngle:i,circumference:a,options:l}=t,{borderWidth:u,borderJoinStyle:d,borderDash:f,borderDashOffset:h,borderRadius:m}=l,p=l.borderAlign==="inner";if(!u)return;e.setLineDash(f||[]),e.lineDashOffset=h,p?(e.lineWidth=u*2,e.lineJoin=d||"round"):(e.lineWidth=u,e.lineJoin=d||"bevel");let g=t.endAngle;if(o){xw(e,t,n,r,g,s);for(let b=0;b<o;++b)e.stroke();isNaN(a)||(g=i+(a%Xn||Xn))}p&&abe(e,t,g),l.selfJoin&&g-i>=hn&&m===0&&d!=="miter"&&ibe(e,t,g),o||(xw(e,t,n,r,g,s),e.stroke())}class fh extends wi{constructor(n){super();Ue(this,"circumference");Ue(this,"endAngle");Ue(this,"fullCircles");Ue(this,"innerRadius");Ue(this,"outerRadius");Ue(this,"pixelMargin");Ue(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}=kV(o,{x:n,y:r}),{startAngle:l,endAngle:u,innerRadius:d,outerRadius:f,circumference:h}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],s),m=(this.options.spacing+this.options.borderWidth)/2,p=mt(h,u-l),g=wb(i,l,u)&&l!==u,b=p>=Xn||g,x=_l(a,d+m,f+m);return b&&x}getCenterPoint(n){const{x:r,y:s,startAngle:o,endAngle:i,innerRadius:a,outerRadius:l}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],n),{offset:u,spacing:d}=this.options,f=(o+i)/2,h=(a+l+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>Xn?Math.floor(s/Xn):0,s===0||this.innerRadius<0||this.outerRadius<0)return;n.save();const l=(this.startAngle+this.endAngle)/2;n.translate(Math.cos(l)*o,Math.sin(l)*o);const u=1-Math.sin(Math.min(hn,s||0)),d=o*u;n.fillStyle=r.backgroundColor,n.strokeStyle=r.borderColor,ube(n,this,d,i,a),dbe(n,this,d,i,a),n.restore()}}Ue(fh,"id","arc"),Ue(fh,"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}),Ue(fh,"defaultRoutes",{backgroundColor:"backgroundColor"}),Ue(fh,"descriptors",{_scriptable:!0,_indexable:n=>n!=="borderDash"});function oH(e,t,n=t){e.lineCap=mt(n.borderCapStyle,t.borderCapStyle),e.setLineDash(mt(n.borderDash,t.borderDash)),e.lineDashOffset=mt(n.borderDashOffset,t.borderDashOffset),e.lineJoin=mt(n.borderJoinStyle,t.borderJoinStyle),e.lineWidth=mt(n.borderWidth,t.borderWidth),e.strokeStyle=mt(n.borderColor,t.borderColor)}function fbe(e,t,n){e.lineTo(n.x,n.y)}function hbe(e){return e.stepped?Pme:e.tension||e.cubicInterpolationMode==="monotone"?Ome:fbe}function iH(e,t,n={}){const r=e.length,{start:s=0,end:o=r-1}=n,{start:i,end:a}=t,l=Math.max(s,i),u=Math.min(o,a),d=s<i&&o<i||s>a&&o>a;return{count:r,start:l,loop:t.loop,ilen:u<l&&!d?r+u-l:u-l}}function mbe(e,t,n,r){const{points:s,options:o}=t,{count:i,start:a,loop:l,ilen:u}=iH(s,n,r),d=hbe(o);let{move:f=!0,reverse:h}=r||{},m,p,g;for(m=0;m<=u;++m)p=s[(a+(h?u-m:m))%i],!p.skip&&(f?(e.moveTo(p.x,p.y),f=!1):d(e,g,p,h,o.stepped),g=p);return l&&(p=s[(a+(h?u:0))%i],d(e,g,p,h,o.stepped)),!!l}function pbe(e,t,n,r){const s=t.points,{count:o,start:i,ilen:a}=iH(s,n,r),{move:l=!0,reverse:u}=r||{};let d=0,f=0,h,m,p,g,b,x;const y=w=>(i+(u?a-w:w))%o,v=()=>{g!==b&&(e.lineTo(d,b),e.lineTo(d,g),e.lineTo(d,x))};for(l&&(m=s[y(0)],e.moveTo(m.x,m.y)),h=0;h<=a;++h){if(m=s[y(h)],m.skip)continue;const w=m.x,j=m.y,S=w|0;S===p?(j<g?g=j:j>b&&(b=j),d=(f*d+w)/++f):(v(),e.lineTo(w,j),p=S,f=0,g=b=j),x=j}v()}function aE(e){const t=e.options,n=t.borderDash&&t.borderDash.length;return!e._decimated&&!e._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!n?pbe:mbe}function gbe(e){return e.stepped?mpe:e.tension||e.cubicInterpolationMode==="monotone"?ppe:Xu}function bbe(e,t,n,r){let s=t._path;s||(s=t._path=new Path2D,t.path(s,n,r)&&s.closePath()),oH(e,t.options),e.stroke(s)}function xbe(e,t,n,r){const{segments:s,options:o}=t,i=aE(t);for(const a of s)oH(e,o,a.style),e.beginPath(),i(e,t,a,{start:n,end:n+r-1})&&e.closePath(),e.stroke()}const ybe=typeof Path2D=="function";function vbe(e,t,n,r){ybe&&!t.options.segment?bbe(e,t,n,r):xbe(e,t,n,r)}class Vc extends wi{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;ipe(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=wpe(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=WV(this,{property:n,start:s,end:s});if(!i.length)return;const a=[],l=gbe(r);let u,d;for(u=0,d=i.length;u<d;++u){const{start:f,end:h}=i[u],m=o[f],p=o[h];if(m===p){a.push(m);continue}const g=Math.abs((s-m[n])/(p[n]-m[n])),b=l(m,p,g,r.stepped);b[n]=t[n],a.push(b)}return a.length===1?a[0]:a}pathSegment(t,n,r){return aE(this)(t,this,n,r)}path(t,n,r){const s=this.segments,o=aE(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(),vbe(t,this,r,s),t.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}Ue(Vc,"id","line"),Ue(Vc,"defaults",{borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0}),Ue(Vc,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"}),Ue(Vc,"descriptors",{_scriptable:!0,_indexable:t=>t!=="borderDash"&&t!=="fill"});function mF(e,t,n,r){const s=e.options,{[n]:o}=e.getProps([n],r);return Math.abs(t-o)<s.radius+s.hitRadius}class Rd extends wi{constructor(n){super();Ue(this,"parsed");Ue(this,"skip");Ue(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 mF(this,n,"x",r)}inYRange(n,r){return mF(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||!Ml(this,r,this.size(s)/2)||(n.strokeStyle=s.borderColor,n.lineWidth=s.borderWidth,n.fillStyle=s.backgroundColor,pw(n,s,this.x,this.y))}getRange(){const n=this.options||{};return n.radius+n.hitRadius}}Ue(Rd,"id","point"),Ue(Rd,"defaults",{borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0}),Ue(Rd,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});function aH(e,t){const{x:n,y:r,base:s,width:o,height:i}=e.getProps(["x","y","base","width","height"],t);let a,l,u,d,f;return e.horizontal?(f=i/2,a=Math.min(n,s),l=Math.max(n,s),u=r-f,d=r+f):(f=o/2,a=n-f,l=n+f,u=Math.min(r,s),d=Math.max(r,s)),{left:a,top:u,right:l,bottom:d}}function Hc(e,t,n,r){return e?0:rs(t,n,r)}function wbe(e,t,n){const r=e.options.borderWidth,s=e.borderSkipped,o=JM(r);return{t:Hc(s.top,o.top,0,n),r:Hc(s.right,o.right,0,t),b:Hc(s.bottom,o.bottom,0,n),l:Hc(s.left,o.left,0,t)}}function Cbe(e,t,n){const{enableBorderRadius:r}=e.getProps(["enableBorderRadius"]),s=e.options.borderRadius,o=Bl(s),i=Math.min(t,n),a=e.borderSkipped,l=r||Pt(s);return{topLeft:Hc(!l||a.top||a.left,o.topLeft,0,i),topRight:Hc(!l||a.top||a.right,o.topRight,0,i),bottomLeft:Hc(!l||a.bottom||a.left,o.bottomLeft,0,i),bottomRight:Hc(!l||a.bottom||a.right,o.bottomRight,0,i)}}function Sbe(e){const t=aH(e),n=t.right-t.left,r=t.bottom-t.top,s=wbe(e,n/2,r/2),o=Cbe(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 Wj(e,t,n,r){const s=t===null,o=n===null,a=e&&!(s&&o)&&aH(e,r);return a&&(s||_l(t,a.left,a.right))&&(o||_l(n,a.top,a.bottom))}function jbe(e){return e.topLeft||e.topRight||e.bottomLeft||e.bottomRight}function Nbe(e,t){e.rect(t.x,t.y,t.w,t.h)}function qj(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 Oa extends wi{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}=Sbe(this),a=jbe(i.radius)?zl:Nbe;t.save(),(i.w!==o.w||i.h!==o.h)&&(t.beginPath(),a(t,qj(i,n,o)),t.clip(),a(t,qj(o,-n,i)),t.fillStyle=r,t.fill("evenodd")),t.beginPath(),a(t,qj(o,n)),t.fillStyle=s,t.fill(),t.restore()}inRange(t,n,r){return Wj(this,t,n,r)}inXRange(t,n){return Wj(this,t,null,n)}inYRange(t,n){return Wj(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}}Ue(Oa,"id","bar"),Ue(Oa,"defaults",{borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0}),Ue(Oa,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});var kbe=Object.freeze({__proto__:null,ArcElement:fh,BarElement:Oa,LineElement:Vc,PointElement:Rd});const lE=["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)"],pF=lE.map(e=>e.replace("rgb(","rgba(").replace(")",", 0.5)"));function lH(e){return lE[e%lE.length]}function cH(e){return pF[e%pF.length]}function Ebe(e,t){return e.borderColor=lH(t),e.backgroundColor=cH(t),++t}function _be(e,t){return e.backgroundColor=e.data.map(()=>lH(t++)),t}function Tbe(e,t){return e.backgroundColor=e.data.map(()=>cH(t++)),t}function Mbe(e){let t=0;return(n,r)=>{const s=e.getDatasetMeta(r).controller;s instanceof dd?t=_be(n,t):s instanceof Pg?t=Tbe(n,t):s&&(t=Ebe(n,t))}}function gF(e){let t;for(t in e)if(e[t].borderColor||e[t].backgroundColor)return!0;return!1}function Dbe(e){return e&&(e.borderColor||e.backgroundColor)}function Ibe(){return Qn.borderColor!=="rgba(0,0,0,0.1)"||Qn.backgroundColor!=="rgba(0,0,0,0.1)"}var Rbe={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=gF(r)||Dbe(s)||o&&gF(o)||Ibe();if(!n.forceOverride&&i)return;const a=Mbe(e);r.forEach(a)}};function Abe(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 l=0;const u=t+n-1;let d=t,f,h,m,p,g;for(i[l++]=e[d],f=0;f<o-2;f++){let b=0,x=0,y;const v=Math.floor((f+1)*a)+1+t,w=Math.min(Math.floor((f+2)*a)+1,n)+t,j=w-v;for(y=v;y<w;y++)b+=e[y].x,x+=e[y].y;b/=j,x/=j;const S=Math.floor(f*a)+1+t,N=Math.min(Math.floor((f+1)*a)+1,n)+t,{x:E,y:_}=e[d];for(m=p=-1,y=S;y<N;y++)p=.5*Math.abs((E-b)*(e[y].y-_)-(E-e[y].x)*(x-_)),p>m&&(m=p,h=e[y],g=y);i[l++]=h,d=g}return i[l++]=e[u],i}function Pbe(e,t,n,r){let s=0,o=0,i,a,l,u,d,f,h,m,p,g;const b=[],x=t+n-1,y=e[t].x,w=e[x].x-y;for(i=t;i<t+n;++i){a=e[i],l=(a.x-y)/w*r,u=a.y;const j=l|0;if(j===d)u<p?(p=u,f=i):u>g&&(g=u,h=i),s=(o*s+a.x)/++o;else{const S=i-1;if(!_t(f)&&!_t(h)){const N=Math.min(f,h),E=Math.max(f,h);N!==m&&N!==S&&b.push({...e[N],x:s}),E!==m&&E!==S&&b.push({...e[E],x:s})}i>0&&S!==m&&b.push(e[S]),b.push(a),d=j,o=0,p=g=u,f=h=m=i}}return b}function uH(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 bF(e){e.data.datasets.forEach(t=>{uH(t)})}function Obe(e,t){const n=t.length;let r=0,s;const{iScale:o}=e,{min:i,max:a,minDefined:l,maxDefined:u}=o.getUserBounds();return l&&(r=rs(Tl(t,o.axis,i).lo,0,n-1)),u?s=rs(Tl(t,o.axis,a).hi+1,r,n)-r:s=n-r,{start:r,count:s}}var Fbe={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(e,t,n)=>{if(!n.enabled){bF(e);return}const r=e.width;e.data.datasets.forEach((s,o)=>{const{_data:i,indexAxis:a}=s,l=e.getDatasetMeta(o),u=i||s.data;if(Kn([a,e.options.indexAxis])==="y"||!l.controller.supportsDecimation)return;const d=e.scales[l.xAxisID];if(d.type!=="linear"&&d.type!=="time"||e.options.parsing)return;let{start:f,count:h}=Obe(l,u);const m=n.threshold||4*r;if(h<=m){uH(s);return}_t(i)&&(s._data=u,delete s.data,Object.defineProperty(s,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(g){this._data=g}}));let p;switch(n.algorithm){case"lttb":p=Abe(u,f,h,r,n);break;case"min-max":p=Pbe(u,f,h,r);break;default:throw new Error(`Unsupported decimation algorithm '${n.algorithm}'`)}s._decimated=p})},destroy(e){bF(e)}};function $be(e,t,n){const r=e.segments,s=e.points,o=t.points,i=[];for(const a of r){let{start:l,end:u}=a;u=wC(l,u,s);const d=cE(n,s[l],s[u],a.loop);if(!t.segments){i.push({source:a,target:d,start:s[l],end:s[u]});continue}const f=WV(t,d);for(const h of f){const m=cE(n,o[h.start],o[h.end],h.loop),p=UV(a,s,m);for(const g of p)i.push({source:g,target:h,start:{[n]:xF(d,m,"start",Math.max)},end:{[n]:xF(d,m,"end",Math.min)}})}}return i}function cE(e,t,n,r){if(r)return;let s=t[e],o=n[e];return e==="angle"&&(s=ks(s),o=ks(o)),{property:e,start:s,end:o}}function Lbe(e,t){const{x:n=null,y:r=null}=e||{},s=t.points,o=[];return t.segments.forEach(({start:i,end:a})=>{a=wC(i,a,s);const l=s[i],u=s[a];r!==null?(o.push({x:l.x,y:r}),o.push({x:u.x,y:r})):n!==null&&(o.push({x:n,y:l.y}),o.push({x:n,y:u.y}))}),o}function wC(e,t,n){for(;t>e;t--){const r=n[t];if(!isNaN(r.x)&&!isNaN(r.y))break}return t}function xF(e,t,n,r){return e&&t?r(e[n],t[n]):e?e[n]:t?t[n]:0}function dH(e,t){let n=[],r=!1;return Pn(e)?(r=!0,n=e):n=Lbe(e,t),n.length?new Vc({points:n,options:{tension:0},_loop:r,_fullLoop:r}):null}function yF(e){return e&&e.fill!==!1}function zbe(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(!br(s))return s;if(i=e[s],!i)return!1;if(i.visible)return s;o.push(s),s=i.fill}return!1}function Bbe(e,t,n){const r=Wbe(e);if(Pt(r))return isNaN(r.value)?!1:r;let s=parseFloat(r);return br(s)&&Math.floor(s)===s?Vbe(r[0],t,s,n):["origin","start","end","stack","shape"].indexOf(r)>=0&&r}function Vbe(e,t,n,r){return(e==="-"||e==="+")&&(n=t+n),n===t||n<0||n>=r?!1:n}function Hbe(e,t){let n=null;return e==="start"?n=t.bottom:e==="end"?n=t.top:Pt(e)?n=t.getPixelForValue(e.value):t.getBasePixel&&(n=t.getBasePixel()),n}function Ube(e,t,n){let r;return e==="start"?r=n:e==="end"?r=t.options.reverse?t.min:t.max:Pt(e)?r=e.value:r=t.getBaseValue(),r}function Wbe(e){const t=e.options,n=t.fill;let r=mt(n&&n.target,n);return r===void 0&&(r=!!t.backgroundColor),r===!1||r===null?!1:r===!0?"origin":r}function qbe(e){const{scale:t,index:n,line:r}=e,s=[],o=r.segments,i=r.points,a=Ybe(t,n);a.push(dH({x:null,y:t.bottom},r));for(let l=0;l<o.length;l++){const u=o[l];for(let d=u.start;d<=u.end;d++)Gbe(s,i[d],a)}return new Vc({points:s,options:{}})}function Ybe(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 Gbe(e,t,n){const r=[];for(let s=0;s<n.length;s++){const o=n[s],{first:i,last:a,point:l}=Kbe(o,t,"x");if(!(!l||i&&a)){if(i)r.unshift(l);else if(e.push(l),!a)break}}e.push(...r)}function Kbe(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,l=!1;for(let u=0;u<o.length;u++){const d=o[u],f=i[d.start][n],h=i[d.end][n];if(_l(s,f,h)){a=s===f,l=s===h;break}}return{first:a,last:l,point:r}}class fH{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:Xn},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 Zbe(e){const{chart:t,fill:n,line:r}=e;if(br(n))return Xbe(t,n);if(n==="stack")return qbe(e);if(n==="shape")return!0;const s=Qbe(e);return s instanceof fH?s:dH(s,r)}function Xbe(e,t){const n=e.getDatasetMeta(t);return n&&e.isDatasetVisible(t)?n.dataset:null}function Qbe(e){return(e.scale||{}).getPointPositionForValue?exe(e):Jbe(e)}function Jbe(e){const{scale:t={},fill:n}=e,r=Hbe(n,t);if(br(r)){const s=t.isHorizontal();return{x:s?r:null,y:s?null:r}}return null}function exe(e){const{scale:t,fill:n}=e,r=t.options,s=t.getLabels().length,o=r.reverse?t.max:t.min,i=Ube(n,t,o),a=[];if(r.grid.circular){const l=t.getPointPositionForValue(0,o);return new fH({x:l.x,y:l.y,radius:t.getDistanceFromCenterForValue(i)})}for(let l=0;l<s;++l)a.push(t.getPointPositionForValue(l,i));return a}function Yj(e,t,n){const r=Zbe(t),{chart:s,index:o,line:i,scale:a,axis:l}=t,u=i.options,d=u.fill,f=u.backgroundColor,{above:h=f,below:m=f}=d||{},p=s.getDatasetMeta(o),g=qV(s,p);r&&i.points.length&&(Kc(e,n),txe(e,{line:i,target:r,above:h,below:m,area:n,scale:a,axis:l,clip:g}),Zc(e))}function txe(e,t){const{line:n,target:r,above:s,below:o,area:i,scale:a,clip:l}=t,u=n._loop?"angle":t.axis;e.save();let d=o;o!==s&&(u==="x"?(vF(e,r,i.top),Gj(e,{line:n,target:r,color:s,scale:a,property:u,clip:l}),e.restore(),e.save(),vF(e,r,i.bottom)):u==="y"&&(wF(e,r,i.left),Gj(e,{line:n,target:r,color:o,scale:a,property:u,clip:l}),e.restore(),e.save(),wF(e,r,i.right),d=s)),Gj(e,{line:n,target:r,color:d,scale:a,property:u,clip:l}),e.restore()}function vF(e,t,n){const{segments:r,points:s}=t;let o=!0,i=!1;e.beginPath();for(const a of r){const{start:l,end:u}=a,d=s[l],f=s[wC(l,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 wF(e,t,n){const{segments:r,points:s}=t;let o=!0,i=!1;e.beginPath();for(const a of r){const{start:l,end:u}=a,d=s[l],f=s[wC(l,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 Gj(e,t){const{line:n,target:r,property:s,color:o,scale:i,clip:a}=t,l=$be(n,r,s);for(const{source:u,target:d,start:f,end:h}of l){const{style:{backgroundColor:m=o}={}}=u,p=r!==!0;e.save(),e.fillStyle=m,nxe(e,i,a,p&&cE(s,f,h)),e.beginPath();const g=!!n.pathSegment(e,u);let b;if(p){g?e.closePath():CF(e,r,h,s);const x=!!r.pathSegment(e,d,{move:g,reverse:!0});b=g&&x,b||CF(e,r,f,s)}e.closePath(),e.fill(b?"evenodd":"nonzero"),e.restore()}}function nxe(e,t,n,r){const s=t.chart.chartArea,{property:o,start:i,end:a}=r||{};if(o==="x"||o==="y"){let l,u,d,f;o==="x"?(l=i,u=s.top,d=a,f=s.bottom):(l=s.left,u=i,d=s.right,f=a),e.beginPath(),n&&(l=Math.max(l,n.left),d=Math.min(d,n.right),u=Math.max(u,n.top),f=Math.min(f,n.bottom)),e.rect(l,u,d-l,f-u),e.clip()}}function CF(e,t,n,r){const s=t.interpolate(n,r);s&&e.lineTo(s.x,s.y)}var rxe={id:"filler",afterDatasetsUpdate(e,t,n){const r=(e.data.datasets||[]).length,s=[];let o,i,a,l;for(i=0;i<r;++i)o=e.getDatasetMeta(i),a=o.dataset,l=null,a&&a.options&&a instanceof Vc&&(l={visible:e.isDatasetVisible(i),index:i,fill:Bbe(a,i,r),chart:e,axis:o.controller.options.indexAxis,scale:o.vScale,line:a}),o.$filler=l,s.push(l);for(i=0;i<r;++i)l=s[i],!(!l||l.fill===!1)&&(l.fill=zbe(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&&Yj(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;yF(o)&&Yj(e.ctx,o,e.chartArea)}},beforeDatasetDraw(e,t,n){const r=t.meta.$filler;!yF(r)||n.drawTime!=="beforeDatasetDraw"||Yj(e.ctx,r,e.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const SF=(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)}},sxe=(e,t)=>e!==null&&t!==null&&e.datasetIndex===t.datasetIndex&&e.index===t.index;class jF extends wi{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=In(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=Un(r.font),o=s.size,i=this._computeTitleHeight(),{boxWidth:a,itemHeight:l}=SF(r,o);let u,d;n.font=s.string,this.isHorizontal()?(u=this.maxWidth,d=this._fitRows(i,o,a,l)+10):(d=this.maxHeight,u=this._fitCols(i,s,a,l)+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,l=this.legendHitBoxes=[],u=this.lineWidths=[0],d=s+a;let f=t;o.textAlign="left",o.textBaseline="middle";let h=-1,m=-d;return this.legendItems.forEach((p,g)=>{const b=r+n/2+o.measureText(p.text).width;(g===0||u[u.length-1]+b+2*a>i)&&(f+=d,u[u.length-(g>0?0:1)]=0,m+=d,h++),l[g]={left:0,top:m,row:h,width:b,height:s},u[u.length-1]+=b+a}),f}_fitCols(t,n,r,s){const{ctx:o,maxHeight:i,options:{labels:{padding:a}}}=this,l=this.legendHitBoxes=[],u=this.columnSizes=[],d=i-t;let f=a,h=0,m=0,p=0,g=0;return this.legendItems.forEach((b,x)=>{const{itemWidth:y,itemHeight:v}=oxe(r,n,o,b,s);x>0&&m+v+2*a>d&&(f+=h+a,u.push({width:h,height:m}),p+=h+a,g++,h=m=0),l[x]={left:p,top:m,col:g,width:y,height:v},h=Math.max(h,y),m+=v+a}),f+=h,u.push({width:h,height:m}),f}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:n,options:{align:r,labels:{padding:s},rtl:o}}=this,i=Th(o,this.left,this.width);if(this.isHorizontal()){let a=0,l=Ss(r,this.left+s,this.right-this.lineWidths[a]);for(const u of n)a!==u.row&&(a=u.row,l=Ss(r,this.left+s,this.right-this.lineWidths[a])),u.top+=this.top+t+s,u.left=i.leftForLtr(i.x(l),u.width),l+=u.width+s}else{let a=0,l=Ss(r,this.top+t+s,this.bottom-this.columnSizes[a].height);for(const u of n)u.col!==a&&(a=u.col,l=Ss(r,this.top+t+s,this.bottom-this.columnSizes[a].height)),u.top=l,u.left+=this.left+s,u.left=i.leftForLtr(i.x(u.left),u.width),l+=u.height+s}}isHorizontal(){return this.options.position==="top"||this.options.position==="bottom"}draw(){if(this.options.display){const t=this.ctx;Kc(t,this),this._draw(),Zc(t)}}_draw(){const{options:t,columnSizes:n,lineWidths:r,ctx:s}=this,{align:o,labels:i}=t,a=Qn.color,l=Th(t.rtl,this.left,this.width),u=Un(i.font),{padding:d}=i,f=u.size,h=f/2;let m;this.drawTitle(),s.textAlign=l.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=u.string;const{boxWidth:p,boxHeight:g,itemHeight:b}=SF(i,f),x=function(S,N,E){if(isNaN(p)||p<=0||isNaN(g)||g<0)return;s.save();const _=mt(E.lineWidth,1);if(s.fillStyle=mt(E.fillStyle,a),s.lineCap=mt(E.lineCap,"butt"),s.lineDashOffset=mt(E.lineDashOffset,0),s.lineJoin=mt(E.lineJoin,"miter"),s.lineWidth=_,s.strokeStyle=mt(E.strokeStyle,a),s.setLineDash(mt(E.lineDash,[])),i.usePointStyle){const k={radius:g*Math.SQRT2/2,pointStyle:E.pointStyle,rotation:E.rotation,borderWidth:_},M=l.xPlus(S,p/2),T=N+h;AV(s,k,M,T,i.pointStyleWidth&&p)}else{const k=N+Math.max((f-g)/2,0),M=l.leftForLtr(S,p),T=Bl(E.borderRadius);s.beginPath(),Object.values(T).some(P=>P!==0)?zl(s,{x:M,y:k,w:p,h:g,radius:T}):s.rect(M,k,p,g),s.fill(),_!==0&&s.stroke()}s.restore()},y=function(S,N,E){ef(s,E.text,S,N+b/2,u,{strikethrough:E.hidden,textAlign:l.textAlign(E.textAlign)})},v=this.isHorizontal(),w=this._computeTitleHeight();v?m={x:Ss(o,this.left+d,this.right-r[0]),y:this.top+d+w,line:0}:m={x:this.left+d,y:Ss(o,this.top+w+d,this.bottom-n[0].height),line:0},BV(this.ctx,t.textDirection);const j=b+d;this.legendItems.forEach((S,N)=>{s.strokeStyle=S.fontColor,s.fillStyle=S.fontColor;const E=s.measureText(S.text).width,_=l.textAlign(S.textAlign||(S.textAlign=i.textAlign)),k=p+h+E;let M=m.x,T=m.y;l.setWidth(this.width),v?N>0&&M+k+d>this.right&&(T=m.y+=j,m.line++,M=m.x=Ss(o,this.left+d,this.right-r[m.line])):N>0&&T+j>this.bottom&&(M=m.x=M+n[m.line].width+d,m.line++,T=m.y=Ss(o,this.top+w+d,this.bottom-n[m.line].height));const P=l.x(M);if(x(P,T,S),M=jme(_,M+p+h,v?M+k:this.right,t.rtl),y(l.x(M),T,S),v)m.x+=k+d;else if(typeof S.text!="string"){const O=u.lineHeight;m.y+=hH(S,O)+d}else m.y+=j}),VV(this.ctx,t.textDirection)}drawTitle(){const t=this.options,n=t.title,r=Un(n.font),s=bs(n.padding);if(!n.display)return;const o=Th(t.rtl,this.left,this.width),i=this.ctx,a=n.position,l=r.size/2,u=s.top+l;let d,f=this.left,h=this.width;if(this.isHorizontal())h=Math.max(...this.lineWidths),d=this.top+u,f=Ss(t.align,f,this.right-h);else{const p=this.columnSizes.reduce((g,b)=>Math.max(g,b.height),0);d=u+Ss(t.align,this.top,this.bottom-p-t.labels.padding-this._computeTitleHeight())}const m=Ss(a,f,f+h);i.textAlign=o.textAlign(ZM(a)),i.textBaseline="middle",i.strokeStyle=n.color,i.fillStyle=n.color,i.font=r.string,ef(i,n.text,m,d,r)}_computeTitleHeight(){const t=this.options.title,n=Un(t.font),r=bs(t.padding);return t.display?n.lineHeight+r.height:0}_getLegendItemAt(t,n){let r,s,o;if(_l(t,this.left,this.right)&&_l(n,this.top,this.bottom)){for(o=this.legendHitBoxes,r=0;r<o.length;++r)if(s=o[r],_l(t,s.left,s.left+s.width)&&_l(n,s.top,s.top+s.height))return this.legendItems[r]}return null}handleEvent(t){const n=this.options;if(!lxe(t.type,n))return;const r=this._getLegendItemAt(t.x,t.y);if(t.type==="mousemove"||t.type==="mouseout"){const s=this._hoveredItem,o=sxe(s,r);s&&!o&&In(n.onLeave,[t,s,this],this),this._hoveredItem=r,r&&!o&&In(n.onHover,[t,r,this],this)}else r&&In(n.onClick,[t,r,this],this)}}function oxe(e,t,n,r,s){const o=ixe(r,e,t,n),i=axe(s,r,t.lineHeight);return{itemWidth:o,itemHeight:i}}function ixe(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 axe(e,t,n){let r=e;return typeof t.text!="string"&&(r=hH(t,n)),r}function hH(e,t){const n=e.text?e.text.length:0;return t*n}function lxe(e,t){return!!((e==="mousemove"||e==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(e==="click"||e==="mouseup"))}var cxe={id:"legend",_element:jF,start(e,t,n){const r=e.legend=new jF({ctx:e.ctx,options:n,chart:e});Ts.configure(e,r,n),Ts.addBox(e,r)},stop(e){Ts.removeBox(e,e.legend),delete e.legend},beforeUpdate(e,t,n){const r=e.legend;Ts.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(l=>{const u=l.controller.getStyle(n?0:void 0),d=bs(u.borderWidth);return{text:t[l.index].label,fillStyle:u.backgroundColor,fontColor:o,hidden:!l.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:l.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 iD extends wi{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=Pn(r.text)?r.text.length:1;this._padding=bs(r.padding);const o=s*Un(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 l=0,u,d,f;return this.isHorizontal()?(d=Ss(a,r,o),f=n+t,u=o-r):(i.position==="left"?(d=r+t,f=Ss(a,s,n),l=hn*-.5):(d=o-t,f=Ss(a,n,s),l=hn*.5),u=s-n),{titleX:d,titleY:f,maxWidth:u,rotation:l}}draw(){const t=this.ctx,n=this.options;if(!n.display)return;const r=Un(n.font),o=r.lineHeight/2+this._padding.top,{titleX:i,titleY:a,maxWidth:l,rotation:u}=this._drawArgs(o);ef(t,n.text,0,0,r,{color:n.color,maxWidth:l,rotation:u,textAlign:ZM(n.align),textBaseline:"middle",translation:[i,a]})}}function uxe(e,t){const n=new iD({ctx:e.ctx,options:t,chart:e});Ts.configure(e,n,t),Ts.addBox(e,n),e.titleBlock=n}var dxe={id:"title",_element:iD,start(e,t,n){uxe(e,n)},stop(e){const t=e.titleBlock;Ts.removeBox(e,t),delete e.titleBlock},beforeUpdate(e,t,n){const r=e.titleBlock;Ts.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 d0=new WeakMap;var fxe={id:"subtitle",start(e,t,n){const r=new iD({ctx:e.ctx,options:n,chart:e});Ts.configure(e,r,n),Ts.addBox(e,r),d0.set(e,r)},stop(e){Ts.removeBox(e,d0.get(e)),d0.delete(e)},beforeUpdate(e,t,n){const r=d0.get(e);Ts.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 lg={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 l=a.tooltipPosition();r.add(l.x),s+=l.y,++o}}return o===0||r.size===0?!1:{x:[...r].reduce((a,l)=>a+l)/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 l=e[o].element;if(l&&l.hasValue()){const u=l.getCenterPoint(),d=nE(t,u);d<s&&(s=d,a=l)}}if(a){const l=a.tooltipPosition();n=l.x,r=l.y}return{x:n,y:r}}};function fa(e,t){return t&&(Pn(t)?Array.prototype.push.apply(e,t):e.push(t)),e}function ul(e){return(typeof e=="string"||e instanceof String)&&e.indexOf(`
|
|
751
751
|
`)>-1?e.split(`
|
|
752
752
|
`):e}function hxe(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 NF(e,t){const n=e.chart.ctx,{body:r,footer:s,title:o}=e,{boxWidth:i,boxHeight:a}=t,l=Un(t.bodyFont),u=Un(t.titleFont),d=Un(t.footerFont),f=o.length,h=s.length,m=r.length,p=bs(t.padding);let g=p.height,b=0,x=r.reduce((w,j)=>w+j.before.length+j.lines.length+j.after.length,0);if(x+=e.beforeBody.length+e.afterBody.length,f&&(g+=f*u.lineHeight+(f-1)*t.titleSpacing+t.titleMarginBottom),x){const w=t.displayColors?Math.max(a,l.lineHeight):l.lineHeight;g+=m*w+(x-m)*l.lineHeight+(x-1)*t.bodySpacing}h&&(g+=t.footerMarginTop+h*d.lineHeight+(h-1)*t.footerSpacing);let y=0;const v=function(w){b=Math.max(b,n.measureText(w).width+y)};return n.save(),n.font=u.string,Nn(e.title,v),n.font=l.string,Nn(e.beforeBody.concat(e.afterBody),v),y=t.displayColors?i+2+t.boxPadding:0,Nn(r,w=>{Nn(w.before,v),Nn(w.lines,v),Nn(w.after,v)}),y=0,n.font=d.string,Nn(e.footer,v),n.restore(),b+=p.width,{width:b,height:g}}function mxe(e,t){const{y:n,height:r}=t;return n<r/2?"top":n>e.height-r/2?"bottom":"center"}function pxe(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 gxe(e,t,n,r){const{x:s,width:o}=n,{width:i,chartArea:{left:a,right:l}}=e;let u="center";return r==="center"?u=s<=(a+l)/2?"left":"right":s<=o/2?u="left":s>=i-o/2&&(u="right"),pxe(u,e,t,n)&&(u="center"),u}function kF(e,t,n){const r=n.yAlign||t.yAlign||mxe(e,n);return{xAlign:n.xAlign||t.xAlign||gxe(e,t,n,r),yAlign:r}}function bxe(e,t){let{x:n,width:r}=e;return t==="right"?n-=r:t==="center"&&(n-=r/2),n}function xxe(e,t,n){let{y:r,height:s}=e;return t==="top"?r+=n:t==="bottom"?r-=s+n:r-=s/2,r}function EF(e,t,n,r){const{caretSize:s,caretPadding:o,cornerRadius:i}=e,{xAlign:a,yAlign:l}=n,u=s+o,{topLeft:d,topRight:f,bottomLeft:h,bottomRight:m}=Bl(i);let p=bxe(t,a);const g=xxe(t,l,u);return l==="center"?a==="left"?p+=u:a==="right"&&(p-=u):a==="left"?p-=Math.max(d,h)+s:a==="right"&&(p+=Math.max(f,m)+s),{x:rs(p,0,r.width-t.width),y:rs(g,0,r.height-t.height)}}function f0(e,t,n){const r=bs(n.padding);return t==="center"?e.x+e.width/2:t==="right"?e.x+e.width-r.right:e.x+r.left}function _F(e){return fa([],ul(e))}function yxe(e,t,n){return ju(e,{tooltip:t,tooltipItems:n,type:"tooltip"})}function TF(e,t){const n=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return n?e.override(n):e}const mH={beforeTitle:il,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:il,beforeBody:il,beforeLabel:il,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 _t(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:il,afterBody:il,beforeFooter:il,footer:il,afterFooter:il};function io(e,t,n,r){const s=e[t].call(n,r);return typeof s>"u"?mH[t].call(n,r):s}class uE extends wi{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 YV(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(o)),o}getContext(){return this.$context||(this.$context=yxe(this.chart.getContext(),this,this._tooltipItems))}getTitle(t,n){const{callbacks:r}=n,s=io(r,"beforeTitle",this,t),o=io(r,"title",this,t),i=io(r,"afterTitle",this,t);let a=[];return a=fa(a,ul(s)),a=fa(a,ul(o)),a=fa(a,ul(i)),a}getBeforeBody(t,n){return _F(io(n.callbacks,"beforeBody",this,t))}getBody(t,n){const{callbacks:r}=n,s=[];return Nn(t,o=>{const i={before:[],lines:[],after:[]},a=TF(r,o);fa(i.before,ul(io(a,"beforeLabel",this,o))),fa(i.lines,io(a,"label",this,o)),fa(i.after,ul(io(a,"afterLabel",this,o))),s.push(i)}),s}getAfterBody(t,n){return _F(io(n.callbacks,"afterBody",this,t))}getFooter(t,n){const{callbacks:r}=n,s=io(r,"beforeFooter",this,t),o=io(r,"footer",this,t),i=io(r,"afterFooter",this,t);let a=[];return a=fa(a,ul(s)),a=fa(a,ul(o)),a=fa(a,ul(i)),a}_createItems(t){const n=this._active,r=this.chart.data,s=[],o=[],i=[];let a=[],l,u;for(l=0,u=n.length;l<u;++l)a.push(hxe(this.chart,n[l]));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))),Nn(a,d=>{const f=TF(t.callbacks,d);s.push(io(f,"labelColor",this,d)),o.push(io(f,"labelPointStyle",this,d)),i.push(io(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=lg[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 l=this._size=NF(this,r),u=Object.assign({},a,l),d=kF(this.chart,r,u),f=EF(r,u,d,this.chart);this.xAlign=d.xAlign,this.yAlign=d.yAlign,o={opacity:1,x:f.x,y:f.y,width:l.width,height:l.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:l,topRight:u,bottomLeft:d,bottomRight:f}=Bl(a),{x:h,y:m}=t,{width:p,height:g}=n;let b,x,y,v,w,j;return o==="center"?(w=m+g/2,s==="left"?(b=h,x=b-i,v=w+i,j=w-i):(b=h+p,x=b+i,v=w-i,j=w+i),y=b):(s==="left"?x=h+Math.max(l,d)+i:s==="right"?x=h+p-Math.max(u,f)-i:x=this.caretX,o==="top"?(v=m,w=v-i,b=x-i,y=x+i):(v=m+g,w=v+i,b=x+i,y=x-i),j=v),{x1:b,x2:x,x3:y,y1:v,y2:w,y3:j}}drawTitle(t,n,r){const s=this.title,o=s.length;let i,a,l;if(o){const u=Th(r.rtl,this.x,this.width);for(t.x=f0(this,r.titleAlign,r),n.textAlign=u.textAlign(r.titleAlign),n.textBaseline="middle",i=Un(r.titleFont),a=r.titleSpacing,n.fillStyle=r.titleColor,n.font=i.string,l=0;l<o;++l)n.fillText(s[l],u.x(t.x),t.y+i.lineHeight/2),t.y+=i.lineHeight+a,l+1===o&&(t.y+=r.titleMarginBottom-a)}}_drawColorBox(t,n,r,s,o){const i=this.labelColors[r],a=this.labelPointStyles[r],{boxHeight:l,boxWidth:u}=o,d=Un(o.bodyFont),f=f0(this,"left",o),h=s.x(f),m=l<d.lineHeight?(d.lineHeight-l)/2:0,p=n.y+m;if(o.usePointStyle){const g={radius:Math.min(u,l)/2,pointStyle:a.pointStyle,rotation:a.rotation,borderWidth:1},b=s.leftForLtr(h,u)+u/2,x=p+l/2;t.strokeStyle=o.multiKeyBackground,t.fillStyle=o.multiKeyBackground,pw(t,g,b,x),t.strokeStyle=i.borderColor,t.fillStyle=i.backgroundColor,pw(t,g,b,x)}else{t.lineWidth=Pt(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 g=s.leftForLtr(h,u),b=s.leftForLtr(s.xPlus(h,1),u-2),x=Bl(i.borderRadius);Object.values(x).some(y=>y!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,zl(t,{x:g,y:p,w:u,h:l,radius:x}),t.fill(),t.stroke(),t.fillStyle=i.backgroundColor,t.beginPath(),zl(t,{x:b,y:p+1,w:u-2,h:l-2,radius:x}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(g,p,u,l),t.strokeRect(g,p,u,l),t.fillStyle=i.backgroundColor,t.fillRect(b,p+1,u-2,l-2))}t.fillStyle=this.labelTextColors[r]}drawBody(t,n,r){const{body:s}=this,{bodySpacing:o,bodyAlign:i,displayColors:a,boxHeight:l,boxWidth:u,boxPadding:d}=r,f=Un(r.bodyFont);let h=f.lineHeight,m=0;const p=Th(r.rtl,this.x,this.width),g=function(E){n.fillText(E,p.x(t.x+m),t.y+h/2),t.y+=h+o},b=p.textAlign(i);let x,y,v,w,j,S,N;for(n.textAlign=i,n.textBaseline="middle",n.font=f.string,t.x=f0(this,b,r),n.fillStyle=r.bodyColor,Nn(this.beforeBody,g),m=a&&b!=="right"?i==="center"?u/2+d:u+2+d:0,w=0,S=s.length;w<S;++w){for(x=s[w],y=this.labelTextColors[w],n.fillStyle=y,Nn(x.before,g),v=x.lines,a&&v.length&&(this._drawColorBox(n,t,w,p,r),h=Math.max(f.lineHeight,l)),j=0,N=v.length;j<N;++j)g(v[j]),h=f.lineHeight;Nn(x.after,g)}m=0,h=f.lineHeight,Nn(this.afterBody,g),t.y-=o}drawFooter(t,n,r){const s=this.footer,o=s.length;let i,a;if(o){const l=Th(r.rtl,this.x,this.width);for(t.x=f0(this,r.footerAlign,r),t.y+=r.footerMarginTop,n.textAlign=l.textAlign(r.footerAlign),n.textBaseline="middle",i=Un(r.footerFont),n.fillStyle=r.footerColor,n.font=i.string,a=0;a<o;++a)n.fillText(s[a],l.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:l}=t,{width:u,height:d}=r,{topLeft:f,topRight:h,bottomLeft:m,bottomRight:p}=Bl(s.cornerRadius);n.fillStyle=s.backgroundColor,n.strokeStyle=s.borderColor,n.lineWidth=s.borderWidth,n.beginPath(),n.moveTo(a+f,l),i==="top"&&this.drawCaret(t,n,r,s),n.lineTo(a+u-h,l),n.quadraticCurveTo(a+u,l,a+u,l+h),i==="center"&&o==="right"&&this.drawCaret(t,n,r,s),n.lineTo(a+u,l+d-p),n.quadraticCurveTo(a+u,l+d,a+u-p,l+d),i==="bottom"&&this.drawCaret(t,n,r,s),n.lineTo(a+m,l+d),n.quadraticCurveTo(a,l+d,a,l+d-m),i==="center"&&o==="left"&&this.drawCaret(t,n,r,s),n.lineTo(a,l+f),n.quadraticCurveTo(a,l,a+f,l),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=lg[t.position].call(this,this._active,this._eventPosition);if(!i)return;const a=this._size=NF(this,t),l=Object.assign({},i,this._size),u=kF(n,t,l),d=EF(t,l,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=bs(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),BV(t,n.textDirection),o.y+=i.top,this.drawTitle(o,t,n),this.drawBody(o,t,n),this.drawFooter(o,t,n),VV(t,n.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,n){const r=this._active,s=t.map(({datasetIndex:a,index:l})=>{const u=this.chart.getDatasetMeta(a);if(!u)throw new Error("Cannot find a dataset at index "+a);return{datasetIndex:a,element:u.data[l],index:l}}),o=!dw(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),l=n||!dw(i,o)||a;return l&&(this._active=i,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,n))),l}_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=lg[o.position].call(this,t,n);return i!==!1&&(r!==i.x||s!==i.y)}}Ue(uE,"positioners",lg);var pH={id:"tooltip",_element:uE,positioners:lg,afterInit(e,t,n){n&&(e.tooltip=new uE({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:mH},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"]},vxe=Object.freeze({__proto__:null,Colors:Rbe,Decimation:Fbe,Filler:rxe,Legend:cxe,SubTitle:fxe,Title:dxe,Tooltip:pH});const wxe=(e,t,n,r)=>(typeof t=="string"?(n=e.push(t)-1,r.unshift({index:n,label:t})):isNaN(t)&&(n=null),n);function Cxe(e,t,n,r){const s=e.indexOf(t);if(s===-1)return wxe(e,t,n,r);const o=e.lastIndexOf(t);return s!==o?n:s}const Sxe=(e,t)=>e===null?null:rs(Math.round(e),0,t);function MF(e){const t=this.getLabels();return e>=0&&e<t.length?t[e]:e}class Sb extends Nu{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(_t(t))return null;const r=this.getLabels();return n=isFinite(n)&&r[n]===t?n:Cxe(r,t,mt(n,t),this._addedLabels),Sxe(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 MF.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}}Ue(Sb,"id","category"),Ue(Sb,"defaults",{ticks:{callback:MF}});function jxe(e,t){const n=[],{bounds:s,step:o,min:i,max:a,precision:l,count:u,maxTicks:d,maxDigits:f,includeBounds:h}=e,m=o||1,p=d-1,{min:g,max:b}=t,x=!_t(i),y=!_t(a),v=!_t(u),w=(b-g)/(f+1);let j=NO((b-g)/p/m)*m,S,N,E,_;if(j<1e-14&&!x&&!y)return[{value:g},{value:b}];_=Math.ceil(b/j)-Math.floor(g/j),_>p&&(j=NO(_*j/p/m)*m),_t(l)||(S=Math.pow(10,l),j=Math.ceil(j*S)/S),s==="ticks"?(N=Math.floor(g/j)*j,E=Math.ceil(b/j)*j):(N=g,E=b),x&&y&&o&&bme((a-i)/o,j/1e3)?(_=Math.round(Math.min((a-i)/j,d)),j=(a-i)/_,N=i,E=a):v?(N=x?i:N,E=y?a:E,_=u-1,j=(E-N)/_):(_=(E-N)/j,Ig(_,Math.round(_),j/1e3)?_=Math.round(_):_=Math.ceil(_));const k=Math.max(kO(j),kO(N));S=Math.pow(10,_t(l)?k:l),N=Math.round(N*S)/S,E=Math.round(E*S)/S;let M=0;for(x&&(h&&N!==i?(n.push({value:i}),N<i&&M++,Ig(Math.round((N+M*j)*S)/S,i,DF(i,w,e))&&M++):N<i&&M++);M<_;++M){const T=Math.round((N+M*j)*S)/S;if(y&&T>a)break;n.push({value:T})}return y&&h&&E!==a?n.length&&Ig(n[n.length-1].value,a,DF(a,w,e))?n[n.length-1].value=a:n.push({value:a}):(!y||E===a)&&n.push({value:E}),n}function DF(e,t,{horizontal:n,minRotation:r}){const s=Bi(r),o=(n?Math.sin(s):Math.cos(s))||.001,i=.75*t*(""+e).length;return Math.min(t/o,i)}class yw extends Nu{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 _t(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=l=>s=n?s:l,a=l=>o=r?o:l;if(t){const l=Pa(s),u=Pa(o);l<0&&u<0?a(0):l>0&&u>0&&i(0)}if(s===o){let l=o===0?1:Math.abs(o*.05);a(o+l),t||i(s-l)}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=jxe(s,o);return t.bounds==="ticks"&&NV(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 Bx(t,this.chart.options.locale,this.options.ticks.format)}}class tf extends yw{determineDataLimits(){const{min:t,max:n}=this.getMinMax(!0);this.min=br(t)?t:0,this.max=br(n)?n:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),n=t?this.width:this.height,r=Bi(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}}Ue(tf,"id","linear"),Ue(tf,"defaults",{ticks:{callback:xC.formatters.numeric}});const jb=e=>Math.floor(zc(e)),Hu=(e,t)=>Math.pow(10,jb(e)+t);function IF(e){return e/Math.pow(10,jb(e))===1}function RF(e,t,n){const r=Math.pow(10,n),s=Math.floor(e/r);return Math.ceil(t/r)-s}function Nxe(e,t){const n=t-e;let r=jb(n);for(;RF(e,t,r)>10;)r++;for(;RF(e,t,r)<10;)r--;return Math.min(r,jb(e))}function kxe(e,{min:t,max:n}){t=Io(e.min,t);const r=[],s=jb(t);let o=Nxe(t,n),i=o<0?Math.pow(10,Math.abs(o)):1;const a=Math.pow(10,o),l=s>o?Math.pow(10,s):0,u=Math.round((t-l)*i)/i,d=Math.floor((t-l)/a/10)*a*10;let f=Math.floor((u-d)/Math.pow(10,o)),h=Io(e.min,Math.round((l+d+f*Math.pow(10,o))*i)/i);for(;h<n;)r.push({value:h,major:IF(h),significand:f}),f>=10?f=f<15?15:20:f++,f>=20&&(o++,f=2,i=o>=0?1:i),h=Math.round((l+d+f*Math.pow(10,o))*i)/i;const m=Io(e.max,h);return r.push({value:m,major:IF(m),significand:f}),r}class dm extends Nu{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,n){const r=yw.prototype.parse.apply(this,[t,n]);if(r===0){this._zero=!0;return}return br(r)&&r>0?r:null}determineDataLimits(){const{min:t,max:n}=this.getMinMax(!0);this.min=br(t)?Math.max(0,t):null,this.max=br(n)?Math.max(0,n):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!br(this._userMin)&&(this.min=t===Hu(this.min,0)?Hu(this.min,-1):Hu(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(Hu(r,-1)),i(Hu(s,1)))),r<=0&&o(Hu(s,-1)),s<=0&&i(Hu(r,1)),this.min=r,this.max=s}buildTicks(){const t=this.options,n={min:this._userMin,max:this._userMax},r=kxe(n,this);return t.bounds==="ticks"&&NV(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":Bx(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=zc(t),this._valueRange=zc(this.max)-zc(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(zc(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const n=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+n*this._valueRange)}}Ue(dm,"id","logarithmic"),Ue(dm,"defaults",{ticks:{callback:xC.formatters.logarithmic,major:{enabled:!0}}});function dE(e){const t=e.ticks;if(t.display&&e.display){const n=bs(t.backdropPadding);return mt(t.font&&t.font.size,Qn.font.size)+n.height}return 0}function Exe(e,t,n){return n=Pn(n)?n:[n],{w:Ame(e,t.string,n),h:n.length*t.lineHeight}}function AF(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 _xe(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?hn/o:0;for(let l=0;l<o;l++){const u=i.setContext(e.getPointLabelContext(l));s[l]=u.padding;const d=e.getPointPosition(l,e.drawingArea+s[l],a),f=Un(u.font),h=Exe(e.ctx,f,e._pointLabels[l]);r[l]=h;const m=ks(e.getIndexAngle(l)+a),p=Math.round(GM(m)),g=AF(p,d.x,h.w,0,180),b=AF(p,d.y,h.h,90,270);Txe(n,t,m,g,b)}e.setCenterPoint(t.l-n.l,n.r-t.r,t.t-n.t,n.b-t.b),e._pointLabelItems=Ixe(e,r,s)}function Txe(e,t,n,r,s){const o=Math.abs(Math.sin(n)),i=Math.abs(Math.cos(n));let a=0,l=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?(l=(t.t-s.start)/i,e.t=Math.min(e.t,t.t-l)):s.end>t.b&&(l=(s.end-t.b)/i,e.b=Math.max(e.b,t.b+l))}function Mxe(e,t,n){const r=e.drawingArea,{extra:s,additionalAngle:o,padding:i,size:a}=n,l=e.getPointPosition(t,r+s+i,o),u=Math.round(GM(ks(l.angle+_r))),d=Pxe(l.y,a.h,u),f=Rxe(u),h=Axe(l.x,a.w,f);return{visible:!0,x:l.x,y:d,textAlign:f,left:h,top:d,right:h+a.w,bottom:d+a.h}}function Dxe(e,t){if(!t)return!0;const{left:n,top:r,right:s,bottom:o}=e;return!(Ml({x:n,y:r},t)||Ml({x:n,y:o},t)||Ml({x:s,y:r},t)||Ml({x:s,y:o},t))}function Ixe(e,t,n){const r=[],s=e._pointLabels.length,o=e.options,{centerPointLabels:i,display:a}=o.pointLabels,l={extra:dE(o)/2,additionalAngle:i?hn/s:0};let u;for(let d=0;d<s;d++){l.padding=n[d],l.size=t[d];const f=Mxe(e,d,l);r.push(f),a==="auto"&&(f.visible=Dxe(f,u),f.visible&&(u=f))}return r}function Rxe(e){return e===0||e===180?"center":e<180?"left":"right"}function Axe(e,t,n){return n==="right"?e-=t:n==="center"&&(e-=t/2),e}function Pxe(e,t,n){return n===90||n===270?e-=t/2:(n>270||n<90)&&(e-=t),e}function Oxe(e,t,n){const{left:r,top:s,right:o,bottom:i}=n,{backdropColor:a}=t;if(!_t(a)){const l=Bl(t.borderRadius),u=bs(t.backdropPadding);e.fillStyle=a;const d=r-u.left,f=s-u.top,h=o-r+u.width,m=i-s+u.height;Object.values(l).some(p=>p!==0)?(e.beginPath(),zl(e,{x:d,y:f,w:h,h:m,radius:l}),e.fill()):e.fillRect(d,f,h,m)}}function Fxe(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));Oxe(n,i,o);const a=Un(i.font),{x:l,y:u,textAlign:d}=o;ef(n,e._pointLabels[s],l,u+a.lineHeight/2,a,{color:i.color,textAlign:d,textBaseline:"middle"})}}function gH(e,t,n,r){const{ctx:s}=e;if(n)s.arc(e.xCenter,e.yCenter,t,0,Xn);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 $xe(e,t,n,r,s){const o=e.ctx,i=t.circular,{color:a,lineWidth:l}=t;!i&&!r||!a||!l||n<0||(o.save(),o.strokeStyle=a,o.lineWidth=l,o.setLineDash(s.dash||[]),o.lineDashOffset=s.dashOffset,o.beginPath(),gH(e,n,i,r),o.closePath(),o.stroke(),o.restore())}function Lxe(e,t,n){return ju(e,{label:n,index:t,type:"pointLabel"})}class cg extends yw{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=bs(dE(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=br(t)&&!isNaN(t)?t:0,this.max=br(n)&&!isNaN(n)?n:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/dE(this.options))}generateTickLabels(t){yw.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((n,r)=>{const s=In(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?_xe(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=Xn/(this._pointLabels.length||1),r=this.options.startAngle||0;return ks(t*n+Bi(r))}getDistanceFromCenterForValue(t){if(_t(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(_t(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 Lxe(this.getContext(),t,r)}}getPointPosition(t,n,r=0){const s=this.getIndexAngle(t)-_r+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(),gH(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,l,u;if(n.pointLabels.display&&Fxe(this,i),s.display&&this.ticks.forEach((d,f)=>{if(f!==0||f===0&&this.min<0){l=this.getDistanceFromCenterForValue(d.value);const h=this.getContext(f),m=s.setContext(h),p=o.setContext(h);$xe(this,m,l,i,p)}}),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,l=this.getDistanceFromCenterForValue(n.reverse?this.min:this.max),u=this.getPointPosition(a,l),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,l)=>{if(l===0&&this.min>=0&&!n.reverse)return;const u=r.setContext(this.getContext(l)),d=Un(u.font);if(o=this.getDistanceFromCenterForValue(this.ticks[l].value),u.showLabelBackdrop){t.font=d.string,i=t.measureText(a.label).width,t.fillStyle=u.backdropColor;const f=bs(u.backdropPadding);t.fillRect(-i/2-f.left,-o-d.size/2-f.top,i+f.width,d.size+f.height)}ef(t,a.label,0,-o,d,{color:u.color,strokeColor:u.textStrokeColor,strokeWidth:u.textStrokeWidth})}),t.restore()}drawTitle(){}}Ue(cg,"id","radialLinear"),Ue(cg,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:xC.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),Ue(cg,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),Ue(cg,"descriptors",{angleLines:{_fallback:"grid"}});const CC={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}},go=Object.keys(CC);function PF(e,t){return e-t}function OF(e,t){if(_t(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)),br(i)||(i=typeof r=="string"?n.parse(i,r):n.parse(i)),i===null?null:(s&&(i=s==="week"&&(Qd(o)||o===!0)?n.startOf(i,"isoWeek",o):n.startOf(i,s)),+i)}function FF(e,t,n,r){const s=go.length;for(let o=go.indexOf(e);o<s-1;++o){const i=CC[go[o]],a=i.steps?i.steps:Number.MAX_SAFE_INTEGER;if(i.common&&Math.ceil((n-t)/(a*i.size))<=r)return go[o]}return go[s-1]}function zxe(e,t,n,r,s){for(let o=go.length-1;o>=go.indexOf(n);o--){const i=go[o];if(CC[i].common&&e._adapter.diff(s,r,i)>=t-1)return i}return go[n?go.indexOf(n):0]}function Bxe(e){for(let t=go.indexOf(e)+1,n=go.length;t<n;++t)if(CC[go[t]].common)return go[t]}function $F(e,t,n){if(!n)e[t]=!0;else if(n.length){const{lo:r,hi:s}=KM(n,t),o=n[r]>=t?n[r]:n[s];e[o]=!0}}function Vxe(e,t,n,r){const s=e._adapter,o=+s.startOf(t[0].value,r),i=t[t.length-1].value;let a,l;for(a=o;a<=i;a=+s.add(a,1,r))l=n[a],l>=0&&(t[l].major=!0);return t}function LF(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:Vxe(e,r,s,n)}class Nb extends Nu{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 Xpe._date(t.adapters.date);s.init(n),Dg(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:OF(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 l(u){!i&&!isNaN(u.min)&&(s=Math.min(s,u.min)),!a&&!isNaN(u.max)&&(o=Math.max(o,u.max))}(!i||!a)&&(l(this._getLabelBounds()),(t.bounds!=="ticks"||t.ticks.source!=="labels")&&l(this.getMinMax(!1))),s=br(s)&&!isNaN(s)?s:+n.startOf(Date.now(),r),o=br(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=wme(s,o,i);return this._unit=n.unit||(r.autoSkip?FF(n.minUnit,this.min,this.max,this._getLabelCapacity(o)):zxe(this,a.length,n.minUnit,this.min,this.max)),this._majorUnit=!r.major.enabled||this._unit==="year"?void 0:Bxe(this._unit),this.initOffsets(s),t.reverse&&a.reverse(),LF(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=rs(n,0,i),r=rs(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||FF(o.minUnit,n,r,this._getLabelCapacity(n)),a=mt(s.ticks.stepSize,1),l=i==="week"?o.isoWeekday:!1,u=Qd(l)||l===!0,d={};let f=n,h,m;if(u&&(f=+t.startOf(f,"isoWeek",l)),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 p=s.ticks.source==="data"&&this.getDataTimestamps();for(h=f,m=0;h<r;h=+t.add(h,a,i),m++)$F(d,h,p);return(h===r||s.bounds==="ticks"||m===1)&&$F(d,h,p),Object.keys(d).sort(PF).map(g=>+g)}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 In(i,[t,n,r],this);const a=o.time.displayFormats,l=this._unit,u=this._majorUnit,d=l&&a[l],f=u&&a[u],h=r[n],m=u&&f&&h&&h.major;return this._adapter.format(t,s||(m?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=Bi(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,LF(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(OF(this,s[n]));return this._cache.labels=this._normalized?t:this.normalize(t)}normalize(t){return _V(t.sort(PF))}}Ue(Nb,"id","time"),Ue(Nb,"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 h0(e,t,n){let r=0,s=e.length-1,o,i,a,l;n?(t>=e[r].pos&&t<=e[s].pos&&({lo:r,hi:s}=Tl(e,"pos",t)),{pos:o,time:a}=e[r],{pos:i,time:l}=e[s]):(t>=e[r].time&&t<=e[s].time&&({lo:r,hi:s}=Tl(e,"time",t)),{time:o,pos:a}=e[r],{time:i,pos:l}=e[s]);const u=i-o;return u?a+(l-a)*(t-o)/u:a}class fE extends Nb{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=h0(n,this.min),this._tableRange=h0(n,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:n,max:r}=this,s=[],o=[];let i,a,l,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],l=s[i-1],u=s[i],Math.round((d+l)/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(h0(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const n=this._offsets,r=this.getDecimalForPixel(t)/n.factor-n.end;return h0(this._table,r*this._tableRange+this._minPos,!0)}}Ue(fE,"id","timeseries"),Ue(fE,"defaults",Nb.defaults);var Hxe=Object.freeze({__proto__:null,CategoryScale:Sb,LinearScale:tf,LogarithmicScale:dm,RadialLinearScale:cg,TimeScale:Nb,TimeSeriesScale:fE});const Uxe=[Zpe,kbe,vxe,Hxe];function Wxe(){return function(e){const t=Xt.defaults.plugins.legend.labels.generateLabels;return t(e).map(r=>(r.pointStyle="rect",r))}}function qxe(){return function(e){const t=e.data.datasets||[],n=Xt.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 Yxe(){return function(e){const t=Xt.defaults.plugins.legend.labels.generateLabels;return t(e).map(r=>(r.pointStyle="rect",r))}}function Gxe(){return function(e){const t=e.data.datasets||[],n=Xt.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 aD(e,t,n){var h,m,p;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||""),l=o.includes(n||""),u=i.includes(n||""),d=n==="combo",f={...(m=(h=e.plugins)==null?void 0:h.legend)==null?void 0:m.labels};return d?(f.usePointStyle=!0,f.generateLabels=Gxe()):l?(f.usePointStyle=!0,f.generateLabels=Wxe()):a?(f.usePointStyle=!0,f.generateLabels=qxe()):u&&(f.usePointStyle=!0,f.generateLabels=Yxe()),{...e,plugins:{...e.plugins,legend:{...(p=e.plugins)==null?void 0:p.legend,...r,labels:f}}}}function bH(e){return!["kpi","metric","text","table","pivotTable","treemap"].includes(e)}function lD(e){if(bH(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 xH(e,t){return{...e,...t}}function Kxe(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 Zxe(e,t){return(t==null?void 0:t.enabled)!==void 0?t.enabled:(t==null?void 0:t.display)==="auto"?e<=30:!1}function zF(e,t,n,r){return function(s){var o,i;if(s==null)return"";if(r==="range"&&Array.isArray(s)){const a=(e==null?void 0:e.formatOptions)||(t==null?void 0:t.formatOptions)||{},l=(e==null?void 0:e.format)==="auto"?(o=t==null?void 0:t.formatOptions)==null?void 0:o.type:e==null?void 0:e.format;return s.slice(0,2).map(d=>l&&l!=="auto"&&l!=="none"?Er(Number(d),l,a):d).join(" - ")}return(e==null?void 0:e.format)==="none"?s:!(e!=null&&e.format)||e.format==="auto"?(i=t==null?void 0:t.formatOptions)!=null&&i.type&&t.formatOptions.type!=="auto"?Er(Number(s),t.formatOptions.type,t.formatOptions||{}):n?n(s):s:Er(Number(s),e.format,e.formatOptions||{})}}function m0(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";if(o){const l=Hi();return wo(l)}if(i||a){const l=Hi();return wo(l)}return l=>{var d,f,h;const u=((f=(d=l.dataset)==null?void 0:d.backgroundColor)==null?void 0:f[l.dataIndex])||((h=l.dataset)==null?void 0:h.backgroundColor)||t||Hi();return wo(u)}}function Zm(e,t,n,r){var _,k,M,T,P,O,I,$,V,W,L,R,z,F,A,H,B,Y;const s=(k=(_=n==null?void 0:n.chartOptions)==null?void 0:_.plugins)==null?void 0:k.datalabels,o=(s==null?void 0:s.display)!==!1&&((s==null?void 0:s.anchor)||(s==null?void 0:s.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&&o)return e;if(!t)return{...e,plugins:{...e.plugins,datalabels:{display:!1}}};const a=r||e.type||"bar",l=a==="bubble"||a==="scatter",u=((M=n==null?void 0:n.chartOptions)==null?void 0:M.indexAxis)||(e==null?void 0:e.indexAxis)||"x",d=u==="y"?"x":"y",f=u==="y"?"y":"x",h=((P=(T=e.scales)==null?void 0:T[d])==null?void 0:P.stacked)===!0||a==="stackedBar"||a==="stackedLine"||a==="stackedArea"||a==="bar"&&((I=(O=e.scales)==null?void 0:O[f])==null?void 0:I.stacked)===!0&&((V=($=e.scales)==null?void 0:$[d])==null?void 0:V.stacked)===!0,m=a==="stackedBar"||a==="bar"&&((L=(W=e.scales)==null?void 0:W[f])==null?void 0:L.stacked)===!0&&((z=(R=e.scales)==null?void 0:R[d])==null?void 0:z.stacked)===!0,p=u==="y",g=p?n==null?void 0:n.xAxisConfig:n==null?void 0:n.yAxisConfig,b=Kxe(a,p,t.showTotal),x=m&&!t.showTotal?"center":t.anchor||b.anchor,y=m&&!t.showTotal?"center":t.align||b.align;let v=x,w=y;const j=a==="pie"||a==="doughnut"||a==="polarArea"||a==="funnel";m&&!t.showTotal&&(v="center",w="center");const S=l?"start":v,N=l?"center":w,E={display:t.display!==!1,anchor:l?"start":v,align:l?"center":w,clamp:t.clamp??!0,clip:t.clip??!1,offset:t.offset??0,formatter:l?(q,U)=>{var le,de,ce,Ce,ge;const G=(U==null?void 0:U.raw)||q,Z=(G==null?void 0:G.label)??((le=G==null?void 0:G.meta)==null?void 0:le.label)??((Ce=G==null?void 0:G.meta)==null?void 0:Ce[(ce=(de=U==null?void 0:U.chart)==null?void 0:de.data)==null?void 0:ce.labelKey])??((ge=G==null?void 0:G.meta)==null?void 0:ge.labelKey);if(Z!=null&&Z!=="")return Z;const Q=(typeof(G==null?void 0:G.y)=="number"?G==null?void 0:G.y:Number(G==null?void 0:G.y))??(typeof(G==null?void 0:G.x)=="number"?G==null?void 0:G.x:Number(G==null?void 0:G.x))??Number(q);if(!Number.isFinite(Q))return"";const K=t.format;return K==="none"?Q:Er(Q,!K||K==="auto"?"number":K,t.formatOptions||{})}:zF(t,g,(A=(F=e.plugins)==null?void 0:F.datalabels)==null?void 0:A.formatter,a),color:m0(t,void 0,S,N),font:{size:((H=t.font)==null?void 0:H.size)||12,weight:((B=t.font)==null?void 0:B.weight)||"normal"},rotation:t.rotation||0};if(j&&a!=="funnel"&&(delete E.anchor,delete E.align,Object.assign(E,{anchor:"center",align:"center",offset:0,clamp:!0,clip:!1,display:function(q){if(t.display===!1)return!1;const U=q.dataset.data[q.dataIndex],G=q.dataset.data.reduce((Q,K)=>Q+K,0);return U/G*100>5}})),a==="funnel"&&t.enabled&&(Object.assign(E,{display:function(q){var G;if(t.display===!1)return!1;const U=(((G=n==null?void 0:n.funnelConfig)==null?void 0:G.labelThreshold)??0)/100;if(U>0){const Z=q.dataset.data,Q=Z[q.dataIndex],K=Z.reduce((le,de)=>le+de,0);return(K>0?Q/K:0)>=U}return!0},anchor:function(q){return q.dataset.data[q.dataIndex]<.02?"end":"start"},align:function(q){return q.dataset.data[q.dataIndex]<.02?"end":"center"},textAlign:"center",offset:0,clamp:!0,clip:!1}),E.font||(E.font={}),E.font.size=E.font.size||14),h&&t.showTotal&&(E.display=function(q){const U=q.chart.data.datasets.length;return q.datasetIndex===U-1},E.formatter=function(q,U){var K,te;let G=0;const Z=U.dataIndex;return U.chart.data.datasets.forEach(le=>{const de=le.data[Z];de&&!isNaN(de)&&(G+=Number(de))}),zF(t,g,(te=(K=e.plugins)==null?void 0:K.datalabels)==null?void 0:te.formatter,a)(G)},E.anchor="end",E.align=p?"right":"top",E.color=m0(t,void 0,"end",p?"right":"top")),!m&&!j&&t.position&&t.position!=="auto"&&t.position!=="custom"){if(p)switch(t.position){case"left":E.anchor="start",E.align="left";break;case"right":E.anchor="end",E.align="right";break;case"center":E.anchor="center",E.align="center";break;case"top":case"bottom":E.anchor="center",E.align="center";break}else switch(t.position){case"top":E.anchor="end",E.align="top";break;case"bottom":E.anchor="start",E.align="bottom";break;case"center":E.anchor="center",E.align="center";break;case"left":case"right":E.anchor="center",E.align="center";break}E.color=m0(t,void 0,E.anchor,E.align)}else t.position==="custom"&&(E.color=m0(t,void 0,E.anchor,E.align));return j||a==="funnel"?{...e,plugins:{...e.plugins,datalabels:E}}:{...e,plugins:{...e.plugins,datalabels:{...(Y=e.plugins)==null?void 0:Y.datalabels,...E}}}}function yH(e){return!["kpi","metric","text","table","pivotTable","custom"].includes(e)}function Vx(e,t){var n,r,s,o;if(yH(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,l=(((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:l}}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 Xxe(e){return e.length===1?[e[0]]:e.slice(1).filter(n=>!xT.includes(n))}function Kj({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var w;const i=s==="radar"?.2:1,{keys:a}=zn(e),l=Xxe(a);let u="none";s=="bar"?u="bar":s=="line"&&(u="line");const d=a==null?void 0:a[0],f=nc(e,d),m=Gm(l,e,r,i,u,d,s==="stackedBar"||s==="stackedLine",Ym(e)),p=ta(m,n),{options:g,plugins:b}=ou({cardType:s,cfg:t,preferences:r,customCfg:n,card:o}),x=((w=o.interactionConfig)==null?void 0:w.interactions)&&o.interactionConfig.interactions.length>0,y=function(j,S){var E;const N=((E=j.native)==null?void 0:E.target)||j.target;S.length?N.style.cursor="pointer":N.style.cursor="default"};return{type:(n==null?void 0:n.type)||(t==null?void 0:t.type)||"bar",data:{labels:f,datasets:p},options:{...g,onHover:x?y:void 0},plugins:b}}function Qxe(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 Jxe(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 vH(e,t){var i,a,l,u,d,f,h,m,p,g,b,x;const n=Qxe(t,e),r=Jxe(t);return(t==null?void 0:t.xAxisConfig)||(t==null?void 0:t.yAxisConfig)?(e==null?void 0:e.options)||{}:{...e==null?void 0:e.options,scales:{...(i=e==null?void 0:e.options)==null?void 0:i.scales,[n]:{...(l=(a=e==null?void 0:e.options)==null?void 0:a.scales)==null?void 0:l[n],ticks:{...(f=(d=(u=e==null?void 0:e.options)==null?void 0:u.scales)==null?void 0:d[n])==null?void 0:f.ticks,callback:y=>{var v,w,j,S;return Xk({number:Number(y),decimalPlaces:((v=t==null?void 0:t.numberAxisFormat)==null?void 0:v.decimalPlaces)||0,useSuffix:!!((w=t==null?void 0:t.numberAxisFormat)!=null&&w.suffix),customSuffix:"",locale:((j=t==null?void 0:t.numberAxisFormat)==null?void 0:j.locale)||"",currency:((S=t==null?void 0:t.numberAxisFormat)==null?void 0:S.currency)||""})}}},[r]:{...(p=(m=(h=e==null?void 0:e.options)==null?void 0:h.scales)==null?void 0:m[r])==null?void 0:p.ticks,callback:null}},plugins:{...(g=e==null?void 0:e.options)==null?void 0:g.plugins,datalabels:{...(x=(b=e==null?void 0:e.options)==null?void 0:b.plugins)==null?void 0:x.datalabels,formatter:function(y){var v,w,j,S;return Xk({number:Number(y),decimalPlaces:((v=t==null?void 0:t.numberAxisFormat)==null?void 0:v.decimalPlaces)||0,useSuffix:!!((w=t==null?void 0:t.numberAxisFormat)!=null&&w.suffix),customSuffix:"",locale:((j=t==null?void 0:t.numberAxisFormat)==null?void 0:j.locale)||"",currency:((S=t==null?void 0:t.numberAxisFormat)==null?void 0:S.currency)||""})}}}}}function ou({cardType:e,cfg:t,preferences:n,customCfg:r,card:s}){var g,b,x,y,v,w,j,S,N,E,_,k,M,T,P,O,I,$,V,W,L,R,z,F,A,H,B,Y,q,U,G,Z,Q,K,te;const o=J.getState().themeStyle,i=vH(t,n),a=jr((t==null?void 0:t.options)||{},n==null?void 0:n.chartOptions),l=jr(i,a),u=jr(l,(r==null?void 0:r.options)||{}),d=eye(e,n,u,s),f={...u,scales:{...u==null?void 0:u.scales,x:{...(g=u==null?void 0:u.scales)==null?void 0:g.x,grid:{...(x=(b=u==null?void 0:u.scales)==null?void 0:b.x)==null?void 0:x.grid,color:(S=(j=(w=(v=(y=o==null?void 0:o.chart)==null?void 0:y.options)==null?void 0:v.scales)==null?void 0:w.x)==null?void 0:j.grid)==null?void 0:S.color}},y:{...(N=u==null?void 0:u.scales)==null?void 0:N.y,grid:{...(_=(E=u==null?void 0:u.scales)==null?void 0:E.y)==null?void 0:_.grid,color:(O=(P=(T=(M=(k=o==null?void 0:o.chart)==null?void 0:k.options)==null?void 0:M.scales)==null?void 0:T.y)==null?void 0:P.grid)==null?void 0:O.color}}},plugins:{...u==null?void 0:u.plugins,tooltip:{filter:function(le){return le.raw!==void 0&&le.raw!==null&&le.raw!==0},footerColor:((W=(V=($=(I=o==null?void 0:o.chart)==null?void 0:I.options)==null?void 0:$.plugins)==null?void 0:V.tooltip)==null?void 0:W.footerColor)||"#999",footerFont:{size:11,weight:"normal"},footerMarginTop:6,callbacks:d,...(L=u==null?void 0:u.plugins)==null?void 0:L.tooltip,backgroundColor:(A=(F=(z=(R=o==null?void 0:o.chart)==null?void 0:R.options)==null?void 0:z.plugins)==null?void 0:F.tooltip)==null?void 0:A.backgroundColor,bodyColor:(q=(Y=(B=(H=o==null?void 0:o.chart)==null?void 0:H.options)==null?void 0:B.plugins)==null?void 0:Y.tooltip)==null?void 0:q.bodyColor,titleColor:(Q=(Z=(G=(U=o==null?void 0:o.chart)==null?void 0:U.options)==null?void 0:G.plugins)==null?void 0:Z.tooltip)==null?void 0:Q.titleColor}}},{plugins:h,options:m}=Cu((n==null?void 0:n.customVisualCode)||"");let p=Km.applyAxisConfig(f,e||"bar",n);return p=aD(p,(te=(K=n==null?void 0:n.chartOptions)==null?void 0:K.plugins)==null?void 0:te.legend,e),p=Zm(p,n==null?void 0:n.dataLabelsConfig,n,e),p=jr(p,m),{options:p,plugins:h}}function eye(e,t,n,r){var l,u,d,f,h,m,p;if(e==="map")return{};const o=((l=t==null?void 0:t.chartOptions)==null?void 0:l.indexAxis)==="y"?t==null?void 0:t.xAxisConfig:t==null?void 0:t.yAxisConfig,i=(g,b)=>{var y,v,w,j,S;const x=b==="y2"?t==null?void 0:t.secondaryYAxisConfig:o;return(y=x==null?void 0:x.formatOptions)!=null&&y.type&&x.formatOptions.type!=="auto"?Er(g,x.formatOptions.type,x.formatOptions||{}):Xk({number:g,decimalPlaces:((v=t==null?void 0:t.numberAxisFormat)==null?void 0:v.decimalPlaces)||0,useSuffix:!!((w=t==null?void 0:t.numberAxisFormat)!=null&&w.suffix),customSuffix:"",locale:((j=t==null?void 0:t.numberAxisFormat)==null?void 0:j.locale)||"",currency:((S=t==null?void 0:t.numberAxisFormat)==null?void 0:S.currency)||""})},a=(((d=(u=r==null?void 0:r.interactionConfig)==null?void 0:u.drillHierarchies)==null?void 0:d.length)??0)>0||(((h=(f=r==null?void 0:r.interactionConfig)==null?void 0:f.interactions)==null?void 0:h.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,j)=>{const S=j.raw;return S!==void 0&&S!==0?w+S:w},0),v=i(y);return`${b} (${v})`}return b},label:function(g){var w,j;const b=((w=g==null?void 0:g.dataset)==null?void 0:w.label)||"",x=g==null?void 0:g.raw;if(x===void 0||x===0)return;const y=(j=g==null?void 0:g.dataset)==null?void 0:j.yAxisID,v=i(Number(x),y);return`${b}: ${v}`},footer:function(g){return a?["─────────────────","Click to drill"]:[]},...((p=(m=n==null?void 0:n.plugins)==null?void 0:m.tooltip)==null?void 0:p.callbacks)||{}}}class iu{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*tye(e){for(const t of e)yield*t}function wH(e){return Array.from(tye(e))}function hh(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,cD=1e-12,Bt=Math.PI,gr=Bt/2,BF=Bt/4,Wo=Bt*2,Ys=180/Bt,Rn=Bt/180,fn=Math.abs,Xm=Math.atan,Ua=Math.atan2,Et=Math.cos,p0=Math.ceil,CH=Math.exp,vw=Math.log,Zj=Math.pow,wt=Math.sin,ui=Math.sign||function(e){return e>0?1:e<0?-1:0},no=Math.sqrt,uD=Math.tan;function SH(e){return e>1?0:e<-1?Bt:Math.acos(e)}function gi(e){return e>1?gr:e<-1?-gr:Math.asin(e)}function es(){}function ww(e,t){e&&HF.hasOwnProperty(e.type)&&HF[e.type](e,t)}var VF={Feature:function(e,t){ww(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,s=n.length;++r<s;)ww(n[r].geometry,t)}},HF={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){hE(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)hE(n[r],t,0)},Polygon:function(e,t){UF(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)UF(n[r],t)},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,s=n.length;++r<s;)ww(n[r],t)}};function hE(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 UF(e,t){var n=-1,r=e.length;for(t.polygonStart();++n<r;)hE(e[n],t,1);t.polygonEnd()}function nd(e,t){e&&VF.hasOwnProperty(e.type)?VF[e.type](e,t):ww(e,t)}function mE(e){return[Ua(e[1],e[0]),gi(e[2])]}function fm(e){var t=e[0],n=e[1],r=Et(n);return[r*Et(t),r*wt(t),wt(n)]}function g0(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function Cw(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 Xj(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function b0(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function pE(e){var t=no(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function gE(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 bE(e,t){return fn(e)>Bt&&(e-=Math.round(e/Wo)*Wo),[e,t]}bE.invert=bE;function jH(e,t,n){return(e%=Wo)?t||n?gE(qF(e),YF(t,n)):qF(e):t||n?YF(t,n):bE}function WF(e){return function(t,n){return t+=e,fn(t)>Bt&&(t-=Math.round(t/Wo)*Wo),[t,n]}}function qF(e){var t=WF(e);return t.invert=WF(-e),t}function YF(e,t){var n=Et(e),r=wt(e),s=Et(t),o=wt(t);function i(a,l){var u=Et(l),d=Et(a)*u,f=wt(a)*u,h=wt(l),m=h*n+d*r;return[Ua(f*s-m*o,d*n-h*r),gi(m*s+f*o)]}return i.invert=function(a,l){var u=Et(l),d=Et(a)*u,f=wt(a)*u,h=wt(l),m=h*s-f*o;return[Ua(f*s+h*o,d*n+m*r),gi(m*n-d*r)]},i}function nye(e){e=jH(e[0]*Rn,e[1]*Rn,e.length>2?e[2]*Rn:0);function t(n){return n=e(n[0]*Rn,n[1]*Rn),n[0]*=Ys,n[1]*=Ys,n}return t.invert=function(n){return n=e.invert(n[0]*Rn,n[1]*Rn),n[0]*=Ys,n[1]*=Ys,n},t}function rye(e,t,n,r,s,o){if(n){var i=Et(t),a=wt(t),l=r*n;s==null?(s=t+r*Wo,o=t-l/2):(s=GF(i,s),o=GF(i,o),(r>0?s<o:s>o)&&(s+=r*Wo));for(var u,d=s;r>0?d>o:d<o;d-=l)u=mE([i,-a*Et(d),-a*wt(d)]),e.point(u[0],u[1])}}function GF(e,t){t=fm(t),t[0]-=e,pE(t);var n=SH(-t[1]);return((-t[2]<0?-n:n)+Wo-xt)%Wo}function NH(){var e=[],t;return{point:function(n,r,s){t.push([n,r,s])},lineStart:function(){e.push(t=[])},lineEnd:es,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Tv(e,t){return fn(e[0]-t[0])<xt&&fn(e[1]-t[1])<xt}function x0(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 kH(e,t,n,r,s){var o=[],i=[],a,l;if(e.forEach(function(p){if(!((g=p.length-1)<=0)){var g,b=p[0],x=p[g],y;if(Tv(b,x)){if(!b[2]&&!x[2]){for(s.lineStart(),a=0;a<g;++a)s.point((b=p[a])[0],b[1]);s.lineEnd();return}x[0]+=2*xt}o.push(y=new x0(b,p,null,!0)),i.push(y.o=new x0(b,null,y,!1)),o.push(y=new x0(x,p,null,!1)),i.push(y.o=new x0(x,null,y,!0))}}),!!o.length){for(i.sort(t),KF(o),KF(i),a=0,l=i.length;a<l;++a)i[a].e=n=!n;for(var u=o[0],d,f;;){for(var h=u,m=!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(m)for(a=0,l=d.length;a<l;++a)s.point((f=d[a])[0],f[1]);else r(h.x,h.n.x,1,s);h=h.n}else{if(m)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,m=!m}while(!h.v);s.lineEnd()}}}function KF(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 Qj(e){return fn(e[0])<=Bt?e[0]:ui(e[0])*((fn(e[0])+Bt)%Wo-Bt)}function EH(e,t){var n=Qj(t),r=t[1],s=wt(r),o=[wt(n),-Et(n),0],i=0,a=0,l=new iu;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,m=f[h-1],p=Qj(m),g=m[1]/2+BF,b=wt(g),x=Et(g),y=0;y<h;++y,p=w,b=S,x=N,m=v){var v=f[y],w=Qj(v),j=v[1]/2+BF,S=wt(j),N=Et(j),E=w-p,_=E>=0?1:-1,k=_*E,M=k>Bt,T=b*S;if(l.add(Ua(T*_*wt(k),x*N+T*Et(k))),i+=M?E+_*Wo:E,M^p>=n^w>=n){var P=Cw(fm(m),fm(v));pE(P);var O=Cw(o,P);pE(O);var I=(M^E>=0?-1:1)*gi(O[2]);(r>I||r===I&&(P[0]||P[1]))&&(a+=M^E>=0?1:-1)}}return(i<-xt||i<xt&&l<-cD)^a&1}function _H(e,t,n,r){return function(s){var o=t(s),i=NH(),a=t(i),l=!1,u,d,f,h={point:m,lineStart:g,lineEnd:b,polygonStart:function(){h.point=x,h.lineStart=y,h.lineEnd=v,d=[],u=[]},polygonEnd:function(){h.point=m,h.lineStart=g,h.lineEnd=b,d=wH(d);var w=EH(u,r);d.length?(l||(s.polygonStart(),l=!0),kH(d,oye,w,n,s)):w&&(l||(s.polygonStart(),l=!0),s.lineStart(),n(null,null,1,s),s.lineEnd()),l&&(s.polygonEnd(),l=!1),d=u=null},sphere:function(){s.polygonStart(),s.lineStart(),n(null,null,1,s),s.lineEnd(),s.polygonEnd()}};function m(w,j){e(w,j)&&s.point(w,j)}function p(w,j){o.point(w,j)}function g(){h.point=p,o.lineStart()}function b(){h.point=m,o.lineEnd()}function x(w,j){f.push([w,j]),a.point(w,j)}function y(){a.lineStart(),f=[]}function v(){x(f[0][0],f[0][1]),a.lineEnd();var w=a.clean(),j=i.result(),S,N=j.length,E,_,k;if(f.pop(),u.push(f),f=null,!!N){if(w&1){if(_=j[0],(E=_.length-1)>0){for(l||(s.polygonStart(),l=!0),s.lineStart(),S=0;S<E;++S)s.point((k=_[S])[0],k[1]);s.lineEnd()}return}N>1&&w&2&&j.push(j.pop().concat(j.shift())),d.push(j.filter(sye))}}return h}}function sye(e){return e.length>1}function oye(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 ZF=_H(function(){return!0},iye,lye,[-Bt,-gr]);function iye(e){var t=NaN,n=NaN,r=NaN,s;return{lineStart:function(){e.lineStart(),s=1},point:function(o,i){var a=o>0?Bt:-Bt,l=fn(o-t);fn(l-Bt)<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&&l>=Bt&&(fn(t-r)<xt&&(t-=r*xt),fn(o-a)<xt&&(o-=a*xt),n=aye(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 aye(e,t,n,r){var s,o,i=wt(e-n);return fn(i)>xt?Xm((wt(t)*(o=Et(r))*wt(n)-wt(r)*(s=Et(t))*wt(e))/(s*o*i)):(t+r)/2}function lye(e,t,n,r){var s;if(e==null)s=n*gr,r.point(-Bt,s),r.point(0,s),r.point(Bt,s),r.point(Bt,0),r.point(Bt,-s),r.point(0,-s),r.point(-Bt,-s),r.point(-Bt,0),r.point(-Bt,s);else if(fn(e[0]-t[0])>xt){var o=e[0]<t[0]?Bt:-Bt;s=n*o/2,r.point(-o,s),r.point(0,s),r.point(o,s)}else r.point(t[0],t[1])}function cye(e){var t=Et(e),n=2*Rn,r=t>0,s=fn(t)>xt;function o(d,f,h,m){rye(m,e,n,h,d,f)}function i(d,f){return Et(d)*Et(f)>t}function a(d){var f,h,m,p,g;return{lineStart:function(){p=m=!1,g=1},point:function(b,x){var y=[b,x],v,w=i(b,x),j=r?w?0:u(b,x):w?u(b+(b<0?Bt:-Bt),x):0;if(!f&&(p=m=w)&&d.lineStart(),w!==m&&(v=l(f,y),(!v||Tv(f,v)||Tv(y,v))&&(y[2]=1)),w!==m)g=0,w?(d.lineStart(),v=l(y,f),d.point(v[0],v[1])):(v=l(f,y),d.point(v[0],v[1],2),d.lineEnd()),f=v;else if(s&&f&&r^w){var S;!(j&h)&&(S=l(y,f,!0))&&(g=0,r?(d.lineStart(),d.point(S[0][0],S[0][1]),d.point(S[1][0],S[1][1]),d.lineEnd()):(d.point(S[1][0],S[1][1]),d.lineEnd(),d.lineStart(),d.point(S[0][0],S[0][1],3)))}w&&(!f||!Tv(f,y))&&d.point(y[0],y[1]),f=y,m=w,h=j},lineEnd:function(){m&&d.lineEnd(),f=null},clean:function(){return g|(p&&m)<<1}}}function l(d,f,h){var m=fm(d),p=fm(f),g=[1,0,0],b=Cw(m,p),x=g0(b,b),y=b[0],v=x-y*y;if(!v)return!h&&d;var w=t*x/v,j=-t*y/v,S=Cw(g,b),N=b0(g,w),E=b0(b,j);Xj(N,E);var _=S,k=g0(N,_),M=g0(_,_),T=k*k-M*(g0(N,N)-1);if(!(T<0)){var P=no(T),O=b0(_,(-k-P)/M);if(Xj(O,N),O=mE(O),!h)return O;var I=d[0],$=f[0],V=d[1],W=f[1],L;$<I&&(L=I,I=$,$=L);var R=$-I,z=fn(R-Bt)<xt,F=z||R<xt;if(!z&&W<V&&(L=V,V=W,W=L),F?z?V+W>0^O[1]<(fn(O[0]-I)<xt?V:W):V<=O[1]&&O[1]<=W:R>Bt^(I<=O[0]&&O[0]<=$)){var A=b0(_,(-k+P)/M);return Xj(A,N),[O,mE(A)]}}}function u(d,f){var h=r?e:Bt-e,m=0;return d<-h?m|=1:d>h&&(m|=2),f<-h?m|=4:f>h&&(m|=8),m}return _H(i,a,o,r?[0,-e]:[-Bt,e-Bt])}function uye(e,t,n,r,s,o){var i=e[0],a=e[1],l=t[0],u=t[1],d=0,f=1,h=l-i,m=u-a,p;if(p=n-i,!(!h&&p>0)){if(p/=h,h<0){if(p<d)return;p<f&&(f=p)}else if(h>0){if(p>f)return;p>d&&(d=p)}if(p=s-i,!(!h&&p<0)){if(p/=h,h<0){if(p>f)return;p>d&&(d=p)}else if(h>0){if(p<d)return;p<f&&(f=p)}if(p=r-a,!(!m&&p>0)){if(p/=m,m<0){if(p<d)return;p<f&&(f=p)}else if(m>0){if(p>f)return;p>d&&(d=p)}if(p=o-a,!(!m&&p<0)){if(p/=m,m<0){if(p>f)return;p>d&&(d=p)}else if(m>0){if(p<d)return;p<f&&(f=p)}return d>0&&(e[0]=i+d*h,e[1]=a+d*m),f<1&&(t[0]=i+f*h,t[1]=a+f*m),!0}}}}}var ug=1e9,y0=-ug;function dye(e,t,n,r){function s(u,d){return e<=u&&u<=n&&t<=d&&d<=r}function o(u,d,f,h){var m=0,p=0;if(u==null||(m=i(u,f))!==(p=i(d,f))||l(u,d)<0^f>0)do h.point(m===0||m===3?e:n,m>1?r:t);while((m=(m+f+4)%4)!==p);else h.point(d[0],d[1])}function i(u,d){return fn(u[0]-e)<xt?d>0?0:3:fn(u[0]-n)<xt?d>0?2:1:fn(u[1]-t)<xt?d>0?1:0:d>0?3:2}function a(u,d){return l(u.x,d.x)}function l(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=NH(),h,m,p,g,b,x,y,v,w,j,S,N={point:E,lineStart:T,lineEnd:P,polygonStart:k,polygonEnd:M};function E(I,$){s(I,$)&&d.point(I,$)}function _(){for(var I=0,$=0,V=m.length;$<V;++$)for(var W=m[$],L=1,R=W.length,z=W[0],F,A,H=z[0],B=z[1];L<R;++L)F=H,A=B,z=W[L],H=z[0],B=z[1],A<=r?B>r&&(H-F)*(r-A)>(B-A)*(e-F)&&++I:B<=r&&(H-F)*(r-A)<(B-A)*(e-F)&&--I;return I}function k(){d=f,h=[],m=[],S=!0}function M(){var I=_(),$=S&&I,V=(h=wH(h)).length;($||V)&&(u.polygonStart(),$&&(u.lineStart(),o(null,null,1,u),u.lineEnd()),V&&kH(h,a,I,o,u),u.polygonEnd()),d=u,h=m=p=null}function T(){N.point=O,m&&m.push(p=[]),j=!0,w=!1,y=v=NaN}function P(){h&&(O(g,b),x&&w&&f.rejoin(),h.push(f.result())),N.point=E,w&&d.lineEnd()}function O(I,$){var V=s(I,$);if(m&&p.push([I,$]),j)g=I,b=$,x=V,j=!1,V&&(d.lineStart(),d.point(I,$));else if(V&&w)d.point(I,$);else{var W=[y=Math.max(y0,Math.min(ug,y)),v=Math.max(y0,Math.min(ug,v))],L=[I=Math.max(y0,Math.min(ug,I)),$=Math.max(y0,Math.min(ug,$))];uye(W,L,e,t,n,r)?(w||(d.lineStart(),d.point(W[0],W[1])),d.point(L[0],L[1]),V||d.lineEnd(),S=!1):V&&(d.lineStart(),d.point(I,$),S=!1)}y=I,v=$,w=V}return N}}var xE,yE,Mv,Dv,hm={sphere:es,point:es,lineStart:fye,lineEnd:es,polygonStart:es,polygonEnd:es};function fye(){hm.point=mye,hm.lineEnd=hye}function hye(){hm.point=hm.lineEnd=es}function mye(e,t){e*=Rn,t*=Rn,yE=e,Mv=wt(t),Dv=Et(t),hm.point=pye}function pye(e,t){e*=Rn,t*=Rn;var n=wt(t),r=Et(t),s=fn(e-yE),o=Et(s),i=wt(s),a=r*i,l=Dv*n-Mv*r*o,u=Mv*n+Dv*r*o;xE.add(Ua(no(a*a+l*l),u)),yE=e,Mv=n,Dv=r}function gye(e){return xE=new iu,nd(e,hm),+xE}var vE=[null,null],bye={type:"LineString",coordinates:vE};function wE(e,t){return vE[0]=e,vE[1]=t,gye(bye)}var XF={Feature:function(e,t){return Sw(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,s=n.length;++r<s;)if(Sw(n[r].geometry,t))return!0;return!1}},QF={Sphere:function(){return!0},Point:function(e,t){return JF(e.coordinates,t)},MultiPoint:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(JF(n[r],t))return!0;return!1},LineString:function(e,t){return e5(e.coordinates,t)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(e5(n[r],t))return!0;return!1},Polygon:function(e,t){return t5(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(t5(n[r],t))return!0;return!1},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,s=n.length;++r<s;)if(Sw(n[r],t))return!0;return!1}};function Sw(e,t){return e&&QF.hasOwnProperty(e.type)?QF[e.type](e,t):!1}function JF(e,t){return wE(e,t)===0}function e5(e,t){for(var n,r,s,o=0,i=e.length;o<i;o++){if(r=wE(e[o],t),r===0||o>0&&(s=wE(e[o],e[o-1]),s>0&&n<=s&&r<=s&&(n+r-s)*(1-Math.pow((n-r)/s,2))<cD*s))return!0;n=r}return!1}function t5(e,t){return!!EH(e.map(xye),TH(t))}function xye(e){return e=e.map(TH),e.pop(),e}function TH(e){return[e[0]*Rn,e[1]*Rn]}function yye(e,t){return(e&&XF.hasOwnProperty(e.type)?XF[e.type]:Sw)(e,t)}function n5(e,t,n){var r=hh(e,t-xt,n).concat(t);return function(s){return r.map(function(o){return[s,o]})}}function r5(e,t,n){var r=hh(e,t-xt,n).concat(t);return function(s){return r.map(function(o){return[o,s]})}}function MH(){var e,t,n,r,s,o,i,a,l=10,u=l,d=90,f=360,h,m,p,g,b=2.5;function x(){return{type:"MultiLineString",coordinates:y()}}function y(){return hh(p0(r/d)*d,n,d).map(p).concat(hh(p0(a/f)*f,i,f).map(g)).concat(hh(p0(t/l)*l,e,l).filter(function(v){return fn(v%d)>xt}).map(h)).concat(hh(p0(o/u)*u,s,u).filter(function(v){return fn(v%f)>xt}).map(m))}return x.lines=function(){return y().map(function(v){return{type:"LineString",coordinates:v}})},x.outline=function(){return{type:"Polygon",coordinates:[p(r).concat(g(i).slice(1),p(n).reverse().slice(1),g(a).reverse().slice(1))]}},x.extent=function(v){return arguments.length?x.extentMajor(v).extentMinor(v):x.extentMinor()},x.extentMajor=function(v){return arguments.length?(r=+v[0][0],n=+v[1][0],a=+v[0][1],i=+v[1][1],r>n&&(v=r,r=n,n=v),a>i&&(v=a,a=i,i=v),x.precision(b)):[[r,a],[n,i]]},x.extentMinor=function(v){return arguments.length?(t=+v[0][0],e=+v[1][0],o=+v[0][1],s=+v[1][1],t>e&&(v=t,t=e,e=v),o>s&&(v=o,o=s,s=v),x.precision(b)):[[t,o],[e,s]]},x.step=function(v){return arguments.length?x.stepMajor(v).stepMinor(v):x.stepMinor()},x.stepMajor=function(v){return arguments.length?(d=+v[0],f=+v[1],x):[d,f]},x.stepMinor=function(v){return arguments.length?(l=+v[0],u=+v[1],x):[l,u]},x.precision=function(v){return arguments.length?(b=+v,h=n5(o,s,90),m=r5(t,e,b),p=n5(a,i,90),g=r5(r,n,b),x):b},x.extentMajor([[-180,-90+xt],[180,90-xt]]).extentMinor([[-180,-80-xt],[180,80+xt]])}function vye(){return MH()()}const CE=e=>e;var Jj=new iu,SE=new iu,DH,IH,jE,NE,wl={point:es,lineStart:es,lineEnd:es,polygonStart:function(){wl.lineStart=wye,wl.lineEnd=Sye},polygonEnd:function(){wl.lineStart=wl.lineEnd=wl.point=es,Jj.add(fn(SE)),SE=new iu},result:function(){var e=Jj/2;return Jj=new iu,e}};function wye(){wl.point=Cye}function Cye(e,t){wl.point=RH,DH=jE=e,IH=NE=t}function RH(e,t){SE.add(NE*e-jE*t),jE=e,NE=t}function Sye(){RH(DH,IH)}var mm=1/0,jw=mm,kb=-mm,Nw=kb,kw={point:jye,lineStart:es,lineEnd:es,polygonStart:es,polygonEnd:es,result:function(){var e=[[mm,jw],[kb,Nw]];return kb=Nw=-(jw=mm=1/0),e}};function jye(e,t){e<mm&&(mm=e),e>kb&&(kb=e),t<jw&&(jw=t),t>Nw&&(Nw=t)}var kE=0,EE=0,dg=0,Ew=0,_w=0,mh=0,_E=0,TE=0,fg=0,AH,PH,Ta,Ma,ci={point:nf,lineStart:s5,lineEnd:o5,polygonStart:function(){ci.lineStart=Eye,ci.lineEnd=_ye},polygonEnd:function(){ci.point=nf,ci.lineStart=s5,ci.lineEnd=o5},result:function(){var e=fg?[_E/fg,TE/fg]:mh?[Ew/mh,_w/mh]:dg?[kE/dg,EE/dg]:[NaN,NaN];return kE=EE=dg=Ew=_w=mh=_E=TE=fg=0,e}};function nf(e,t){kE+=e,EE+=t,++dg}function s5(){ci.point=Nye}function Nye(e,t){ci.point=kye,nf(Ta=e,Ma=t)}function kye(e,t){var n=e-Ta,r=t-Ma,s=no(n*n+r*r);Ew+=s*(Ta+e)/2,_w+=s*(Ma+t)/2,mh+=s,nf(Ta=e,Ma=t)}function o5(){ci.point=nf}function Eye(){ci.point=Tye}function _ye(){OH(AH,PH)}function Tye(e,t){ci.point=OH,nf(AH=Ta=e,PH=Ma=t)}function OH(e,t){var n=e-Ta,r=t-Ma,s=no(n*n+r*r);Ew+=s*(Ta+e)/2,_w+=s*(Ma+t)/2,mh+=s,s=Ma*e-Ta*t,_E+=s*(Ta+e),TE+=s*(Ma+t),fg+=s*3,nf(Ta=e,Ma=t)}function FH(e){this._context=e}FH.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,Wo);break}}},result:es};var ME=new iu,eN,$H,LH,hg,mg,Eb={point:es,lineStart:function(){Eb.point=Mye},lineEnd:function(){eN&&zH($H,LH),Eb.point=es},polygonStart:function(){eN=!0},polygonEnd:function(){eN=null},result:function(){var e=+ME;return ME=new iu,e}};function Mye(e,t){Eb.point=zH,$H=hg=e,LH=mg=t}function zH(e,t){hg-=e,mg-=t,ME.add(no(hg*hg+mg*mg)),hg=e,mg=t}let i5,Tw,a5,l5;class c5{constructor(t){this._append=t==null?BH:Dye(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!==a5||this._append!==Tw){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`,a5=r,Tw=this._append,l5=this._,this._=s}this._+=l5;break}}}result(){const t=this._;return this._="",t.length?t:null}}function BH(e){let t=1;this._+=e[0];for(const n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function Dye(e){const t=Math.floor(e);if(!(t>=0))throw new RangeError(`invalid digits: ${e}`);if(t>15)return BH;if(t!==i5){const n=10**t;i5=t,Tw=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 Tw}function u5(e,t){let n=3,r=4.5,s,o;function i(a){return a&&(typeof r=="function"&&o.pointRadius(+r.apply(this,arguments)),nd(a,s(o))),o.result()}return i.area=function(a){return nd(a,s(wl)),wl.result()},i.measure=function(a){return nd(a,s(Eb)),Eb.result()},i.bounds=function(a){return nd(a,s(kw)),kw.result()},i.centroid=function(a){return nd(a,s(ci)),ci.result()},i.projection=function(a){return arguments.length?(s=a==null?(e=null,CE):(e=a).stream,i):e},i.context=function(a){return arguments.length?(o=a==null?(t=null,new c5(n)):new FH(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 l=Math.floor(a);if(!(l>=0))throw new RangeError(`invalid digits: ${a}`);n=l}return t===null&&(o=new c5(n)),i},i.projection(e).digits(n).context(t)}function dD(e){return function(t){var n=new DE;for(var r in e)n[r]=e[r];return n.stream=t,n}}function DE(){}DE.prototype={constructor:DE,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 fD(e,t,n){var r=e.clipExtent&&e.clipExtent();return e.scale(150).translate([0,0]),r!=null&&e.clipExtent(null),nd(n,e.stream(kw)),t(kw.result()),r!=null&&e.clipExtent(r),e}function hD(e,t,n){return fD(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,l=+t[0][1]+(o-i*(r[1][1]+r[0][1]))/2;e.scale(150*i).translate([a,l])},n)}function VH(e,t,n){return hD(e,[[0,0],t],n)}function HH(e,t,n){return fD(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 UH(e,t,n){return fD(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 d5=16,Iye=Et(30*Rn);function f5(e,t){return+t?Aye(e,t):Rye(e)}function Rye(e){return dD({point:function(t,n){t=e(t,n),this.stream.point(t[0],t[1])}})}function Aye(e,t){function n(r,s,o,i,a,l,u,d,f,h,m,p,g,b){var x=u-r,y=d-s,v=x*x+y*y;if(v>4*t&&g--){var w=i+h,j=a+m,S=l+p,N=no(w*w+j*j+S*S),E=gi(S/=N),_=fn(fn(S)-1)<xt||fn(o-f)<xt?(o+f)/2:Ua(j,w),k=e(_,E),M=k[0],T=k[1],P=M-r,O=T-s,I=y*P-x*O;(I*I/v>t||fn((x*P+y*O)/v-.5)>.3||i*h+a*m+l*p<Iye)&&(n(r,s,o,i,a,l,M,T,_,w/=N,j/=N,S,g,b),b.point(M,T),n(M,T,_,w,j,S,u,d,f,h,m,p,g,b))}}return function(r){var s,o,i,a,l,u,d,f,h,m,p,g,b={point:x,lineStart:y,lineEnd:w,polygonStart:function(){r.polygonStart(),b.lineStart=j},polygonEnd:function(){r.polygonEnd(),b.lineStart=y}};function x(E,_){E=e(E,_),r.point(E[0],E[1])}function y(){f=NaN,b.point=v,r.lineStart()}function v(E,_){var k=fm([E,_]),M=e(E,_);n(f,h,d,m,p,g,f=M[0],h=M[1],d=E,m=k[0],p=k[1],g=k[2],d5,r),r.point(f,h)}function w(){b.point=x,r.lineEnd()}function j(){y(),b.point=S,b.lineEnd=N}function S(E,_){v(s=E,_),o=f,i=h,a=m,l=p,u=g,b.point=v}function N(){n(f,h,d,m,p,g,o,i,s,a,l,u,d5,r),b.lineEnd=w,w()}return b}}var Pye=dD({point:function(e,t){this.stream.point(e*Rn,t*Rn)}});function Oye(e){return dD({point:function(t,n){var r=e(t,n);return this.stream.point(r[0],r[1])}})}function Fye(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 h5(e,t,n,r,s,o){if(!o)return Fye(e,t,n,r,s);var i=Et(o),a=wt(o),l=i*e,u=a*e,d=i/e,f=a/e,h=(a*n-i*t)/e,m=(a*t+i*n)/e;function p(g,b){return g*=r,b*=s,[l*g-u*b+t,n-u*g-l*b]}return p.invert=function(g,b){return[r*(d*g-f*b+h),s*(m-f*g-d*b)]},p}function rc(e){return WH(function(){return e})()}function WH(e){var t,n=150,r=480,s=250,o=0,i=0,a=0,l=0,u=0,d,f=0,h=1,m=1,p=null,g=ZF,b=null,x,y,v,w=CE,j=.5,S,N,E,_,k;function M(I){return E(I[0]*Rn,I[1]*Rn)}function T(I){return I=E.invert(I[0],I[1]),I&&[I[0]*Ys,I[1]*Ys]}M.stream=function(I){return _&&k===I?_:_=Pye(Oye(d)(g(S(w(k=I)))))},M.preclip=function(I){return arguments.length?(g=I,p=void 0,O()):g},M.postclip=function(I){return arguments.length?(w=I,b=x=y=v=null,O()):w},M.clipAngle=function(I){return arguments.length?(g=+I?cye(p=I*Rn):(p=null,ZF),O()):p*Ys},M.clipExtent=function(I){return arguments.length?(w=I==null?(b=x=y=v=null,CE):dye(b=+I[0][0],x=+I[0][1],y=+I[1][0],v=+I[1][1]),O()):b==null?null:[[b,x],[y,v]]},M.scale=function(I){return arguments.length?(n=+I,P()):n},M.translate=function(I){return arguments.length?(r=+I[0],s=+I[1],P()):[r,s]},M.center=function(I){return arguments.length?(o=I[0]%360*Rn,i=I[1]%360*Rn,P()):[o*Ys,i*Ys]},M.rotate=function(I){return arguments.length?(a=I[0]%360*Rn,l=I[1]%360*Rn,u=I.length>2?I[2]%360*Rn:0,P()):[a*Ys,l*Ys,u*Ys]},M.angle=function(I){return arguments.length?(f=I%360*Rn,P()):f*Ys},M.reflectX=function(I){return arguments.length?(h=I?-1:1,P()):h<0},M.reflectY=function(I){return arguments.length?(m=I?-1:1,P()):m<0},M.precision=function(I){return arguments.length?(S=f5(N,j=I*I),O()):no(j)},M.fitExtent=function(I,$){return hD(M,I,$)},M.fitSize=function(I,$){return VH(M,I,$)},M.fitWidth=function(I,$){return HH(M,I,$)},M.fitHeight=function(I,$){return UH(M,I,$)};function P(){var I=h5(n,0,0,h,m,f).apply(null,t(o,i)),$=h5(n,r-I[0],s-I[1],h,m,f);return d=jH(a,l,u),N=gE(t,$),E=gE(d,N),S=f5(N,j),O()}function O(){return _=k=null,M}return function(){return t=e.apply(this,arguments),M.invert=t.invert&&T,P()}}function mD(e){var t=0,n=Bt/3,r=WH(e),s=r(t,n);return s.parallels=function(o){return arguments.length?r(t=o[0]*Rn,n=o[1]*Rn):[t*Ys,n*Ys]},s}function $ye(e){var t=Et(e);function n(r,s){return[r*t,wt(s)/t]}return n.invert=function(r,s){return[r/t,gi(s*t)]},n}function Lye(e,t){var n=wt(e),r=(n+wt(t))/2;if(fn(r)<xt)return $ye(e);var s=1+n*(2*r-n),o=no(s)/r;function i(a,l){var u=no(s-2*r*wt(l))/r;return[u*wt(a*=r),o-u*Et(a)]}return i.invert=function(a,l){var u=o-l,d=Ua(a,fn(u))*ui(u);return u*r<0&&(d-=Bt*ui(a)*ui(u)),[d/r,gi((s-(a*a+u*u)*r*r)/(2*r))]},i}function Mw(){return mD(Lye).scale(155.424).center([0,33.6442])}function qH(){return Mw().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function zye(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 Bye(){var e,t,n=qH(),r,s=Mw().rotate([154,0]).center([-2,58.5]).parallels([55,65]),o,i=Mw().rotate([157,0]).center([-3,19.9]).parallels([8,18]),a,l,u={point:function(h,m){l=[h,m]}};function d(h){var m=h[0],p=h[1];return l=null,r.point(m,p),l||(o.point(m,p),l)||(a.point(m,p),l)}d.invert=function(h){var m=n.scale(),p=n.translate(),g=(h[0]-p[0])/m,b=(h[1]-p[1])/m;return(b>=.12&&b<.234&&g>=-.425&&g<-.214?s:b>=.166&&b<.234&&g>=-.214&&g<-.115?i:n).invert(h)},d.stream=function(h){return e&&t===h?e:e=zye([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 m=n.scale(),p=+h[0],g=+h[1];return r=n.translate(h).clipExtent([[p-.455*m,g-.238*m],[p+.455*m,g+.238*m]]).stream(u),o=s.translate([p-.307*m,g+.201*m]).clipExtent([[p-.425*m+xt,g+.12*m+xt],[p-.214*m-xt,g+.234*m-xt]]).stream(u),a=i.translate([p-.205*m,g+.212*m]).clipExtent([[p-.214*m+xt,g+.166*m+xt],[p-.115*m-xt,g+.234*m-xt]]).stream(u),f()},d.fitExtent=function(h,m){return hD(d,h,m)},d.fitSize=function(h,m){return VH(d,h,m)},d.fitWidth=function(h,m){return HH(d,h,m)},d.fitHeight=function(h,m){return UH(d,h,m)};function f(){return e=t=null,d}return d.scale(1070)}function YH(e){return function(t,n){var r=Et(t),s=Et(n),o=e(r*s);return o===1/0?[2,0]:[o*s*wt(t),o*wt(n)]}}function Hx(e){return function(t,n){var r=no(t*t+n*n),s=e(r),o=wt(s),i=Et(s);return[Ua(t*o,r*i),gi(r&&n*o/r)]}}var GH=YH(function(e){return no(2/(1+e))});GH.invert=Hx(function(e){return 2*gi(e/2)});function Vye(){return rc(GH).scale(124.75).clipAngle(180-.001)}var KH=YH(function(e){return(e=SH(e))&&e/wt(e)});KH.invert=Hx(function(e){return e});function Hye(){return rc(KH).scale(79.4188).clipAngle(180-.001)}function SC(e,t){return[e,vw(uD((gr+t)/2))]}SC.invert=function(e,t){return[e,2*Xm(CH(t))-gr]};function Uye(){return ZH(SC).scale(961/Wo)}function ZH(e){var t=rc(e),n=t.center,r=t.scale,s=t.translate,o=t.clipExtent,i=null,a,l,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=l=u=null:(i=+f[0][0],a=+f[0][1],l=+f[1][0],u=+f[1][1]),d()):i==null?null:[[i,a],[l,u]]};function d(){var f=Bt*r(),h=t(nye(t.rotate()).invert([0,0]));return o(i==null?[[h[0]-f,h[1]-f],[h[0]+f,h[1]+f]]:e===SC?[[Math.max(h[0]-f,i),a],[Math.min(h[0]+f,l),u]]:[[i,Math.max(h[1]-f,a)],[l,Math.min(h[1]+f,u)]])}return d()}function v0(e){return uD((gr+e)/2)}function Wye(e,t){var n=Et(e),r=e===t?wt(e):vw(n/Et(t))/vw(v0(t)/v0(e)),s=n*Zj(v0(e),r)/r;if(!r)return SC;function o(i,a){s>0?a<-gr+xt&&(a=-gr+xt):a>gr-xt&&(a=gr-xt);var l=s/Zj(v0(a),r);return[l*wt(r*i),s-l*Et(r*i)]}return o.invert=function(i,a){var l=s-a,u=ui(r)*no(i*i+l*l),d=Ua(i,fn(l))*ui(l);return l*r<0&&(d-=Bt*ui(i)*ui(l)),[d/r,2*Xm(Zj(s/u,1/r))-gr]},o}function qye(){return mD(Wye).scale(109.5).parallels([30,30])}function Dw(e,t){return[e,t]}Dw.invert=Dw;function Yye(){return rc(Dw).scale(152.63)}function Gye(e,t){var n=Et(e),r=e===t?wt(e):(n-Et(t))/(t-e),s=n/r+e;if(fn(r)<xt)return Dw;function o(i,a){var l=s-a,u=r*i;return[l*wt(u),s-l*Et(u)]}return o.invert=function(i,a){var l=s-a,u=Ua(i,fn(l))*ui(l);return l*r<0&&(u-=Bt*ui(i)*ui(l)),[u/r,s-ui(r)*no(i*i+l*l)]},o}function Kye(){return mD(Gye).scale(131.154).center([0,13.9389])}var Og=1.340264,Fg=-.081106,$g=893e-6,Lg=.003796,Iw=no(3)/2,Zye=12;function XH(e,t){var n=gi(Iw*wt(t)),r=n*n,s=r*r*r;return[e*Et(n)/(Iw*(Og+3*Fg*r+s*(7*$g+9*Lg*r))),n*(Og+Fg*r+s*($g+Lg*r))]}XH.invert=function(e,t){for(var n=t,r=n*n,s=r*r*r,o=0,i,a,l;o<Zye&&(a=n*(Og+Fg*r+s*($g+Lg*r))-t,l=Og+3*Fg*r+s*(7*$g+9*Lg*r),n-=i=a/l,r=n*n,s=r*r*r,!(fn(i)<cD));++o);return[Iw*e*(Og+3*Fg*r+s*(7*$g+9*Lg*r))/Et(n),gi(wt(n)/Iw)]};function Xye(){return rc(XH).scale(177.158)}function QH(e,t){var n=Et(t),r=Et(e)*n;return[n*wt(e)/r,wt(t)/r]}QH.invert=Hx(Xm);function Qye(){return rc(QH).scale(144.049).clipAngle(60)}function JH(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)))]}JH.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(fn(s)>xt&&--r>0);return[e/(.8707+(o=n*n)*(-.131979+o*(-.013791+o*o*o*(.003971-.001529*o)))),n]};function Jye(){return rc(JH).scale(175.295)}function eU(e,t){return[Et(t)*wt(e),wt(t)]}eU.invert=Hx(gi);function e0e(){return rc(eU).scale(249.5).clipAngle(90+xt)}function tU(e,t){var n=Et(t),r=1+Et(e)*n;return[n*wt(e)/r,wt(t)/r]}tU.invert=Hx(function(e){return 2*Xm(e)});function t0e(){return rc(tU).scale(250).clipAngle(142)}function nU(e,t){return[vw(uD((gr+t)/2)),-e]}nU.invert=function(e,t){return[-t,2*Xm(CH(e))-gr]};function n0e(){var e=ZH(nU),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 yn(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 jC(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function pD(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Qm(){}var rf=.7,pm=1/rf,Mh="\\s*([+-]?\\d+)\\s*",_b="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Fa="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",r0e=/^#([0-9a-f]{3,8})$/,s0e=new RegExp(`^rgb\\(${Mh},${Mh},${Mh}\\)$`),o0e=new RegExp(`^rgb\\(${Fa},${Fa},${Fa}\\)$`),i0e=new RegExp(`^rgba\\(${Mh},${Mh},${Mh},${_b}\\)$`),a0e=new RegExp(`^rgba\\(${Fa},${Fa},${Fa},${_b}\\)$`),l0e=new RegExp(`^hsl\\(${_b},${Fa},${Fa}\\)$`),c0e=new RegExp(`^hsla\\(${_b},${Fa},${Fa},${_b}\\)$`),m5={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};jC(Qm,gD,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:p5,formatHex:p5,formatHex8:u0e,formatHsl:d0e,formatRgb:g5,toString:g5});function p5(){return this.rgb().formatHex()}function u0e(){return this.rgb().formatHex8()}function d0e(){return sU(this).formatHsl()}function g5(){return this.rgb().formatRgb()}function gD(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=r0e.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?b5(t):n===3?new Ms(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?w0(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?w0(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=s0e.exec(e))?new Ms(t[1],t[2],t[3],1):(t=o0e.exec(e))?new Ms(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=i0e.exec(e))?w0(t[1],t[2],t[3],t[4]):(t=a0e.exec(e))?w0(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=l0e.exec(e))?v5(t[1],t[2]/100,t[3]/100,1):(t=c0e.exec(e))?v5(t[1],t[2]/100,t[3]/100,t[4]):m5.hasOwnProperty(e)?b5(m5[e]):e==="transparent"?new Ms(NaN,NaN,NaN,0):null}function b5(e){return new Ms(e>>16&255,e>>8&255,e&255,1)}function w0(e,t,n,r){return r<=0&&(e=t=n=NaN),new Ms(e,t,n,r)}function rU(e){return e instanceof Qm||(e=gD(e)),e?(e=e.rgb(),new Ms(e.r,e.g,e.b,e.opacity)):new Ms}function Tb(e,t,n,r){return arguments.length===1?rU(e):new Ms(e,t,n,r??1)}function Ms(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}jC(Ms,Tb,pD(Qm,{brighter(e){return e=e==null?pm:Math.pow(pm,e),new Ms(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?rf:Math.pow(rf,e),new Ms(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Ms(Ad(this.r),Ad(this.g),Ad(this.b),Rw(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:x5,formatHex:x5,formatHex8:f0e,formatRgb:y5,toString:y5}));function x5(){return`#${fd(this.r)}${fd(this.g)}${fd(this.b)}`}function f0e(){return`#${fd(this.r)}${fd(this.g)}${fd(this.b)}${fd((isNaN(this.opacity)?1:this.opacity)*255)}`}function y5(){const e=Rw(this.opacity);return`${e===1?"rgb(":"rgba("}${Ad(this.r)}, ${Ad(this.g)}, ${Ad(this.b)}${e===1?")":`, ${e})`}`}function Rw(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Ad(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function fd(e){return e=Ad(e),(e<16?"0":"")+e.toString(16)}function v5(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new $i(e,t,n,r)}function sU(e){if(e instanceof $i)return new $i(e.h,e.s,e.l,e.opacity);if(e instanceof Qm||(e=gD(e)),!e)return new $i;if(e instanceof $i)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,l=(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/=l<.5?o+s:2-o-s,i*=60):a=l>0&&l<1?0:i,new $i(i,a,l,e.opacity)}function h0e(e,t,n,r){return arguments.length===1?sU(e):new $i(e,t,n,r??1)}function $i(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}jC($i,h0e,pD(Qm,{brighter(e){return e=e==null?pm:Math.pow(pm,e),new $i(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?rf:Math.pow(rf,e),new $i(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 Ms(tN(e>=240?e-240:e+120,s,r),tN(e,s,r),tN(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new $i(w5(this.h),C0(this.s),C0(this.l),Rw(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=Rw(this.opacity);return`${e===1?"hsl(":"hsla("}${w5(this.h)}, ${C0(this.s)*100}%, ${C0(this.l)*100}%${e===1?")":`, ${e})`}`}}));function w5(e){return e=(e||0)%360,e<0?e+360:e}function C0(e){return Math.max(0,Math.min(1,e||0))}function tN(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 m0e=Math.PI/180,p0e=180/Math.PI;var oU=-.14861,bD=1.78277,xD=-.29227,NC=-.90649,Mb=1.97294,C5=Mb*NC,S5=Mb*bD,j5=bD*xD-NC*oU;function g0e(e){if(e instanceof Pd)return new Pd(e.h,e.s,e.l,e.opacity);e instanceof Ms||(e=rU(e));var t=e.r/255,n=e.g/255,r=e.b/255,s=(j5*r+C5*t-S5*n)/(j5+C5-S5),o=r-s,i=(Mb*(n-s)-xD*o)/NC,a=Math.sqrt(i*i+o*o)/(Mb*s*(1-s)),l=a?Math.atan2(i,o)*p0e-120:NaN;return new Pd(l<0?l+360:l,a,s,e.opacity)}function Wa(e,t,n,r){return arguments.length===1?g0e(e):new Pd(e,t,n,r??1)}function Pd(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}jC(Pd,Wa,pD(Qm,{brighter(e){return e=e==null?pm:Math.pow(pm,e),new Pd(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?rf:Math.pow(rf,e),new Pd(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=isNaN(this.h)?0:(this.h+120)*m0e,t=+this.l,n=isNaN(this.s)?0:this.s*t*(1-t),r=Math.cos(e),s=Math.sin(e);return new Ms(255*(t+n*(oU*r+bD*s)),255*(t+n*(xD*r+NC*s)),255*(t+n*(Mb*r)),this.opacity)}}));function b0e(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 x0e(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 b0e((n-r/t)*t,i,s,o,a)}}const yD=e=>()=>e;function iU(e,t){return function(n){return e+n*t}}function y0e(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 v0e(e,t){var n=t-e;return n?iU(e,n>180||n<-180?n-360*Math.round(n/360):n):yD(isNaN(e)?t:e)}function w0e(e){return(e=+e)==1?Dh:function(t,n){return n-t?y0e(t,n,e):yD(isNaN(t)?n:t)}}function Dh(e,t){var n=t-e;return n?iU(e,n):yD(isNaN(e)?t:e)}(function e(t){var n=w0e(t);function r(s,o){var i=n((s=Tb(s)).r,(o=Tb(o)).r),a=n(s.g,o.g),l=n(s.b,o.b),u=Dh(s.opacity,o.opacity);return function(d){return s.r=i(d),s.g=a(d),s.b=l(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function C0e(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=Tb(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(l){return a.r=r(l),a.g=s(l),a.b=o(l),a+""}}}var S0e=C0e(x0e);function aU(e){return function t(n){n=+n;function r(s,o){var i=e((s=Wa(s)).h,(o=Wa(o)).h),a=Dh(s.s,o.s),l=Dh(s.l,o.l),u=Dh(s.opacity,o.opacity);return function(d){return s.h=i(d),s.s=a(d),s.l=l(Math.pow(d,n)),s.opacity=u(d),s+""}}return r.gamma=t,r}(1)}aU(v0e);var vD=aU(Dh);const Vn=e=>S0e(e[e.length-1]);var j0e=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(yn);const N0e=Vn(j0e);var k0e=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(yn);const E0e=Vn(k0e);var _0e=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(yn);const T0e=Vn(_0e);var M0e=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(yn);const D0e=Vn(M0e);var I0e=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(yn);const R0e=Vn(I0e);var A0e=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(yn);const P0e=Vn(A0e);var O0e=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(yn);const F0e=Vn(O0e);var $0e=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(yn);const L0e=Vn($0e);var z0e=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(yn);const B0e=Vn(z0e);var V0e=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(yn);const H0e=Vn(V0e);var U0e=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(yn);const W0e=Vn(U0e);var q0e=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(yn);const Y0e=Vn(q0e);var G0e=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(yn);const K0e=Vn(G0e);var Z0e=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(yn);const X0e=Vn(Z0e);var Q0e=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(yn);const J0e=Vn(Q0e);var eve=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(yn);const tve=Vn(eve);var nve=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(yn);const rve=Vn(nve);var sve=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(yn);const ove=Vn(sve);var ive=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(yn);const ave=Vn(ive);var lve=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(yn);const cve=Vn(lve);var uve=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(yn);const dve=Vn(uve);var fve=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(yn);const hve=Vn(fve);var mve=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(yn);const pve=Vn(mve);var gve=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(yn);const bve=Vn(gve);var xve=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(yn);const yve=Vn(xve);var vve=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(yn);const wve=Vn(vve);var Cve=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(yn);const Sve=Vn(Cve);function jve(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 Nve=vD(Wa(300,.5,0),Wa(-240,.5,1));var kve=vD(Wa(-100,.75,.35),Wa(80,1.5,.8)),Eve=vD(Wa(260,.75,.35),Wa(80,1.5,.8)),S0=Wa();function _ve(e){(e<0||e>1)&&(e-=Math.floor(e));var t=Math.abs(e-.5);return S0.h=360*e-100,S0.s=1.5-1.5*t,S0.l=.8-.9*t,S0+""}var j0=Tb(),Tve=Math.PI/3,Mve=Math.PI*2/3;function Dve(e){var t;return e=(.5-e)*Math.PI,j0.r=255*(t=Math.sin(e))*t,j0.g=255*(t=Math.sin(e+Tve))*t,j0.b=255*(t=Math.sin(e+Mve))*t,j0+""}function Ive(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 kC(e){var t=e.length;return function(n){return e[Math.max(0,Math.min(t-1,Math.floor(n*t)))]}}const Rve=kC(yn("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var Ave=kC(yn("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),Pve=kC(yn("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),Ove=kC(yn("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function Fve(e){return e}function $ve(e){if(e==null)return Fve;var t,n,r=e.scale[0],s=e.scale[1],o=e.translate[0],i=e.translate[1];return function(a,l){l||(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 Lve(e,t){for(var n,r=e.length,s=r-t;s<--r;)n=e[s],e[s++]=e[r],e[r]=n}function zve(e,t){return typeof t=="string"&&(t=e.objects[t]),t.type==="GeometryCollection"?{type:"FeatureCollection",features:t.geometries.map(function(n){return N5(e,n)})}:N5(e,t)}function N5(e,t){var n=t.id,r=t.bbox,s=t.properties==null?{}:t.properties,o=Bve(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 Bve(e,t){var n=$ve(e.transform),r=e.arcs;function s(d,f){f.length&&f.pop();for(var h=r[d<0?~d:d],m=0,p=h.length;m<p;++m)f.push(n(h[m],m));d<0&&Lve(f,p)}function o(d){return n(d)}function i(d){for(var f=[],h=0,m=d.length;h<m;++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 l(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=l(d.arcs);break;case"MultiPolygon":h=d.arcs.map(l);break;default:return null}return{type:f,coordinates:h}}return u(t)}const zg={geoAzimuthalEqualArea:Vye,geoAzimuthalEquidistant:Hye,geoGnomonic:Qye,geoOrthographic:e0e,geoStereographic:t0e,geoEqualEarth:Xye,geoAlbers:qH,geoAlbersUsa:Bye,geoConicConformal:qye,geoConicEqualArea:Mw,geoConicEquidistant:Kye,geoEquirectangular:Yye,geoMercator:Uye,geoTransverseMercator:n0e,geoNaturalEarth1:Jye};Object.keys(zg).forEach(e=>{zg[`${e.charAt(3).toLowerCase()}${e.slice(4)}`]=zg[e]});class If extends Nu{constructor(t){super(t),this.outlineBounds=null,this.oldChartBounds=null,this.geoPath=u5()}init(t){t.position="chartArea",super.init(t),typeof t.projection=="function"?this.projection=t.projection:this.projection=(zg[t.projection]||zg.albersUsa)(),this.geoPath.projection(this.projection),this.outlineBounds=null,this.oldChartBounds=null}computeBounds(t){const n=u5(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,l=t.right-t.left-o-a,u=t.bottom-t.top-s-i,d=this.oldChartBounds;this.oldChartBounds={chartWidth:l,chartHeight:u};const f=Math.min(l/n.width,u/n.height),h=n.width*f,m=n.height*f,p=(l-h)*.5+t.left+o,g=(u-m)*.5+t.top+s,b=this.options;return this.projection.scale(n.refScale*f*b.projectionScale).translate([f*n.refX+p+b.projectionOffset[0],f*n.refY+g+b.projectionOffset[1]]),!d||d.chartWidth!==this.oldChartBounds.chartWidth||d.chartHeight!==this.oldChartBounds.chartHeight}}If.id="projection";If.defaults={projection:"albersUsa",projectionScale:1,projectionOffset:[0,0],padding:0};If.descriptors={_scriptable:e=>e!=="projection",_indexable:e=>e!=="projectionOffset"};const EC={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 Vve(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 Hve(e,t,n,r,s){const{indicatorWidth:o,align:i,position:a}=t,l=i==="top"||i==="bottom",u=(i==="left"?s.w:n)+(l?o:0),d=(i==="top"?s.h:r)+(l?0:o),f=Vve(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 ph extends tf{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(),l=(m,p)=>m<1?p*m:m,u=Math.min(o,l(a?i.length:i.width,o))-(a?0:i.indicatorWidth),d=Math.min(s,l(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=Hve(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 lU extends dm{constructor(){super(...arguments),this.legendSize={w:0,h:0}}init(t){ph.prototype.init.call(this,t)}parse(t,n){return ph.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 ph.prototype.update.call(this,t,n,r)}_computeLabelArea(){}draw(t){return ph.prototype.draw.call(this,t)}_drawIndicator(){}}const Cl={interpolateBlues:hve,interpolateBrBG:N0e,interpolateBuGn:H0e,interpolateBuPu:W0e,interpolateCividis:jve,interpolateCool:Eve,interpolateCubehelixDefault:Nve,interpolateGnBu:Y0e,interpolateGreens:pve,interpolateGreys:bve,interpolateInferno:Pve,interpolateMagma:Ave,interpolateOrRd:K0e,interpolateOranges:Sve,interpolatePRGn:E0e,interpolatePiYG:T0e,interpolatePlasma:Ove,interpolatePuBu:J0e,interpolatePuBuGn:X0e,interpolatePuOr:D0e,interpolatePuRd:tve,interpolatePurples:yve,interpolateRainbow:_ve,interpolateRdBu:R0e,interpolateRdGy:P0e,interpolateRdPu:rve,interpolateRdYlBu:F0e,interpolateRdYlGn:L0e,interpolateReds:wve,interpolateSinebow:Dve,interpolateSpectral:B0e,interpolateTurbo:Ive,interpolateViridis:Rve,interpolateWarm:kve,interpolateYlGn:ave,interpolateYlGnBu:ove,interpolateYlOrBr:cve,interpolateYlOrRd:dve};Object.keys(Cl).forEach(e=>{Cl[`${e.charAt(11).toLowerCase()}${e.slice(12)}`]=Cl[e],Cl[e.slice(11)]=Cl[e]});function cU(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 uU={interpolate:"blues",missing:"transparent",quantize:0};class au extends ph{get interpolate(){const t=this.options;return t?typeof t.interpolate=="function"?t.interpolate:Cl[t.interpolate]||Cl.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=cU(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)}}}}au.id="color";au.defaults=Or({},[tf.defaults,EC,uU]);au.descriptors={_scriptable:e=>e!=="interpolate",_indexable:!1};class wD extends lU{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=Cl[t.interpolate]||Cl.blues}getColorForValue(t){return au.prototype.getColorForValue.call(this,t)}getColor(t){let n=t;return this.options.quantize>0&&(n=cU(n,this.options.quantize)),this.interpolate(n)}_drawIndicator(){return au.prototype._drawIndicator.call(this)}}wD.id="colorLogarithmic";wD.defaults=Or({},[dm.defaults,EC,uU]);wD.descriptors={_scriptable:e=>e!=="interpolate",_indexable:!1};const dU={missing:1,mode:"area",range:[2,20],legend:{align:"bottom",length:90,width:70,indicatorWidth:42}};class lu extends ph{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,l=t*a+i;return Math.sqrt(l/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,l)=>({[r?"x":"y"]:this.getPixelForTick(l)}));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,l)=>{const u=i[l],d=this.getSizeForValue(a.value),f=r?u.x:n,h=r?n:u.y,m={pointStyle:"circle",borderWidth:0,...this._model||{},radius:d};pw(t,m,f,h)})}}lu.id="size";lu.defaults=Or({},[tf.defaults,EC,dU]);lu.descriptors={_scriptable:!0,_indexable:e=>e!=="range"};class fU extends lU{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 lu.prototype.getSizeImpl.call(this,t)}_drawIndicator(){lu.prototype._drawIndicator.call(this)}}fU.id="sizeLogarithmic";fU.defaults=Or({},[dm.defaults,EC,dU]);function Uve(e,t){return[[e[0][0]-t,e[0][1]-t],[e[1][0]+t,e[1][1]+t]]}class Jl extends wi{constructor(){super(...arguments),this.cache=void 0}updateExtras({scale:t,feature:n,center:r,pixelRatio:s,mode:o}){var i,a;const l=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,l&&(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&&yye(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=Uve(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),l=this.pixelRatio||1,u=Math.ceil(Math.max(i-s,1)*l),d=Math.ceil(Math.max(a-o,1)*l);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(l,l),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),l=i-s,u=a-o;l>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())}}Jl.id="geoFeature";Jl.defaults={...Oa.defaults,outlineBackgroundColor:null,outlineBorderWidth:0,graticuleBorderColor:"#CCCCCC",graticuleBorderWidth:0};Jl.defaultRoutes={outlineBorderColor:"borderColor",...Oa.defaultRoutes||{}};const hU={showOutline:!1,showGraticule:!1,clipMap:!0},mU={scales:{projection:{axis:"x",type:If.id,position:"chartArea",display:!1}}};function k5(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 pU extends Co{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 mt(this.getGeoDataset().showOutline,this.getGeoOptions().showOutline)}clipMap(){return mt(this.getGeoDataset().clipMap,this.getGeoOptions().clipMap)}getGraticule(){return mt(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=k5(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=k5(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(vye());else{const i=MH();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,Kc(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||Kc(t.ctx,t.chartArea):r&&(r=!1,Zc(t.ctx)),this.showGraticule(),n===!0||n==="items"?r||Kc(t.ctx,t.chartArea):r&&(r=!1,Zc(t.ctx)),this.getMeta().data.forEach(s=>s.draw.call(s,t.ctx,t.chartArea)),r&&(r=!1,Zc(t.ctx))}}function gU(e,t,n,r=[],s=[]){hr.addControllers(n),Array.isArray(r)?hr.addElements(...r):hr.addElements(r),Array.isArray(s)?hr.addScales(...s):hr.addScales(s);const o=t;return o.type=e,o}class Jm extends pU{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),l=this.getProjectionScale();this.updateSharedOptions(i,s,o);for(let u=n;u<n+r;u+=1){const d=t[u];d.projectionScale=l;const f=d.updateExtras({scale:l,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])}}Jm.id="choropleth";Jm.defaults=Or({},[hU,{datasetElementType:Jl.id,dataElementType:Jl.id}]);Jm.overrides=Or({},[mU,{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:au.id,axis:"x"}},elements:{geoFeature:{backgroundColor(e){return e.dataIndex==null?null:e.chart.getDatasetMeta(e.datasetIndex).controller.indexToColor(e.dataIndex)}}}}]);class Wve extends Xt{constructor(t,n){super(t,gU("choropleth",n,Jm,Jl,[au,If]))}}Wve.id=Jm.id;class ep extends pU{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),l=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),m=u.projection([h.x,h.y]),p={x:m?m[0]:0,y:m?m[1]:0,skip:Number.isNaN(h.x)||Number.isNaN(h.y)};l&&(p.options=a||this.resolveDataElementOptions(d,s),o&&(p.options.radius=0)),this.updateElement(f,d,p,s)}}indexToRadius(t){const n=this.getMeta().rScale;return n.getSizeForValue(this.getParsed(t)[n.axis])}}ep.id="bubbleMap";ep.defaults=Or({},[hU,{dataElementType:Rd.id,datasetElementType:Jl.id,showOutline:!0,clipMap:"outline+graticule"}]);ep.overrides=Or({},[mU,{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:lu.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 qve extends Xt{constructor(t,n){super(t,gU("bubbleMap",n,ep,Jl,[lu,If]))}}qve.id=ep.id;function Yve(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 Gve(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 Kve(e,t,n=!1){var s,o,i,a,l,u,d,f,h,m,p;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:((l=(a=(i=e==null?void 0:e.options)==null?void 0:i.scales)==null?void 0:a.x)==null?void 0:l.display)??!0,stacked:!n},y:{...(d=(u=e==null?void 0:e.options)==null?void 0:u.scales)==null?void 0:d.y,display:((m=(h=(f=e==null?void 0:e.options)==null?void 0:f.scales)==null?void 0:h.y)==null?void 0:m.display)??!0,stacked:t==="stackedBar"}},plugins:{...(p=e==null?void 0:e.options)==null?void 0:p.plugins,legend:{display:!1,position:"bottom",align:"center"}}}}}function Zve(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 Xve(e){var r,s;const t=J.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:$n.slate[800]},angleLines:{color:$n.slate[800]},ticks:{color:$n.slate[800],showLabelBackdrop:!1}}}}}),n}function Js({number:e,decimalPlaces:t=0,useSuffix:n=!1,customSuffix:r="",currency:s="",locale:o="en-US"}){let i=1,a=r,l=o;const u=t;n&&!r&&(e>=1e9?(i=1e9,a="B"):e>=1e7&&o==="en-IN"?(i=1e7,a="Cr"):e>=1e5&&o==="en-IN"?(i=1e5,a="L"):e>=1e6?(i=1e6,a="M"):e>=1e3&&(i=1e3,a="K"));const d=e/i,f={maximumFractionDigits:u,minimumFractionDigits:u,useGrouping:!0};if(s){f.style="currency",f.currency=s;try{new Intl.NumberFormat(o,f).format(0)}catch{}}try{new Intl.NumberFormat(o,f).format(0)}catch{l="en-US"}let m=new Intl.NumberFormat(l,f).format(d);return n&&(m+=a),m}function _C(e,t){if(!t)return"";const n=t.find(r=>e>=r.start&&e<=r.end);return(n==null?void 0:n.color)||""}const Qve=5,Jve=30,IE=5;function ewe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o,cardConfig:i,isDevMode:a=!1,card:l}){var I,$,V,W,L,R,z,F,A,H,B;if(!e||e.length===0)return{type:s,data:{labels:[],datasets:[]}};const u=r==null?void 0:r.bubbleScatterConfig,d=twe(e,u,i,a,s);if(!d.xKey||!d.yKey)return{type:s,data:{labels:[],datasets:[]}};const f=J.getState(),h=o??f.themeStyle,m=rwe(e,d,u,s),p=owe(m,h,r,s),g=ta(p,n),b=cwe(r),x=lD(s),y=($=(I=r==null?void 0:r.chartOptions)==null?void 0:I.plugins)==null?void 0:$.legend,v=xH(x,y),w=!!(y!=null&&y.labels||(L=(W=(V=t==null?void 0:t.options)==null?void 0:V.plugins)==null?void 0:W.legend)!=null&&L.labels||(F=(z=(R=n==null?void 0:n.options)==null?void 0:R.plugins)==null?void 0:z.legend)!=null&&F.labels);(y==null?void 0:y.display)===void 0&&(v.display=d.grouping.enabled);const j=dwe(l);let S=awe({resolvedKeys:d,formatConfig:b,preferences:r,cardType:s,legendConfig:v,hasCustomLegendLabels:w,hasDrillDown:j});S=aD(S,v);const{plugins:N=[],options:E}=Cu((r==null?void 0:r.customVisualCode)||""),_=r!=null&&r.chartOptions?{...r.chartOptions,plugins:{...r.chartOptions.plugins??{},legend:(y==null?void 0:y.display)!==void 0?(A=r.chartOptions.plugins)==null?void 0:A.legend:{...((H=r.chartOptions.plugins)==null?void 0:H.legend)??{},display:v.display}}}:void 0,k=uwe([S,t==null?void 0:t.options,_,n==null?void 0:n.options,E]),M=jr(((B=h==null?void 0:h.chart)==null?void 0:B.options)||{},k),T={type:s,data:{datasets:g},options:M,plugins:N},P=Vx(s,r),O=(r==null?void 0:r.dataLabelsConfig)??P;return T.options=Zm(T.options||{},O,r,s),T.options=Km.applyAxisConfig(T.options||{},s,r),T}function twe(e,t,n,r,s){var v,w;const{metricKeys:o,keys:i}=zn(e),a=Object.keys((e==null?void 0:e[0])||{}),l=a.length>0?a:i,u=r?[]:((v=n==null?void 0:n.metricColumns)==null?void 0:v.map(j=>j.label||j.name||j.alias).filter(Boolean))||[],d=u.length>0?u:o,f=l[0],h=(w=n==null?void 0:n.groupByColumns)==null?void 0:w[0],m=(h==null?void 0:h.label)||(h==null?void 0:h.name)||(h==null?void 0:h.alias),p=r?(t==null?void 0:t.labelKey)??f??i[0]:(t==null?void 0:t.labelKey)??m??i[0],g=nwe(t,n,r,l);let b,x,y;if(r){const j=1+(g.enabled&&g.groupKey?1:0),S=l.slice(j);b=(t==null?void 0:t.xMetricKey)??S[0],x=(t==null?void 0:t.yMetricKey)??S[1],y=s==="bubble"?(t==null?void 0:t.radiusMetricKey)??S[2]:void 0,b||(b=S[0]),x||(x=S[1]??S[0]),s==="bubble"&&!y&&(y=S[2]??S[1]??S[0])}else b=(t==null?void 0:t.xMetricKey)??d[0],x=(t==null?void 0:t.yMetricKey)??d[1],y=s==="bubble"?(t==null?void 0:t.radiusMetricKey)??d[2]:void 0;return{labelKey:p,xKey:b,yKey:x,radiusKey:y,grouping:g}}function nwe(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 rwe(e,t,n,r){const{labelKey:s,xKey:o,yKey:i,radiusKey:a,grouping:l}=t;let u=[];r==="bubble"&&a&&(u=e.map(x=>N0(x[a])).filter(x=>Number.isFinite(x)));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)??Qve,h=(n==null?void 0:n.maxRadius)??Jve,m=(n==null?void 0:n.radiusScale)??"sqrt",p=(n==null?void 0:n.fixedRadius)??IE,g=x=>{const y=N0(x[o]),v=N0(x[i]);if(!Number.isFinite(y)||!Number.isFinite(v))return null;let w;if(r==="scatter")w=p;else if(m==="fixed")w=p;else if(a){const S=N0(x[a]);if(!Number.isFinite(S))return null;w=swe(S,d,f,h,m)}else w=p;const j=E5(x[s]);return{x:y,y:v,r:w,label:j,meta:x}};if(l.enabled&&l.groupKey){const x=l.groupKey,y=new Map;for(const v of e){const w=E5(v[x]);y.has(w)||y.set(w,[]);const j=g(v);j&&y.get(w).push(j)}return Array.from(y.entries()).map(([v,w])=>({group:v,points:w}))}return[{group:"",points:e.map(g).filter(x=>x!==null)}]}function swe(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 owe(e,t,n,r){var u,d,f,h;const s=Df().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"],l=i.length>0?i:a;return e.map((m,p)=>{var y,v;if(!m.group&&e.length===1){const w=m.points.map((N,E)=>{var M,T;const k=((T=(M=n==null?void 0:n.colorConfig)==null?void 0:M.segments)==null?void 0:T[N.label])||a[E%a.length]||"#3b82f6";return _5(k,.8)}),j=m.points.map((N,E)=>{var k,M;return((M=(k=n==null?void 0:n.colorConfig)==null?void 0:k.segments)==null?void 0:M[N.label])||l[E%l.length]||"#3b82f6"}),S={label:void 0,data:m.points.map(N=>({x:N.x,y:N.y,r:N.r,label:N.label,meta:N.meta})),backgroundColor:w,borderColor:j,borderWidth:1};return r==="scatter"&&(S.pointRadius=((y=m.points[0])==null?void 0:y.r)??IE),S}const b=iwe({seriesKey:m.group,seriesIndex:p,preferences:n,backgroundPalette:a,borderPalette:l}),x={label:m.group||void 0,data:m.points.map(w=>({x:w.x,y:w.y,r:w.r,label:w.label,meta:w.meta})),backgroundColor:_5(b.backgroundColor,.8),borderColor:b.borderColor,borderWidth:1};return r==="scatter"&&(x.pointRadius=((v=m.points[0])==null?void 0:v.r)??IE),x})}function iwe({seriesKey:e,seriesIndex:t,preferences:n,backgroundPalette:r,borderPalette:s}){var l,u;const o=r[t%r.length]||r[0]||"#3b82f6",i=s[t%s.length]||s[0]||o,a=e&&((u=(l=n==null?void 0:n.colorConfig)==null?void 0:l.segments)==null?void 0:u[e])||void 0;return{backgroundColor:a||o,borderColor:a||i}}function awe({resolvedKeys:e,formatConfig:t,preferences:n,cardType:r,legendConfig:s,hasCustomLegendLabels:o,hasDrillDown:i}){var m,p,g,b,x,y,v,w;const a=((p=(m=n==null?void 0:n.xAxisConfig)==null?void 0:m.name)==null?void 0:p.enabled)??!1,l=((b=(g=n==null?void 0:n.yAxisConfig)==null?void 0:g.name)==null?void 0:b.enabled)??!1,u=((y=(x=n==null?void 0:n.xAxisConfig)==null?void 0:x.name)==null?void 0:y.text)||e.xKey,d=((w=(v=n==null?void 0:n.yAxisConfig)==null?void 0:v.name)==null?void 0:w.text)||e.yKey,f=!e.grouping.enabled&&!o;return{responsive:!0,maintainAspectRatio:!1,scales:{x:{type:"linear",position:"bottom",title:{display:a,text:u},ticks:{callback:j=>Bg(Number(j),"x",t,n)}},y:{type:"linear",position:"left",title:{display:l,text:d},ticks:{callback:j=>Bg(Number(j),"y",t,n)}}},plugins:{legend:{...s,...f?{labels:{generateLabels:hwe(e)}}:{}},tooltip:{displayColors:!1,callbacks:lwe(e,t,r,n,i)}}}}function lwe(e,t,n,r,s){return{title:o=>{if(!o.length)return"";const i=o[0],a=i.dataset.label,l=i.raw,u=l==null?void 0:l.label;return a&&u?`${a} (${u})`:u||a||""},label:o=>{const i=o.raw,a=[],l=Bg(i.x,"x",t,r),u=Bg(i.y,"y",t,r);if(a.push(`${e.xKey} (x): ${l}`),a.push(`${e.yKey} (y): ${u}`),n==="bubble"&&e.radiusKey){const d=i.meta;if(d&&e.radiusKey in d){const f=Bg(d[e.radiusKey],"y",t,r);a.push(`${e.radiusKey} (size): ${f}`)}}return s&&(a.push("─────────────────"),a.push("Click to drill")),a}}}function cwe(e){var a,l,u,d,f,h;const t=(l=(a=e==null?void 0:e.xAxisConfig)==null?void 0:a.formatOptions)==null?void 0:l.type,n=(d=(u=e==null?void 0:e.yAxisConfig)==null?void 0:u.formatOptions)==null?void 0:d.type,r=(t&&t!=="auto"?t:void 0)??(n&&n!=="auto"?n:void 0),s=e==null?void 0:e.numberAxisFormat,o=r??(s!=null&&s.currency?"currency":void 0)??"number",i=((f=e==null?void 0:e.xAxisConfig)==null?void 0:f.formatOptions)??((h=e==null?void 0:e.yAxisConfig)==null?void 0:h.formatOptions)??{decimalPlaces:s==null?void 0:s.decimalPlaces,prefix:"",suffix:s==null?void 0:s.suffix,currency:s==null?void 0:s.currency,locale:s==null?void 0:s.locale};return{format:o,options:i}}function N0(e){const t=Number(e);return Number.isFinite(t)?t:Number.NaN}function E5(e){return e==null||e===""?"(Blank)":String(e)}function uwe(e){return e.reduce((t,n)=>jr(t,n||{}),{})}function Bg(e,t,n,r){var i;const s=t==="x"?r==null?void 0:r.xAxisConfig:r==null?void 0:r.yAxisConfig,o=(i=s==null?void 0:s.formatOptions)==null?void 0:i.type;if(o&&o!=="auto")return Er(e,o,(s==null?void 0:s.formatOptions)||{});if(r!=null&&r.numberAxisFormat){const a=r.numberAxisFormat;return Js({number:e,decimalPlaces:a.decimalPlaces??0,useSuffix:!!a.suffix,customSuffix:a.suffix||"",locale:a.locale||"",currency:a.currency||""})}return Er(e,n.format,n.options)}function dwe(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 fwe(e){return/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(e.trim())}function _5(e,t){if(!e||!fwe(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),l=Math.round(t*255).toString(16).padStart(2,"0");return`#${o}${i}${a}${l}`}function hwe(e){return t=>{var l,u;const n=(u=(l=t==null?void 0:t.data)==null?void 0:l.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 mwe(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 pwe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var P,O,I,$,V,W,L;const i=((P=r==null?void 0:r.chartOptions)==null?void 0:P.indexAxis)||"y",a={...t,options:{indexAxis:i}},{keys:l}=zn(e),u=[l[1]],d=l==null?void 0:l[0],f=gV(u,e,r,d),h=ta(f,n);h.forEach((R,z)=>{var F,A,H,B,Y,q,U;R.shrinkAnchor=((H=(A=(F=n==null?void 0:n.data)==null?void 0:F.datasets)==null?void 0:A[z])==null?void 0:H.shrinkAnchor)||"top",R.shrinkFraction=((B=r==null?void 0:r.funnelConfig)==null?void 0:B.shrinkFraction)??((U=(q=(Y=n==null?void 0:n.data)==null?void 0:Y.datasets)==null?void 0:q[z])==null?void 0:U.shrinkFraction)??1});const{plugins:m,options:p}=Cu((r==null?void 0:r.customVisualCode)||""),g=l[0],b=nc(e,g),x=jr((a==null?void 0:a.options)||{},(n==null?void 0:n.options)||{}),y=jr(x,(r==null?void 0:r.chartOptions)||{}),v=(I=(O=y.plugins)==null?void 0:O.datalabels)==null?void 0:I.display;Array(h.length).fill(!0);const w=e.map(R=>R[g]),j=e.map(R=>R[u[0]]),S=($=h[0])==null?void 0:$.backgroundColor.slice(),N=R=>{var A,H,B,Y,q;const z=(Y=(B=(H=(A=R==null?void 0:R.chart)==null?void 0:A.data)==null?void 0:H.datasets)==null?void 0:B[(R==null?void 0:R.datasetIndex)||0])==null?void 0:Y.data;return((z&&z.length>0?z:(q=R==null?void 0:R.dataset)==null?void 0:q.data)??j).map(U=>Number(U))},E={...y,plugins:{...y.plugins,legend:{...(V=y.plugins)==null?void 0:V.legend,labels:{generateLabels:R=>{const z=R.data.labels;return w.map((F,A)=>({text:F,fillStyle:S[A],hidden:!z.includes(F.toString()),index:A,datasetIndex:0,lineWidth:0}))}},onClick:(R,z,F)=>{const A=F.chart,H=z.index,B=w[H],Y=A.data.datasets[0],q=A.data.labels,U=Y.data,G=Y.backgroundColor,Z=q.indexOf(B.toString());Z>=0?(q.splice(Z,1),U.splice(Z,1),G.splice(Z,1)):(q.splice(H,0,w[H].toString()),U.splice(H,0,Number(j[H])),G.splice(H,0,S[H])),A.update()}},datalabels:{...(W=y.plugins)==null?void 0:W.datalabels,display:function(R){var F;if(v===!1)return!1;if(typeof v=="function")return v(R);const z=(((F=r==null?void 0:r.funnelConfig)==null?void 0:F.labelThreshold)??0)/100;if(z>0){const A=N(R),H=A[R.dataIndex],B=A.reduce((q,U)=>q+U,0);return(B>0?H/B:0)>=z}return!0},anchor:R=>N(R)[R.dataIndex]<.02?"end":"start",align:R=>N(R)[R.dataIndex]<.02?"end":"center",textAlign:"center",font:{size:14},formatter:(R,z)=>{var F,A,H,B;return Js({number:Number(R),decimalPlaces:((F=r==null?void 0:r.numberAxisFormat)==null?void 0:F.decimalPlaces)||0,useSuffix:!!((A=r==null?void 0:r.numberAxisFormat)!=null&&A.suffix),customSuffix:"",locale:((H=r==null?void 0:r.numberAxisFormat)==null?void 0:H.locale)||"",currency:((B=r==null?void 0:r.numberAxisFormat)==null?void 0:B.currency)||""})}},tooltip:{...(L=y.plugins)==null?void 0:L.tooltip,callbacks:{title:function(R){var B,Y,q,U,G;const z=(Y=(B=R==null?void 0:R[0])==null?void 0:B.dataset)==null?void 0:Y.data,F=(q=R==null?void 0:R[0])==null?void 0:q.parsed[i==="x"?"y":"x"],A=((U=r==null?void 0:r.funnelConfig)==null?void 0:U.percentMode)??"percentOfTotal",H=mwe(F,z,A);return`${(G=R==null?void 0:R[0])==null?void 0:G.label} (${H}%)`},label:function(R){var U,G,Z,Q;R.dataset.label;const z=R.dataset.data;z.reduce((K,te)=>K+te,0);const F=R.parsed[i==="x"?"y":"x"],A=z.indexOf(F),H=z[A-1],B=Js({number:Number(F),decimalPlaces:((U=r==null?void 0:r.numberAxisFormat)==null?void 0:U.decimalPlaces)||0,useSuffix:!!((G=r==null?void 0:r.numberAxisFormat)!=null&&G.suffix),customSuffix:"",locale:((Z=r==null?void 0:r.numberAxisFormat)==null?void 0:Z.locale)||"",currency:((Q=r==null?void 0:r.numberAxisFormat)==null?void 0:Q.currency)||""});let Y=0;return H!==void 0&&(Y=Number((F/H*100).toFixed(2))),B+(H!==void 0?` | Conversion: ${Y}%`:"")},footer:function(R){var F,A,H,B;return(((A=(F=o==null?void 0:o.interactionConfig)==null?void 0:F.drillHierarchies)==null?void 0:A.length)??0)>0||(((B=(H=o==null?void 0:o.interactionConfig)==null?void 0:H.interactions)==null?void 0:B.some(Y=>Y.mode==="drillDown"||Y.mode==="drillToDetail"||Y.mode==="drillThrough"||Y.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},_=jr(y,E),k=r!=null&&r.dataLabelsConfig?Zm(_,r.dataLabelsConfig,r,"funnel"):_,M=jr(k,p);return delete M.scales,{type:s,data:{labels:b,datasets:h},options:M,plugins:[...m]}}function gwe({data:e,cfg:t,customCfg:n,preferences:r,card:s}){var S,N;const o=Gve(t),i=bwe(e),a=ta(i,n),{plugins:l,options:u}=Cu((r==null?void 0:r.customVisualCode)||""),d=jr((o==null?void 0:o.options)||{},(t==null?void 0:t.options)||{}),f=jr(d,(r==null?void 0:r.chartOptions)||{}),h=jr(f,(n==null?void 0:n.options)||{}),m={...h,plugins:{...h==null?void 0:h.plugins,tooltip:{...(S=h==null?void 0:h.plugins)==null?void 0:S.tooltip,callbacks:{label:function(E){if(Array.isArray(E.raw)&&E.raw.every(_=>_===null))return null},footer:function(E){var k,M,T,P;return(((M=(k=s==null?void 0:s.interactionConfig)==null?void 0:k.drillHierarchies)==null?void 0:M.length)??0)>0||(((P=(T=s==null?void 0:s.interactionConfig)==null?void 0:T.interactions)==null?void 0:P.some(O=>O.mode==="drillDown"||O.mode==="drillToDetail"||O.mode==="drillThrough"||O.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},p=jr(m,u),g=vH(t,r),b=jr(p,g);let x;r!=null&&r.dataLabelsConfig?x=Zm(b,r.dataLabelsConfig,r,"range"):x={...b,plugins:{...b==null?void 0:b.plugins,datalabels:{...(N=b==null?void 0:b.plugins)==null?void 0:N.datalabels,formatter:(E,_)=>E.map(M=>{var T,P,O,I;return Js({number:Number(M),decimalPlaces:((T=r==null?void 0:r.numberAxisFormat)==null?void 0:T.decimalPlaces)||0,useSuffix:!!((P=r==null?void 0:r.numberAxisFormat)!=null&&P.suffix),customSuffix:"",locale:((O=r==null?void 0:r.numberAxisFormat)==null?void 0:O.locale)||"",currency:((I=r==null?void 0:r.numberAxisFormat)==null?void 0:I.currency)||""})}).slice(0,2).join(" - ")}}};const{keys:y}=zn(e),v=y[0];return{type:"bar",data:{labels:[...new Set(nc(e,v))],datasets:a},options:x,plugins:[...l]}}function bwe(e){var h,m,p,g;const{keys:t}=zn(e),n=t.slice(0,2),r=t.slice(2),s=J.getState().themeStyle,o=(m=(h=s==null?void 0:s.chart)==null?void 0:h.dataset)==null?void 0:m.backgroundColor,i=(g=(p=s==null?void 0:s.chart)==null?void 0:p.dataset)==null?void 0:g.borderColor,a=n[1],l=n[0],u=[...new Set(e.map(b=>b==null?void 0:b[l]))];return[...new Set(e.map(b=>b==null?void 0:b[a]))].map((b,x)=>{const y=e.filter(j=>(j==null?void 0:j[a])===b),w=u.map(j=>{const S=y.filter(N=>(N==null?void 0:N[l])===j);return S.length===0?[[null,null,null]]:S.map(N=>[N==null?void 0:N[r[0]],N==null?void 0:N[r[1]],N==null?void 0:N[r[2]],j])}).flat();return{label:b,data:w,backgroundColor:o==null?void 0:o[x%o.length],borderColor:i==null?void 0:i[x%i.length],borderSkipped:!1}})}function xwe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var w;const i=Yve(t),{keys:a}=zn(e),l=Lx({dataArray:e,groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:u}=zn(l),d=u.slice(1),f=Gm(d,l,r),h=ta(f,n),m=u[0],p=nc(l,m),{options:g,plugins:b}=ou({cardType:s,cfg:i,preferences:r,customCfg:n,card:o}),x={type:(n==null?void 0:n.type)||(i==null?void 0:i.type)||"bar",data:{labels:p,datasets:h},options:g,plugins:b},y="x2";return{...x,data:{...x.data,datasets:x.data.datasets.map((j,S)=>S===1?{...j,xAxisID:y}:j)},options:{...x.options,scales:{...(w=x==null?void 0:x.options)==null?void 0:w.scales,[y]:{beginAtZero:!0,stack:1}}}}}const T5={type:"treemap",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function ywe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s}){var j;if(!e||e.length===0)return T5;const{dimensionKeys:o,metricKeys:i,keys:a}=zn(e),l=o.length>0?o:a.slice(0,1);let u=i[0];if(u||(u=a.find(S=>!l.includes(S))||i[0]||a[1]),!u)return console.warn("Treemap chart could not determine a metric column."),T5;const d=Swe(e,l,u),f=s??J.getState().themeStyle,h=((j=r==null?void 0:r.chartOptions)==null?void 0:j.treemapColorMode)??"branch",m=jwe(d,l,r,f),p=Nwe(r),g=vwe({tree:d,dimensionKeys:l,metricKey:u,colorLookups:m,formatConfig:p,themeStyle:f,preferences:r,colorMode:h}),b=wwe({dimensionKeys:l,metricKey:u,formatConfig:p}),{plugins:x,options:y}=Cu((r==null?void 0:r.customVisualCode)||""),v=Cwe([b,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,y]);return{type:"treemap",data:{datasets:[g]},options:v,plugins:x||[]}}function vwe({tree:e,dimensionKeys:t,metricKey:n,colorLookups:r,formatConfig:s,themeStyle:o,preferences:i,colorMode:a}){var m,p,g,b,x,y,v,w,j,S,N;const l=Vx("treemap",i),u=(i==null?void 0:i.dataLabelsConfig)??l,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:((g=(p=(m=o==null?void 0:o.chart)==null?void 0:m.dataset)==null?void 0:p.borderColor)==null?void 0:g[0])||"rgba(255,255,255,0.8)",labels:{display:d,align:"center",position:"middle",overflow:"fit",formatter:E=>{if(!d)return"";const _=E==null?void 0:E.raw,k=bU(_,t),M=Number((_==null?void 0:_.v)??0),T=xU(M,s);return k?`${k}
|
|
753
|
-
${T}`:T},color:E=>{if(f)return f;const _=E==null?void 0:E.raw,k=M5({raw:_,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a});return wo(k)},font:{size:((x=(b=o==null?void 0:o.chart)==null?void 0:b.font)==null?void 0:x.size)||((y=u==null?void 0:u.font)==null?void 0:y.size)||12,weight:((w=(v=o==null?void 0:o.chart)==null?void 0:v.font)==null?void 0:w.weight)||((j=u==null?void 0:u.font)==null?void 0:j.weight)||"bold",family:((N=(S=o==null?void 0:o.chart)==null?void 0:S.font)==null?void 0:N.family)||"Inter"}},backgroundColor:E=>{const _=E==null?void 0:E.raw;return M5({raw:_,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a})}}}function wwe({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 Ewe(o==null?void 0:o.raw,e)},label:s=>{const o=s==null?void 0:s.raw,i=bU(o,e),a=Number((o==null?void 0:o.v)??0),l=xU(a,n),u=t||"Value";return i?`${i} — ${u}: ${l}`:`${u}: ${l}`}}}}}}function Cwe(e){return e.reduce((t,n)=>jr(t,n||{}),{})}function Swe(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 jwe(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))??Df();return t.map((l,u)=>{const d=new Map;return u>0||Array.from(new Set(e.map(h=>h[l]).filter(h=>!!h))).forEach((h,m)=>{var p,g;if((g=(p=n==null?void 0:n.colorConfig)==null?void 0:p.segments)!=null&&g[h]){d.set(h,n.colorConfig.segments[h]);return}d.set(h,s[m%s.length])}),d})}function Nwe(e){var i,a,l;const t=((i=e==null?void 0:e.dataLabelsConfig)==null?void 0:i.format)||((a=e==null?void 0:e.numberAxisFormat)==null?void 0:a.format)||"number",n=t&&t!=="none"?t:"number",r=((l=e==null?void 0:e.dataLabelsConfig)==null?void 0:l.formatOptions)||(e==null?void 0:e.numberAxisFormat)||(e==null?void 0:e.formatNumber)||{},s=["decimalPlaces","currency","locale","useSuffix","prefix","suffix","negativeInParentheses","multiplyBy"],o=Object.fromEntries(Object.entries(r).filter(([u])=>s.includes(u)));return{format:n,formatOptions:o}}function bU(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 kwe(e._data,t);if(e.path){const r=e.path.split("."),s=r[r.length-1];if(s)return s}return""}function kwe(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 Ewe(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 xU(e,t){return Er(e,t.format,t.formatOptions)}function M5({raw:e,dimensionKeys:t,colorLookups:n,themeStyle:r,preferences:s,colorMode:o}){var p,g,b,x,y,v,w;if(!e)return"#999999";const i=((b=(g=(p=r==null?void 0:r.chart)==null?void 0:p.dataset)==null?void 0:g.backgroundColor)==null?void 0:b.filter(Boolean))??Df(),a=_we(e,t),l=a[0]||((x=e._data)==null?void 0:x[t[0]])||e.g||"",u=((v=(y=s==null?void 0:s.colorConfig)==null?void 0:y.segments)==null?void 0:v[l])||((w=n[0])==null?void 0:w.get(l))||i[0]||"#999999",d=Math.max(t.length-1,0),f=typeof e.l=="number"?e.l:a.length-1,h=CD(f,0,d);if(h===0||o==="category")return u;const m=Twe(e);return Mwe(u,m,h)}function _we(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 Twe(e){if(!e)return 1;const t=Number(e.v??0),n=Number(e.gs??e.s??0);return n>0&&Number.isFinite(t)?CD(t/n,0,1):1}function Mwe(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=D5(e,"#ffffff",o);return a=D5(a,"#000000",i),a}function D5(e,t,n){const r=CD(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=I5(e),o=I5(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),l=Math.round(s.b+(o.b-s.b)*r);return Dwe(i,a,l)}function I5(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 Dwe(e,t,n){const r=s=>s.toString(16).padStart(2,"0");return`#${r(nN(e))}${r(nN(t))}${r(nN(n))}`}function nN(e){return Math.min(255,Math.max(0,Math.round(e)))}function CD(e,t,n){return Math.max(t,Math.min(n,e))}function yU(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 Iwe(e,t,n){var i;if(e==null)return"";const r=Number(e);if(isNaN(r))return String(e);const s=t.format||"auto",o=t.formatOptions||{};switch(s){case"currency":return Er(r,"currency",{currency:o.currency||"USD",decimalPlaces:o.decimalPlaces??2,useSuffix:o.useSuffix,locale:o.locale});case"number":return Er(r,"number",{decimalPlaces:o.decimalPlaces??0,useSuffix:o.useSuffix,locale:o.locale});case"percent":return Er(r,"percent",{decimalPlaces:o.decimalPlaces??1,locale:o.locale});case"none":return String(e);case"auto":default:return(i=n==null?void 0:n.formatOptions)!=null&&i.type&&n.formatOptions.type!=="auto"?Er(r,n.formatOptions.type,n.formatOptions):String(e)}}function TC(e,t,n){var h,m;if(!(e.enabled??!1))return{display:!1};const s=e.position||"auto";let o,i;if(s==="custom")o=e.anchor||"center",i=e.align||"center";else{const g=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"}},b=g[s]||g.auto;o=b.anchor,i=b.align}const a=e.color,l=p=>{var b,x,y;if(a&&a!=="auto")return a;if(s!=="center"||n==="line"||n==="area")return wo(Hi());const g=((x=(b=p.dataset)==null?void 0:b.backgroundColor)==null?void 0:x[p.dataIndex])||((y=p.dataset)==null?void 0:y.backgroundColor)||Hi();return wo(g)},u=((h=e.font)==null?void 0:h.size)||11,d=((m=e.font)==null?void 0:m.weight)||"normal",f=e.rotation||0;return{display:e.display==="auto"?"auto":!0,formatter:p=>Iwe(p,e,t),anchor:o,align:i,color:l,font:{size:u,weight:d},rotation:f,clamp:e.clamp??!0,clip:e.clip??!1,offset:e.offset??4}}function MC(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 SD(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 DC(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 Rwe(e,t){return Array.from({length:e},(n,r)=>({idx:r,fill:t&&r>0?"-1":"origin"}))}function Awe(e,t,n){const r=Rwe(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 Pwe(e,t,n,r){const s=n==null?void 0:n.lineStyleConfig,o=n==null?void 0:n.yAxisConfig;return e.map((i,a)=>{const l=t.find(m=>m.idx===a),u={...i};u.type="line",u.fill=(l==null?void 0:l.fill)??"origin",u.borderWidth=u.borderWidth??2,u.tension=u.tension??.1,u.pointRadius=(l==null?void 0:l.pointRadius)??(s==null?void 0:s.pointRadius)??3,u.pointStyle=(l==null?void 0:l.pointStyle)??(s==null?void 0:s.pointStyle)??"circle";const d=(l==null?void 0:l.pointRadius)??(s==null?void 0:s.pointRadius)??3;u.pointHoverRadius=(l==null?void 0:l.pointHoverRadius)??d+2,u.borderDash=SD((l==null?void 0:l.lineStyle)??(s==null?void 0:s.lineStyle));const f=u.borderColor||u.backgroundColor;f&&typeof f=="string"&&(u.backgroundColor=yU(f,.5));const h=DC(n==null?void 0:n.dataLabelsConfig,l==null?void 0:l.dataLabels);return h&&(u.datalabels=TC(h,o,"area")),u})}function Owe(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 Fwe({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var j,S;const{keys:i}=zn(t),a=vb(i),l=a.length,u=o==="stackedArea",d=Awe(s==null?void 0:s.datasetOptions,l,u),f=i==null?void 0:i[0],h=nc(t,f),m=Gm(a,t,s,1,"none",f,!1,Ym(t)),p=Pwe(m,d,s),g=ta(p,r),{options:b,plugins:x}=ou({cardType:o||"area",cfg:n,preferences:s,customCfg:r,card:e}),y=Owe(b==null?void 0:b.scales,u),v={...b,scales:y},w=(((S=(j=e.interactionConfig)==null?void 0:j.interactions)==null?void 0:S.length)??0)>0;return MC(v,w),{type:"line",data:{labels:h,datasets:g},options:v,plugins:x}}const vU=["poor","satisfactory","good"],rN={poor:"Poor",satisfactory:"Average",good:"Good"},$we=["#F5F6F8","#E3E6EC","#CED4DD"],Lwe=["#1F2933","#27323D","#303B47"];function zwe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s}){var le,de,ce,Ce,ge,he,me;if(!e||e.length===0)return{type:"bar",data:{labels:[],datasets:[]}};const{dimensionKeys:o,metricKeys:i,keys:a}=zn(e),l=o[0]??a[0];if(!l)return{type:"bar",data:{labels:[],datasets:[]}};const u=i[0]??a.find(oe=>oe!==l);if(!u)return{type:"bar",data:{labels:[],datasets:[]}};const d=r==null?void 0:r.bulletConfig,f=(d==null?void 0:d.targetMetricKey)??i.find(oe=>oe!==u),h=(d==null?void 0:d.comparativeMetricKey)??(d!=null&&d.disableAutoComparative?void 0:i.find(oe=>oe!==u&&oe!==f)),m=J.getState(),p=s??m.themeStyle,g=m.theme==="dark",b=Bwe({data:e,dimensionKey:l,actualKey:u,targetKey:f,comparativeKey:h,bulletConfig:d}),x=b.map(oe=>oe.label),y=(d==null?void 0:d.showRanges)??t1e(d),v=Uwe(b,y),w=(le=r==null?void 0:r.chartOptions)==null?void 0:le.indexAxis,S=(w?w==="y"?"horizontal":"vertical":void 0)??(d==null?void 0:d.orientation)??"horizontal",N=S==="vertical"?"x":"y",E=r?{...r,chartOptions:{...r.chartOptions||{},indexAxis:N}}:{chartOptions:{indexAxis:N}},_=Qwe(r),k=e1e(d),M=Jwe(g),T=Df().filter(Boolean),P=(((ce=(de=p==null?void 0:p.chart)==null?void 0:de.dataset)==null?void 0:ce.backgroundColor)||[]).filter(Boolean),O=(((ge=(Ce=p==null?void 0:p.chart)==null?void 0:Ce.dataset)==null?void 0:ge.borderColor)||[]).filter(Boolean),I=P.length>0?P:T.length>0?T:["#3b82f6"],$=O.length>0?O:I.length>0?I:["#111827"],V=oN({metricKey:u,metricIndex:0,preferences:r,backgroundPalette:I,borderPalette:$}),L=oN({metricKey:f||`${u}__target`,metricIndex:1,preferences:r,backgroundPalette:I,borderPalette:$}).borderColor||V.borderColor||"#111827",R=oN({metricKey:h,metricIndex:2,preferences:r,backgroundPalette:I,borderPalette:$}),z=y?Wwe(b,M,S,g,k):[],F=qwe(b,V,S,u),A=Ywe(b,R,S,h),H=[...z,F];A&&H.push(A);let B=Gwe({orientation:S,chartMax:v,formatConfig:_,series:b,preferences:E,rangeLabelMap:k,showRanges:y});const Y=(me=(he=r==null?void 0:r.chartOptions)==null?void 0:he.plugins)==null?void 0:me.legend;B=aD(B,Y);const{plugins:q=[],options:U}=Cu((r==null?void 0:r.customVisualCode)||""),G=o1e([B,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,U]),Z=b.some(oe=>oe.target!=null)&&v>0?Xwe({series:b,orientation:S,color:L}):null,Q={type:"bar",data:{labels:x,datasets:H},options:G,plugins:Z?[...q,Z]:q},K=Vx("bullet",r),te=(r==null?void 0:r.dataLabelsConfig)??K;return Q.options=Zm(Q.options||{},te,E,"bar"),Q.options=Km.applyAxisConfig(Q.options||{},"bar",E),Q.options=Q.options||{},Q.options.indexAxis=N,Q}function Bwe({data:e,dimensionKey:t,actualKey:n,targetKey:r,comparativeKey:s,bulletConfig:o}){const i=e.map(l=>{const u=Hwe(l[t]),d=Iv(l[n]),f=r&&l[r]!=null?Iv(l[r]):(o==null?void 0:o.targetValue)??null,h=s&&l[s]!=null?Iv(l[s]):null;return{label:u,actual:d,target:f,comparative:h,row:l}}),a=i.reduce((l,u)=>{var d;return Math.max(l,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(l=>{const u=Vwe({row:l.row,actual:l.actual,target:l.target,globalMax:a||l.actual||1,bulletConfig:o});return{label:l.label,actual:l.actual,target:l.target??void 0,comparative:l.comparative??void 0,ranges:u,actualKey:n,targetKey:r||void 0}})}function Vwe({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),l={poor:sN("poor",e,o,i,a*.5,s,a),satisfactory:sN("satisfactory",e,o,i,a*.8,s,a),good:sN("good",e,o,i,a,s,a)};let u=0;return vU.forEach(d=>{const f=l[d];if(!Number.isFinite(f)||f<0){l[d]=u;return}f<u?l[d]=u:u=f}),l}function sN(e,t,n,r,s,o,i){const a=n==null?void 0:n[e];if(a&&t[a]!=null)return Iv(t[a]);if((r==null?void 0:r[e])!=null){const l=r[e];return o!=null&&o.rangesArePercentages?l*i:l}return s}function Iv(e){const t=Number(e);return Number.isFinite(t)?t:0}function Hwe(e){return e==null||e===""?"(Blank)":String(e)}function Uwe(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 Wwe(e,t,n,r,s){const o=[];return vU.forEach((i,a)=>{const l=[],u=e.map(f=>{const h=f.ranges[i];return l.push({start:0,end:h}),h}),d={type:"bar",label:s[i],data:u,order:10,backgroundColor:r1e(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:l};o.push(d)}),o}function qwe(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 Ywe(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 Gwe({orientation:e,chartMax:t,formatConfig:n,series:r,preferences:s,rangeLabelMap:o,showRanges:i}){var f,h,m,p,g,b,x,y,v;const a={type:"linear",stacked:!1,beginAtZero:!0,suggestedMax:t,ticks:{callback:w=>Er(Number(w),n.format,n.options)},grid:{drawOnChartArea:!0}},l={type:"category",stacked:!0,grid:{display:!1}};return{responsive:!0,maintainAspectRatio:!1,scales:{x:e==="vertical"?l:a,y:e==="vertical"?a:l},plugins:{legend:{display:((m=(h=(f=s==null?void 0:s.chartOptions)==null?void 0:f.plugins)==null?void 0:h.legend)==null?void 0:m.display)??!0,position:((b=(g=(p=s==null?void 0:s.chartOptions)==null?void 0:p.plugins)==null?void 0:g.legend)==null?void 0:b.position)??"top",align:((v=(y=(x=s==null?void 0:s.chartOptions)==null?void 0:x.plugins)==null?void 0:y.legend)==null?void 0:v.align)??"center"},tooltip:{filter:w=>{const j=w.dataset.customRole;return j?j!=="range":!0},callbacks:Kwe(r,n,o,i)}},indexAxis:e==="vertical"?"x":"y"}}function Kwe(e,t,n,r){return{title:s=>{var o;return s.length?((o=e[s[0].dataIndex])==null?void 0:o.label)??"":""},label:s=>{const o=e[s.dataIndex];return o?`${o.actualKey||"Actual"}: ${Er(o.actual,t.format,t.options)}`:s.formattedValue},afterBody:s=>{if(!s.length)return[];const o=e[s[0].dataIndex];if(!o)return[];const i=[];if(o.target!=null){const u=Er(o.target,t.format,t.options),d=o.actual-o.target,f=Er(d,t.format,t.options),h=o.targetKey||"Target";i.push(`${h}: ${u} (${f})`)}const a=Zwe(o,n);r&&a&&i.push(`Range: ${a}`);const l=o.comparative;return l!=null&&i.push(`Comparative: ${Er(l,t.format,t.options)}`),i}}}function Zwe(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 Xwe({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,l=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 b,x,y,v,w;if(d.target==null)return;const h=(b=r.data.labels)==null?void 0:b[f],m=((y=(x=r.getDatasetMeta(u>=0?u:l>=0?l:0))==null?void 0:x.data)==null?void 0:y[f])||((w=(v=r.getDatasetMeta(0))==null?void 0:v.data)==null?void 0:w[f]),p=m?t==="horizontal"?m.height??m.width??20:m.width??m.height??20:20,g=Math.max(Math.min(p/2,12),6);if(t==="horizontal"){const j=o.getPixelForValue(d.target),S=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(j,S-g),s.lineTo(j,S+g),s.stroke(),s.beginPath(),s.moveTo(j-4,S-g),s.lineTo(j+4,S-g),s.moveTo(j-4,S+g),s.lineTo(j+4,S+g),s.stroke()}else{const j=o.getPixelForValue(d.target),S=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(S-g,j),s.lineTo(S+g,j),s.stroke(),s.beginPath(),s.moveTo(S-g,j-4),s.lineTo(S-g,j+4),s.moveTo(S+g,j-4),s.lineTo(S+g,j+4),s.stroke()}}),s.restore()}}}function Qwe(e){var r,s,o;const t=((r=e==null?void 0:e.dataLabelsConfig)==null?void 0:r.format)??((s=e==null?void 0:e.numberAxisFormat)==null?void 0:s.format)??"number",n=((o=e==null?void 0:e.dataLabelsConfig)==null?void 0:o.formatOptions)??(e==null?void 0:e.numberAxisFormat)??(e==null?void 0:e.formatNumber)??{};return{format:t==="none"?"number":t,options:n}}function Jwe(e){return[...e?Lwe:$we]}function e1e(e){var n,r,s;const t=(e==null?void 0:e.rangeLabels)||{};return{poor:((n=t.poor)==null?void 0:n.trim())||rN.poor,satisfactory:((r=t.satisfactory)==null?void 0:r.trim())||rN.satisfactory,good:((s=t.good)==null?void 0:s.trim())||rN.good}}function t1e(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 n1e(e,t,n){const r=wU(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=R5(e),o=R5(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),l=Math.round(s.b+(o.b-s.b)*r);return s1e(i,a,l)}function r1e(e,t,n){return n1e(e,n?"#000000":"#ffffff",t)}function oN({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 R5(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 s1e(e,t,n){return`#${iN(e)}${iN(t)}${iN(n)}`}function iN(e){return wU(Math.round(e),0,255).toString(16).padStart(2,"0")}function wU(e,t,n){return Math.max(t,Math.min(n,e))}function o1e(e){return e.reduce((t,n)=>jr(t,n||{}),{})}const RE={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"}},CU=["#dcfce7","#15803d"],k0={type:"matrix",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function i1e({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o}){var B,Y,q;if(!Array.isArray(e)||e.length===0)return k0;const{dimensionKeys:i,metricKeys:a,keys:l}=zn(e),u=i[0]??l[0];if(!u)return k0;const d=i[1],f=l.find(U=>U!==u&&!a.includes(U)&&U!==d)??d,h=!d&&(!f||typeof((B=e[0])==null?void 0:B[f])!="string")&&a.length>1,m=a[0]??l.find(U=>U!==u&&U!==f);if(!m&&!h)return k0;const p=r==null?void 0:r.heatmapConfig,g=(p==null?void 0:p.legendPosition)??"bottom",b=h?l1e({data:e,dimensionKey:u,metricKeys:a}):a1e({data:e,xKey:u,yKey:f||m,metricKey:m});if(b.length===0)return k0;const x=h?a.map(gm):aN(b.map(U=>U.x)),y=aN(h?e.map(U=>gm(U==null?void 0:U[u])):b.map(U=>U.y)),v=c1e(b),w=o??J.getState().themeStyle,j=p1e({min:v.min,max:v.max,heatmapConfig:p,themeStyle:w}),S=u1e({points:b,xLabels:x,yLabels:y,fill:(p==null?void 0:p.fillMissingCells)!==!1}),N=v1e(r),_=["auto","number","currency","percent","none"].includes(N.format)?N.format:"auto",k=Vx("heatmap",r),M=k?{...k,format:k.format??_,formatOptions:k.formatOptions??N.options}:void 0,T=(r==null?void 0:r.dataLabelsConfig)??M,P=d1e({points:S,xLabels:x,yLabels:y,colorScale:j,datasetLabel:h?"Value":m||"Value",dataLabelPrefs:T,formatConfig:N}),O=f1e({xLabels:x,yLabels:y,heatmapConfig:p,formatConfig:N,themeStyle:w,legendPreferences:(q=(Y=r==null?void 0:r.chartOptions)==null?void 0:Y.plugins)==null?void 0:q.legend,cardType:s,legendPosition:g}),{plugins:I=[],options:$}=Cu((r==null?void 0:r.customVisualCode)||""),V=w1e([O,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,$]),W=(p==null?void 0:p.showLegend)===!1?null:g1e({stops:j.stops,min:v.min,max:v.max,formatConfig:N,position:g}),L={type:"matrix",data:{datasets:[P]},options:V,plugins:W?[...I,W]:I};L.options=Zm(L.options||{},T,r,"matrix");const R=Qk(s??"heatmap","x"),z=Qk(s??"heatmap","y"),F=Jk(R,r==null?void 0:r.xAxisConfig),A=Jk(z,r==null?void 0:r.yAxisConfig),H=F||A||r?{...r||{},...F?{xAxisConfig:F}:{},...A?{yAxisConfig:A}:{}}:r;return L.options=Km.applyAxisConfig(L.options||{},"heatmap",H),L}function a1e({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 l=gm(i),u=gm(a),d=`${l}__${u}`,f=SU(o==null?void 0:o[r]);if(!s.has(d)){s.set(d,{x:l,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 l1e({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=gm(o);n.forEach(a=>{if(a===t)return;const l=SU(s==null?void 0:s[a]),u=gm(a);r.push({x:u,y:i,v:l,raw:{...s,_metricKey:a}})})}),r}function gm(e){return e==null||e===""?"Unknown":String(e)}function SU(e){const t=Number(e);return Number.isFinite(t)?t:null}function aN(e){const t=new Set,n=[];return e.forEach(r=>{t.has(r)||(t.add(r),n.push(r))}),n}function c1e(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 u1e({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 l=`${i}__${a}`,u=s.get(l);u?o.push(u):o.push({x:i,y:a,v:null})})}),o}function d1e({points:e,xLabels:t,yLabels:n,colorScale:r,datasetLabel:s,dataLabelPrefs:o,formatConfig:i}){const a=Zxe(e.length,o),l=Math.max(t.length||1,n.length||1);return{label:s,data:e,backgroundColor:d=>{const f=d==null?void 0:d.raw;return r.getColor((f==null?void 0:f.v)??null)},hoverBackgroundColor:d=>{const f=d==null?void 0:d.raw,h=r.getColor((f==null?void 0:f.v)??null);return y1e(h,.85)},borderWidth:1,borderColor:"rgba(255, 255, 255, 0.65)",width:({chart:d})=>{var f;return A5((f=d==null?void 0:d.chartArea)==null?void 0:f.width,t.length)},height:({chart:d})=>{var f;return A5((f=d==null?void 0:d.chartArea)==null?void 0:f.height,n.length)},datalabels:{display:a,anchor:"center",align:"center",formatter:d=>{let f=null;return typeof d=="number"?f=d:d&&typeof d=="object"&&"v"in d&&(f=Number(d.v)),f==null||Number.isNaN(f)?"":jD(f,i??{format:"number",options:{}})},color:d=>{const f=d==null?void 0:d.raw,h=r.getColor((f==null?void 0:f.v)??null)||"rgba(148,163,184,0.35)";return wo(x1e(h))},font:{size:Math.max(10,Math.min(14,120/l))}}}}function A5(e,t){return!e||t===0?0:Math.max(4,e/t-2)}function f1e({xLabels:e,yLabels:t,heatmapConfig:n,formatConfig:r,themeStyle:s,legendPreferences:o,cardType:i,legendPosition:a}){var m,p,g;const l=(n==null?void 0:n.showLegend)??!0,u=((g=(p=(m=s==null?void 0:s.chart)==null?void 0:m.options)==null?void 0:p.plugins)==null?void 0:g.tooltip)||{},d=lD(i??"heatmap"),f=xH(d,o);return{responsive:!0,maintainAspectRatio:!1,layout:{padding:h1e(l,a)},plugins:{legend:f,tooltip:{...u,filter:b=>{const x=b==null?void 0:b.raw;return(x==null?void 0:x.v)!=null&&x.v!==0},callbacks:m1e(r)}},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 h1e(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 m1e(e){return{title(t){var r;const n=(r=t==null?void 0:t[0])==null?void 0:r.raw;return n&&(n.y||n.x)||""},label(t){var i;const n=t==null?void 0:t.raw;if(!n||n.v==null)return"";const r=((i=t==null?void 0:t.dataset)==null?void 0:i.label)||n.x||"Value",s=n.x,o=jD(n.v,e);return s?`${s}: ${o}`:`${r}: ${o}`}}}function p1e({min:e,max:t,heatmapConfig:n,themeStyle:r}){var y,v;const s=((v=(y=r==null?void 0:r.chart)==null?void 0:y.dataset)==null?void 0:v.backgroundColor)||[],o=["#0ea5e9","#f97316"],i=(n==null?void 0:n.colorPalette)??"green",a=i!=="custom"?RE[i]??RE.blue:void 0,l=n==null?void 0:n.colorRange,u=l&&l[0]&&l[1]?l:a?[a.start,a.end]:i==="custom"?CU: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",m=Math.max(3,(n==null?void 0:n.steps)??5),p=(n==null?void 0:n.nullFillColor)??"rgba(148, 163, 184, 0.25)",g=Math.max(t-e,Number.EPSILON),b=h==="continuous"?[{offset:0,color:Uu(d)},{offset:1,color:Uu(f)}]:Array.from({length:m}).map((w,j)=>{const S=m===1?0:j/(m-1||1);return{offset:S,color:P5(Uu(d),Uu(f),S)}}),x=h==="continuous"?null:b.map(w=>w.color);return{getColor(w){if(w==null||w===0)return p;if(h==="continuous"){const N=Db((w-e)/g,0,1);return P5(Uu(d),Uu(f),N)}const j=Db((w-e)/g,0,1),S=Math.min(m-1,Math.max(0,Math.floor(j*m)));return(x==null?void 0:x[S])??Uu(d)},stops:b}}function g1e({stops:e,min:t,max:n,formatConfig:r,position:s}){if(!e||e.length===0)return null;const o=i=>jD(i,r);return{id:"heatmapLegend",afterDraw(i){var p,g,b,x;const{ctx:a,chartArea:l}=i;if(!a||!l)return;a.save();const u=((x=(b=(g=(p=i.options)==null?void 0:p.plugins)==null?void 0:g.legend)==null?void 0:b.labels)==null?void 0:x.font)||{},d=u.size??12,f=u.family??"sans-serif",h=wo(Hi()),m=24;if(a.font=`${d}px ${f}`,a.fillStyle=h,s==="bottom"||s==="top"){const v=l.left,w=l.right,j=s==="bottom"?l.bottom+m/2:l.top-10-m/2,S=a.createLinearGradient(v,0,w,0);e.forEach(E=>S.addColorStop(E.offset,E.color)),a.fillStyle=S,a.fillRect(v,j,w-v,10),a.fillStyle=h,a.textAlign="left",a.textBaseline=s==="bottom"?"top":"bottom";const N=s==="bottom"?j+10+4:j-4;a.fillText(o(t),v,N),a.textAlign="center",a.fillText(o(t+(n-t)/2),(v+w)/2,N),a.textAlign="right",a.fillText(o(n),w,N)}else{const v=l.top,w=l.bottom,j=s==="left"?l.left-10-m/2:l.right+m/2,S=a.createLinearGradient(0,v,0,w);e.forEach(E=>S.addColorStop(E.offset,E.color)),a.fillStyle=S,a.fillRect(j,v,10,w-v),a.fillStyle=h,a.textAlign=s==="left"?"right":"left",a.textBaseline="middle";const N=s==="left"?j-6:j+10+6;a.fillText(o(n),N,v),a.fillText(o(t+(n-t)/2),N,(v+w)/2),a.fillText(o(t),N,w)}a.restore()}}}function Uu(e){if(!e)return"#3b82f6";if(e.startsWith("rgb"))return e;if(e.startsWith("#")){const t=jU(e);return t?b1e(t.r,t.g,t.b,1):e}return e}function P5(e,t,n){const r=Aw(e),s=Aw(t);if(!r||!s)return e;const o=Db(n,0,1),i=Math.round(r.r+(s.r-r.r)*o),a=Math.round(r.g+(s.g-r.g)*o),l=Math.round(r.b+(s.b-r.b)*o),u=r.a+(s.a-r.a)*o;return`rgba(${i}, ${a}, ${l}, ${u})`}function Aw(e){if(e.startsWith("#")){const n=jU(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 jU(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 b1e(e,t,n,r){return`rgba(${e}, ${t}, ${n}, ${r})`}function x1e(e){const t=Aw(e);return t?`#${lN(t.r)}${lN(t.g)}${lN(t.b)}`:"#000000"}function lN(e){return Db(Math.round(e),0,255).toString(16).padStart(2,"0")}function y1e(e,t){const n=Aw(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${Db(t,0,1)})`:e}function Db(e,t,n){return Math.min(n,Math.max(t,e))}function jD(e,t){return e==null||Number.isNaN(e)?"—":Er(e,t.format,t.options)}function v1e(e){var r,s,o;const t=((r=e==null?void 0:e.dataLabelsConfig)==null?void 0:r.format)??((s=e==null?void 0:e.numberAxisFormat)==null?void 0:s.format)??"number",n=((o=e==null?void 0:e.dataLabelsConfig)==null?void 0:o.formatOptions)??(e==null?void 0:e.numberAxisFormat)??(e==null?void 0:e.formatNumber)??{};return{format:!t||t==="none"?"number":t,options:n}}function w1e(e){return e.reduce((t,n)=>n?Jh({},t,n):t,{})}function AE(){return{enabled:!0,position:"right",labels:{enabled:!0,rotation:"auto"},name:{enabled:!1}}}function C1e(e){return Array.from({length:e},(t,n)=>({idx:n,type:"bar",yAxisId:"y"}))}function S1e(e){return!e||e.length===0?!1:e.some(t=>t.yAxisId==="y2")}function j1e(e,t){var r,s,o,i,a,l,u,d,f,h,m,p,g,b;if(!t)return e||AE();const n=AE();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:((l=t==null?void 0:t.name)==null?void 0:l.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)??((m=e==null?void 0:e.labels)==null?void 0:m.enabled)??((p=n.labels)==null?void 0:p.enabled)??!0,rotation:((g=t==null?void 0:t.labels)==null?void 0:g.rotation)??((b=e==null?void 0:e.labels)==null?void 0:b.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 N1e(e,t){const n=C1e(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 k1e(e,t,n){const r=n==null?void 0:n.yAxisConfig,s=n==null?void 0:n.secondaryYAxisConfig,o=n==null?void 0:n.dataLabelsConfig;return e.map((i,a)=>{const l=t.find(p=>p.idx===a),u={...i},d=(l==null?void 0:l.type)||"bar";u.type=d;const f=(l==null?void 0:l.fill)!==void 0&&(l==null?void 0:l.fill)!=="";if(d==="line"){if(u.borderWidth=u.borderWidth??2,u.tension=u.tension??.1,u.pointRadius=(l==null?void 0:l.pointRadius)??3,u.pointStyle=(l==null?void 0:l.pointStyle)??"circle",u.pointHoverRadius=(l==null?void 0:l.pointHoverRadius)??((l==null?void 0:l.pointRadius)??3)+2,u.borderDash=SD(l==null?void 0:l.lineStyle),f){const p=u.borderColor||u.backgroundColor;p&&typeof p=="string"&&(u.backgroundColor=yU(p,.3)),u.fill=l.fill}u.order=0}else u.order=1;l!=null&&l.yAxisId&&(u.yAxisID=l.yAxisId);const h=(l==null?void 0:l.yAxisId)==="y2"?s:r,m=DC(o,l==null?void 0:l.dataLabels);return m&&(u.datalabels=TC(m,h,d==="line"?"line":"bar")),u})}function E1e(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 l=j1e(AE(),n==null?void 0:n.secondaryYAxisConfig);r.y2={...e==null?void 0:e.y2,type:"linear",display:l.enabled!==!1,position:l.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=l.labels)==null?void 0:i.enabled)!==!1},title:(a=l.name)!=null&&a.enabled?{display:!0,text:l.name.text||"",font:{size:l.name.fontSize||12,weight:l.name.fontWeight||"normal"}}:void 0},l.scale&&(l.scale.min!==void 0&&l.scale.min!=="auto"&&(r.y2.min=l.scale.min),l.scale.max!==void 0&&l.scale.max!=="auto"&&(r.y2.max=l.scale.max),l.scale.stepSize!==void 0&&l.scale.stepSize!=="auto"&&(r.y2.ticks={...r.y2.ticks,stepSize:l.scale.stepSize}))}return r}function _1e({card:e,data:t,cfg:n,customCfg:r,preferences:s}){var w,j;const{keys:o}=zn(t),i=vb(o),a=i.length,l=N1e(s==null?void 0:s.datasetOptions,a),u=S1e(l),d=o==null?void 0:o[0],f=nc(t,d),h=Gm(i,t,s,1,"none",d,!1,Ym(t)),m=k1e(h,l,s),p=ta(m,r),{options:g,plugins:b}=ou({cardType:"combo",cfg:n,preferences:s,customCfg:r,card:e}),x=E1e(g==null?void 0:g.scales,u,s),y={...g,scales:x},v=(((j=(w=e.interactionConfig)==null?void 0:w.interactions)==null?void 0:j.length)??0)>0;return MC(y,v),{type:"bar",data:{labels:f,datasets:p},options:y,plugins:b}}function T1e(e,t,n,r){const s=n==null?void 0:n.lineStyleConfig,o=n==null?void 0:n.yAxisConfig,i=(r==null?void 0:r.some(a=>a._forecast))??!1;return e.map((a,l)=>{const u=t.find(m=>m.idx===l),d={...a};d.type="line",d.fill=!1,d.borderWidth=d.borderWidth??2,d.tension=d.tension??.1;const f=(u==null?void 0:u.pointRadius)??(s==null?void 0:s.pointRadius)??3;d.pointRadius=f,d.pointStyle=(u==null?void 0:u.pointStyle)??(s==null?void 0:s.pointStyle)??"circle",d.pointHoverRadius=(u==null?void 0:u.pointHoverRadius)??f+2,d.borderDash=SD((u==null?void 0:u.lineStyle)??(s==null?void 0:s.lineStyle)),i&&r&&M1e(d,r,a.borderColor);const h=DC(n==null?void 0:n.dataLabelsConfig,u==null?void 0:u.dataLabels);return h&&(d.datalabels=TC(h,o,"line")),d})}function M1e(e,t,n){const r=J.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 D1e(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 I1e({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var v,w;const{keys:i}=zn(t),a=vb(i),l=(s==null?void 0:s.datasetOptions)||[],u=i==null?void 0:i[0],d=nc(t,u),f=Gm(a,t,s,1,"none",u,!1,Ym(t)),h=T1e(f,l,s,t),m=ta(h,r),{options:p,plugins:g}=ou({cardType:o||"line",cfg:n,preferences:s,customCfg:r,card:e}),b=D1e(p==null?void 0:p.scales),x={...p,scales:b},y=(((w=(v=e.interactionConfig)==null?void 0:v.interactions)==null?void 0:w.length)??0)>0;return MC(x,y),{type:"line",data:{labels:d,datasets:m},options:x,plugins:g}}function R1e(e,t,n,r,s){const o=n==null?void 0:n.barStyleConfig,i=s==="horizontalBar"?n==null?void 0:n.xAxisConfig:n==null?void 0:n.yAxisConfig,a=(r==null?void 0:r.some(l=>l._forecast))??!1;return e.map((l,u)=>{const d=t.find(m=>m.idx===u),f={...l};f.borderRadius=(d==null?void 0:d.borderRadius)??(o==null?void 0:o.borderRadius)??0,f.borderWidth=(d==null?void 0:d.barBorderWidth)??(o==null?void 0:o.borderWidth)??0,f.barPercentage=(d==null?void 0:d.barPercentage)??(o==null?void 0:o.barPercentage)??.9,f.categoryPercentage=(d==null?void 0:d.categoryPercentage)??(o==null?void 0:o.categoryPercentage)??.8,a&&r&&A1e(f,r,l.backgroundColor);const h=DC(n==null?void 0:n.dataLabelsConfig,d==null?void 0:d.dataLabels);if(h){const m=s==="horizontalBar"?"horizontalBar":"bar";f.datalabels=TC(h,i,m)}return f})}function A1e(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 P1e(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 O1e(e){return e==="horizontalBar"?"y":void 0}function cN({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var k,M,T,P;let i=t;const{keys:a}=zn(i),l=vb(a),u=(s==null?void 0:s.datasetOptions)||[],d=a==null?void 0:a[0],f=Ym(i),h=o==="stackedBar",m=((k=e.config)==null?void 0:k.pivotByColumns)&&e.config.pivotByColumns.length>0,p=((M=e.config)==null?void 0:M.groupByColumns)&&e.config.groupByColumns.length>0;h&&!f&&(!m||!p)&&(i=Lx({dataArray:i,groupKey:a[0],pivotKey:a[1],valueKey:a[2],sortChart:s==null?void 0:s.sortChart}));const g=nc(i,d),b=Gm(h?vb(zn(i).keys):l,i,s,1,"none",d,h,f),x=R1e(b,u,s,i,o),y=ta(x,r),{options:v,plugins:w}=ou({cardType:o||"bar",cfg:n,preferences:s,customCfg:r,card:e}),j=o||"bar",S=P1e(v==null?void 0:v.scales,j,f),N=O1e(j),E={...v,scales:S,...N&&{indexAxis:N}},_=(((P=(T=e.interactionConfig)==null?void 0:T.interactions)==null?void 0:P.length)??0)>0;return MC(E,_),{type:"bar",data:{labels:g,datasets:y},options:E,plugins:w}}function ND({card:e,data:t,cardType:n="bar",cfg:r,customCfg:s,provider:o="chartjs",userSettings:i,preferences:a,topoJson:l,queryConfig:u,isDevMode:d}){var b,x,y,v,w,j,S,N;const f=e.config,h=d??!!e.sql;let m=t;const p=f&&f.pivotByColumns&&f.pivotByColumns.length>0,g=f&&f.groupByColumns&&f.groupByColumns.length>0;if(p&&g&&(m=Ahe(t,(f==null?void 0:f.metricColumns)||[])),n==="map"){if(!l)return null;const E=(b=a==null?void 0:a.mapVisualOptions)==null?void 0:b.objectKey;if(!E)return null;const _=zve(l,(x=l==null?void 0:l.objects)==null?void 0:x[E]).features;if(!_)return null;const k={plugins:{datalabels:{display:!1}},scales:{x:{display:!1,grid:{display:!1}},y:{display:!1,grid:{display:!1}},projection:{axis:"x",projection:((y=a==null?void 0:a.mapVisualOptions)==null?void 0:y.projection)||"mercator",projectionScale:((v=a==null?void 0:a.mapVisualOptions)==null?void 0:v.projectionScale)||1,projectionOffset:((w=a==null?void 0:a.mapVisualOptions)==null?void 0:w.projectionOffset)||[0,0]},color:{axis:"x",interpolate:((j=a==null?void 0:a.mapVisualOptions)==null?void 0:j.colorScale)||"blues",quantize:5,legend:{position:"bottom-right",align:"right"}}}},{keys:M}=zn(m),T=_.map(W=>{var F;const L=M==null?void 0:M[0],R=M==null?void 0:M[1],z=(F=m.find(A=>(A==null?void 0:A[L])===W.properties.NAME||(A==null?void 0:A[L])===W.properties.name))==null?void 0:F[R];return{feature:W,value:z}}),O=ta([{label:E,data:T,borderColor:"lightgray"}],s),I={type:"choropleth",data:{labels:_.map(W=>W.properties.NAME||W.properties.name),datasets:O},options:k},{options:$}=ou({cfg:I,preferences:a,customCfg:s,cardType:n});return{...I,options:$}}if(n==="bar")return cN({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="horizontalBar")return cN({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="funnel")return pwe({data:m,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="tornado"||n==="pyramid")return xwe({data:m,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="treemap")return ywe({data:m,cfg:r,customCfg:s,preferences:a});if(n==="heatmap")return i1e({data:m,cfg:r,customCfg:s,preferences:a,cardType:n});if(n==="bullet")return zwe({data:m,cfg:r,customCfg:s,preferences:a});if(n==="stackedBar")return cN({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="stackedLine"){const E=Ym(m),_=Kve(r,n,E),{keys:k}=zn(m);return!E&&(!p||!g)&&(m=Lx({dataArray:m,groupKey:k[0],pivotKey:k[1],valueKey:k[2],sortChart:a==null?void 0:a.sortChart})),Kj({card:e,data:m,cfg:_,customCfg:s,cardType:n,preferences:a})}if(n==="line")return I1e({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="area"||n==="stackedArea")return Fwe({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="combo")return _1e({card:e,data:m,cfg:r,customCfg:s,preferences:a});if(n==="range")return gwe({data:m,cfg:r,customCfg:s,preferences:a,card:e});if(n==="pie"||n==="doughnut"||n==="polarArea"){const E=Zve(n,r),{keys:_}=zn(m),k=_.slice(0,1),M=_.slice(1),T=gV(M,m,a,k==null?void 0:k[0]),P=ta(T,s),{plugins:O,options:I}=Cu((a==null?void 0:a.customVisualCode)||""),$=k[0],V=nc(m,$),W=jr((E==null?void 0:E.options)||{},(s==null?void 0:s.options)||{}),L=jr(W,(a==null?void 0:a.chartOptions)||{}),R={...L,plugins:{...L.plugins,datalabels:{...(S=L.plugins)==null?void 0:S.datalabels,formatter:(Y,q)=>{var U,G,Z,Q;return Js({number:Number(Y),decimalPlaces:((U=a==null?void 0:a.numberAxisFormat)==null?void 0:U.decimalPlaces)||0,useSuffix:!!((G=a==null?void 0:a.numberAxisFormat)!=null&&G.suffix),customSuffix:"",locale:((Z=a==null?void 0:a.numberAxisFormat)==null?void 0:Z.locale)||"",currency:((Q=a==null?void 0:a.numberAxisFormat)==null?void 0:Q.currency)||""})}},tooltip:{...(N=L.plugins)==null?void 0:N.tooltip,callbacks:{label:function(Y){var K,te,le,de;Y.dataset.label;const U=Y.dataset.data.reduce((ce,Ce)=>ce+Ce,0),G=Y.parsed,Z=Js({number:Number(G),decimalPlaces:((K=a==null?void 0:a.numberAxisFormat)==null?void 0:K.decimalPlaces)||0,useSuffix:!!((te=a==null?void 0:a.numberAxisFormat)!=null&&te.suffix),customSuffix:"",locale:((le=a==null?void 0:a.numberAxisFormat)==null?void 0:le.locale)||"",currency:((de=a==null?void 0:a.numberAxisFormat)==null?void 0:de.currency)||""}),Q=(G/U*100).toFixed(2);return Z+` (${Q}%)`},footer:function(Y){var U,G,Z,Q;return(((G=(U=e==null?void 0:e.interactionConfig)==null?void 0:U.drillHierarchies)==null?void 0:G.length)??0)>0||(((Q=(Z=e==null?void 0:e.interactionConfig)==null?void 0:Z.interactions)==null?void 0:Q.some(K=>K.mode==="drillDown"||K.mode==="drillToDetail"||K.mode==="drillThrough"||K.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},z=jr(L,R),{options:F}=ou({cfg:{options:z},preferences:a,customCfg:s,cardType:n,card:e}),A=jr(F,I);return{type:n,data:{labels:V,datasets:P},options:A,plugins:[n==="doughnut"?{id:"doughnutLabel",beforeDatasetsDraw:function(Y,q,U){var Ce,ge,he,me;const{ctx:G,data:Z}=Y;G.save();const Q=Y.getDatasetMeta(0).data[0].x,K=Y.getDatasetMeta(0).data[0].y,te=wo(Hi()),le=window.getComputedStyle(G.canvas).fontFamily;G.font=`1em ${le}`,G.fontWeight="bolder",G.fillStyle=te,G.textAlign="center",G.textBaseline="middle";const de=Z.datasets[0].data.reduce((oe,Ne)=>oe+Ne,0),ce=Js({number:Number(de),decimalPlaces:((Ce=a==null?void 0:a.numberAxisFormat)==null?void 0:Ce.decimalPlaces)||0,useSuffix:!!((ge=a==null?void 0:a.numberAxisFormat)!=null&&ge.suffix),customSuffix:"",locale:((he=a==null?void 0:a.numberAxisFormat)==null?void 0:he.locale)||"",currency:((me=a==null?void 0:a.numberAxisFormat)==null?void 0:me.currency)||""});G.fillText(ce,Q,K)}}:"",...O]}}if(n==="radar"){const E=Xve(r);return Kj({card:e,data:m,cfg:E,customCfg:s,cardType:n,preferences:a})}return n==="bubble"||n==="scatter"?ewe({data:m,cfg:r,customCfg:s,preferences:a,cardType:n,cardConfig:f,isDevMode:h,card:e}):Kj({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a})}function F1e({chart:e,elementIndex:t,datasetIndex:n,cardType:r,cfg:s,apply:o}){const i=J.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)&&L1e(e,t,s,o,a),["pie","doughnut","polarArea","funnel"].includes(r)&&z1e(e,t,s,o,a),["stackedBar","pyramid"].includes(r)&&$1e({chart:e,elementIndex:t,datasetIndex:n,cfg:s,apply:o,blurColor:a})}function $1e(e){var a,l,u,d;const{chart:t,elementIndex:n,datasetIndex:r,cfg:s,apply:o,blurColor:i}=e;o?(l=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null||l.forEach((f,h)=>{var m,p;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=(m=f==null?void 0:f.backgroundColor)==null?void 0:m.map((g,b)=>b===n&&h===r?g:i),f.borderColor=(p=f==null?void 0:f.borderColor)==null?void 0:p.map((g,b)=>b===n&&h===r?g:i)}):(d=(u=t==null?void 0:t.data)==null?void 0:u.datasets)==null||d.forEach((f,h)=>{var m,p,g,b,x,y;f.backgroundColor=new Array(f.data.length).fill((g=(p=(m=s==null?void 0:s.data)==null?void 0:m.datasets)==null?void 0:p[h])==null?void 0:g.backgroundColor),f.borderColor=new Array(f.data.length).fill((y=(x=(b=s==null?void 0:s.data)==null?void 0:b.datasets)==null?void 0:x[h])==null?void 0:y.borderColor)}),t==null||t.update()}function L1e(e,t,n,r,s){var o,i,a,l;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,m)=>m===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,m)=>m===t?h:s)}):(l=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||l.forEach((u,d)=>{var f,h,m,p,g,b;u.backgroundColor=new Array(u.data.length).fill((m=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:m.backgroundColor),u.borderColor=new Array(u.data.length).fill((b=(g=(p=n==null?void 0:n.data)==null?void 0:p.datasets)==null?void 0:g[d])==null?void 0:b.borderColor)}),e==null||e.update()}function z1e(e,t,n,r,s){var o,i,a,l;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,m)=>m===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,m)=>m===t?h:s)}):(l=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||l.forEach((u,d)=>{var f,h,m,p,g,b,x,y;typeof u.backgroundColor=="string"&&(u.backgroundColor=(m=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:m.backgroundColor,u.borderColor=(b=(g=(p=n==null?void 0:n.data)==null?void 0:p.datasets)==null?void 0:g[d])==null?void 0:b.borderColor),u.backgroundColor=(x=u==null?void 0:u.backgroundColor)==null?void 0:x.map((v,w)=>{var j;return(j=n.data.datasets[d].backgroundColor)==null?void 0:j[w]}),u.borderColor=(y=u==null?void 0:u.borderColor)==null?void 0:y.map((v,w)=>{var j;return(j=n.data.datasets[d].borderColor)==null?void 0:j[w]})}),e==null||e.update()}function B1e({card:e,data:t,datasetIndex:n,clickIndex:r,value:s}){var o,i,a,l,u,d,f;try{if(!t)return;const{keys:h}=zn(t);if(e.type==="map"){const m=h[0],p=((i=(o=s==null?void 0:s.feature)==null?void 0:o.properties)==null?void 0:i.name)||((l=(a=s==null?void 0:s.feature)==null?void 0:a.properties)==null?void 0:l.NAME);return[{columnName:m,columnValue:p}]}if(["bar","horizontalBar","line","pie","doughnut","radar","polarArea","funnel"].includes(e.type)){const m=h[0],p=h.slice(1),g=(u=t[r])==null?void 0:u[m];return[{columnName:m,columnValue:g,metric:p[n],value:s}]}if(["stackedBar","pyramid"].includes(e.type)){const m=Lx({dataArray:t,groupKey:h[0],pivotKey:h[1],valueKey:h[2]}),p=h[0],g=(d=m[r])==null?void 0:d[p],b=h[1],{keys:x}=zn(m),v=x.slice(1)[n];return[{columnName:p,columnValue:g,metric:h[2],value:s},{columnName:b,columnValue:v,metric:h[2],value:s}]}if(e.type==="bubble"||e.type==="scatter"){const m=h[0],p=(f=t[n])==null?void 0:f[m];return console.log(s,"bubble"),[{columnName:m,columnValue:p,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 NU(e){var a,l,u,d,f,h;const t=(((l=(a=e.preferences)==null?void 0:a.mapVisualOptions)==null?void 0:l.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}=En({queryKey:["topojson",t],queryFn:()=>fetch(t).then(m=>m.json()),enabled:n,staleTime:1/0});return{data:r,isLoading:s,isFetching:o,isError:i}}const cu="SEMAPHOR_CALCULATED_FIELD",V1e=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","YYYY-MM-DD HH:mm","YYYY-MM-DD HH:mm:ss","YYYY-MM-DD HH:mm Z","YYYY-MM-DD HH:mm:ss Z","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function sc(e){return e.role==="metric"&&"expression"in e&&!!e.expression}function Ux(e){return!!e.expression}function Pw(e){return!!e.expression}var kU=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(kU||{});function Ci(e){const{tokenProps:t}=Xe(),n=J(h=>h.authToken)||e,r=Ae(h=>h.selectedConnectionId),s=Ae(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r||s,{refetch:i,isPending:a,data:l,isLoading:u,isError:d}=En({queryKey:[t.project_id,"connections"],queryFn:()=>rr(`${t.apiServiceUrl}/v1/connections`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)}),f=l==null?void 0:l.connections.find(h=>h.id===o);return{isPending:a,error:d,connectionsData:l,connections:(l==null?void 0:l.connections)||[],isConnectionsLoading:u,isConnectionsError:d,refetchConnections:i,selectedConnection:f}}function EU(e){const{connections:t}=Ci(e),n=Ae(o=>o.selectedConnectionId),r=t.find(o=>o.id===n),s=r==null?void 0:r.capabilities.path.includes("schema");return{selectedConnection:r,capabilities:r==null?void 0:r.capabilities,connectionType:r==null?void 0:r.type,hasSchemaSupport:s}}const H1e=[],U1e=[],W1e=[];function q1e(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||pi(n.name),description:n.description,entityId:n.entityId||t.entityId,entityName:n.entityName||t.entityName,entityType:n.entityType||t.entityType})))}function gh(e){if(e.type==="model")return`${Uv}.${e.name}`;if(e.type==="dataset"){if(e.database&&e.schema)return`${e.database}.${e.schema}.${e.name}`;if(e.schema)return`${e.schema}.${e.name}`;if(e.database)return`${e.database}.${e.name}`}if(uk.includes(e.type)){if(e.database&&e.schema)return`${e.database}.${e.schema}.${e.name}`;if(e.schema)return`${e.schema}.${e.name}`;if(e.database)return`${e.database}.${e.name}`}return e.name}function kD(e){var v;const{tokenProps:t}=Xe(),n=J(w=>w.authToken)||e,{hasSchemaSupport:r}=EU(e),s=Ae(w=>{var j;return(j=w.card.dataSource)==null?void 0:j.connectionId}),o=Ae(w=>{var j;return(j=w.card.dataSource)==null?void 0:j.semanticDomainId}),i=Ae(w=>{var j;return(j=w.card.dataSource)==null?void 0:j.selectedEntities}),a=C.useMemo(()=>(i==null?void 0:i.filter(w=>w.type==="model"))||H1e,[i]),l=C.useMemo(()=>(i==null?void 0:i.filter(w=>uk.includes(w.type)))||U1e,[i]),u=C.useMemo(()=>(i==null?void 0:i.filter(w=>w.type==="dataset"))||W1e,[i]);function d(w){return w.type==="dataset"?!!s&&!!w.domainId&&!!w.name:w.type==="model"?!!s&&!!w.id:uk.includes(w.type)?r?!!s&&!!w.name&&!!w.database&&!!w.schema:["S3","API"].includes(w.connectionType)?!!s&&!!w.name:!!s&&!!w.name&&!!w.database:!1}const f=[...a,...l,...u],h=AT({queries:f.map(w=>{let j={};return w.type==="model"?j={connection_id:s,datamodel_id:w.id,database_name:"",schema_name:"",table_name:""}:w.type==="dataset"?j={connection_id:w.connectionId,domain_id:w.domainId,dataset_name:w.name}:j={connection_id:s,datamodel_id:"",database_name:w.database,schema_name:w.schema,table_name:w.name},{queryKey:["columns",s,w,o||null],queryFn:()=>rr(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",j),enabled:!!s&&d(w)}})}),m=h.some(w=>w.isPending),p=h.some(w=>w.isError),g=(v=h.find(w=>w.isError))==null?void 0:v.error,b=h.map((w,j)=>{var E;const S=f[j],N=gh(S);return{entityId:S.id||S.name,entityType:S.type,entityName:S.name,label:S.label,description:S.description,qualifiedEntityName:N,columns:(E=w.data)==null?void 0:E.columns.map(_=>({id:`${S.name}-${_.column_name}`,name:_.column_name,qualifiedFieldName:_.qualifiedFieldName||_.column_name,dataType:_.data_type,label:_.label||cb(_.column_name),description:_.description||"",qualifiedEntityName:N,entityId:S.id||S.id||S.name,entityName:S.name,entityType:S.type}))}}).filter(w=>{var j;return((j=w==null?void 0:w.columns)==null?void 0:j.length)>0})||[],x=h.flatMap(w=>{var j;return((j=w.data)==null?void 0:j.calculatedFields)||[]}).map(w=>({...w,fieldScope:"domain"}));if(x.length>0){const w=new Map;x.forEach(j=>{const S=`${j.name}-${j.role||"unknown"}`;w.has(S)||w.set(S,j)}),b.unshift({entityId:pz,entityType:"dataset",entityName:Qh,label:"Calculated Fields",description:"Domain-level calculated metrics and dimensions",qualifiedEntityName:Qh,columns:Array.from(w.values())})}const y=q1e(b);return{columnGroups:b,columns:y,isLoading:m,hasError:p,error:g,refetch:()=>{h.forEach(w=>w.refetch())}}}function Y1e(e,t,n){if(e===t)return!0;const r=new Map;for(const i of n){const a=i.source.name,l=i.target.name;r.has(a)||r.set(a,new Set),r.get(a).add(l),r.has(l)||r.set(l,new Set),r.get(l).add(a)}const s=new Set,o=[e];for(s.add(e);o.length>0;){const i=o.shift(),a=r.get(i);if(a)for(const l of a){if(l===t)return!0;s.has(l)||(s.add(l),o.push(l))}}return!1}function ED(e,t){var g,b,x,y,v,w,j;const{joinabilityMap:n,selectedFields:r,cardConfig:s,autoJoinMetadata:o,baseEntityName:i}=t;if(!n)return{state:"draggable"};if(e.entityName===cu||Pw(e))return{state:"draggable"};const a=r.filter(S=>S.entityName!==cu&&!Pw(S));if(a.length===0)return{state:"draggable",tooltip:"Select to establish base dataset"};let l;const u=(b=(g=s==null?void 0:s.joinPlan)==null?void 0:g.baseEntity)==null?void 0:b.name,d=(y=(x=o==null?void 0:o.resolvedJoinPlan)==null?void 0:x.baseEntity)==null?void 0:y.name;u?l=u:d?l=d:i?l=i:l=[...new Set(a.map(N=>N.entityName))].filter(Boolean)[0];const f=r.some(S=>S.entityName===e.entityName&&(S.name===e.name||S.id===e.id));if(e.entityName===l)return{state:"base",tooltip:f?"Field already in query (base dataset)":"From base dataset",isSelected:f};const h=n[l];if(!h)return{state:"unreachable",tooltip:"No relationships defined for base dataset"};if(h.canJoinTo.includes(e.entityName))return{state:"draggable",tooltip:`Direct join from ${l}`,joinPath:[l,e.entityName],isSelected:f};const m=(v=h.indirectJoins)==null?void 0:v[e.entityName];if(m&&m.length>0){const S=[l,...m,e.entityName];return{state:"indirect",joinPath:S,tooltip:`Multi-hop join: ${S.join(" → ")}`,isSelected:f}}const p=n[e.entityName];if(p){if(p.canJoinTo.includes(l))return{state:"draggable",tooltip:`Direct join to ${l}`,joinPath:[e.entityName,l],isSelected:f};const S=(w=p.indirectJoins)==null?void 0:w[l];if(S&&S.length>0){const N=[e.entityName,...S,l];return{state:"indirect",joinPath:N,tooltip:`Multi-hop join: ${N.join(" → ")}`,isSelected:f}}}return(j=s==null?void 0:s.joinPlan)!=null&&j.joins&&s.joinPlan.joins.length>0&&Y1e(l,e.entityName,s.joinPlan.joins)?{state:"draggable",tooltip:"Manual join configured",isSelected:f}:{state:"unreachable",tooltip:`Cannot join ${e.entityName} to ${l}`,isSelected:f}}function _U(e,t,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:e===t||e===gh(n.baseEntity)||t===gh(n.baseEntity)?!0:n.joins.some(s=>{const o=gh(s.source),i=gh(s.target);return o===e&&i===t||o===t&&i===e})}function G1e(e,t,n){var l;const{joinPlan:r,joinabilityMap:s,semanticDomainId:o}=n,i=t.filter(u=>u.entityName!==cu&&u.qualifiedEntityName!==Qh);if(i.length===0)return{isValid:!0};const a=i[0].qualifiedEntityName;if(!a)return{isValid:!0};if(a===e.qualifiedEntityName)return{isValid:!0};if(e.qualifiedEntityName){if(o&&s)return ED(e,{joinabilityMap:s,selectedFields:t,baseEntityName:(l=r==null?void 0:r.baseEntity)==null?void 0:l.name}).state==="unreachable"?{isValid:!1,showError:!0}:{isValid:!0};if(!r)return{isValid:!1,showError:!0};if(!_U(a,e.qualifiedEntityName,r))return{isValid:!1,showError:!0}}return{isValid:!0}}function TU(){ze.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 MU(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||{},l=JSON.stringify(i),u=JSON.stringify(a);if(l!==u)return!1}return!1}return!0})}function K1e(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 Z1e(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})`}function DU(e,t){return`${e}-${t.qualifiedEntityName}-${t.name}-${Date.now()}`}function IU(e,t){const n=pi(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 X1e(e,t,n){const r=yr(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 RU(e,t,n=[]){const r=DU(t,e),s=yr(e.dataType),o=s==="date",i=e.role==="metric"&&"expression"in e&&!!e.expression,a=e.role==="groupby"&&"expression"in e&&!!e.expression,l={id:r,name:e.name,dataType:e.dataType,label:cb(e.name),qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityId:e.entityId,entityName:e.entityName,entityType:e.entityType};if(t==="metrics"){if(i){const{fieldScope:h,...m}=e;return{...m,id:r,label:e.label||e.name,role:"metric"}}const u=s==="number"?"SUM":"COUNT",d=IU(e.label,u),f=Z1e({...l,label:d},n,t);return{...l,role:"metric",label:f,aggregate:u}}if(t==="groupBy"){if(a){const{fieldScope:u,...d}=e;return{...d,id:r,label:e.label||e.name,role:"groupby"}}return{...l,role:"groupby",...o&&{granularity:"month",dateFormat:"YYYY-MM"}}}return t==="pivotBy"?{...l,role:"pivotby"}:t==="detailColumns"?{...l,role:"detail"}:t==="sortBy"?{...l,role:"sortby",label:e.label,direction:"asc"}:null}function Q1e(e){var o,i,a,l;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=(l=e.config)==null?void 0:l.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 J1e(e){var i,a;const[t]=C.useState({id:"",title:"",type:"bar"}),{getCard:n}=Wt(),r=n(e),s=Wx(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 Wx(e){var P;const{onChartElementClicked:t}=Xe(),[n,r]=C.useState(0),s=J(O=>O.themeStyle),o=J(O=>O.filteringCards),i=J(O=>O.selectedSheetId),a=J(O=>O.selectedLensId),l=J(O=>O.filterValues),u=C.useRef(l),d=(P=e==null?void 0:e.preferences)==null?void 0:P.onClickFilter,{addFilteringCard:f,addOrUpdateFilterValues:h,removeFilterValues:m,removeFilteringCard:p}=Wt(),{data:g,isLoading:b,isFetching:x,isError:y,isPending:v,queryKey:w,isFilteringCard:j,isSingleCardFrame:S,pagination:N,comparisonMetadata:E}=Ha(e),{data:_}=NU(e);let k;k=C.useMemo(()=>{if(!(!(g!=null&&g.records)||!(g!=null&&g.records.length)))return ND({card:e,data:g==null?void 0:g.records,cardType:e.type,queryConfig:e.queryConfig,customCfg:e.customCfg,preferences:e.preferences,topoJson:_})},[g==null?void 0:g.records,e.type,e.queryConfig,e.customCfg,e.config,e.preferences,_,s]);const M=C.useRef({filteringCards:o});C.useEffect(()=>{e.connectionId&&!j&&(u.current=l)},[l,a,e.connectionId,j]),C.useEffect(()=>{var I;j&&(M.current.filteringCards=[...o||[]]),!j&&((I=M.current.filteringCards)==null?void 0:I.find($=>$.id===e.id))&&S&&r($=>$+1)},[j,S,e.id,o]);function T(O,I,$,V){var R;if(Q1e(e))return;let W=!1;if(!(g!=null&&g.records))return;const L=B1e({card:e,data:g==null?void 0:g.records,datasetIndex:I,clickIndex:$,value:V});if(console.log("fieldValues",L),t==null||t(e,L),!!(((R=e==null?void 0:e.preferences)==null?void 0:R.onClickFilter)??[]).length){if(j){const z=e.id;m(z),p(e)}else{if(W=!0,!L)return;const z=[];L.forEach((F,A)=>{const H=d==null?void 0:d.find(Y=>Y.columnIndex===A);if(!H)return;const B={filterId:e.id+"-"+F.columnName+"-"+i,connectionId:e==null?void 0:e.connectionId,tableName:e.lastSelectedTable,name:F.columnName,expression:H.expression,valueType:jT(L[H.columnIndex].columnValue),operation:"=",values:[L[H.columnIndex].columnValue]};z.push(B)}),h(z),f(e)}F1e({chart:O,elementIndex:$,datasetIndex:I,cardType:e.type,cfg:k,apply:W})}}return{isPending:v,isError:y,isLoading:b,isFetching:x,data:g,visualKey:n,handleDatapointClick:T,cfg:k,queryKey:w,pagination:N,comparisonMetadata:E}}function AU(e){var x;const{tokenProps:t}=Xe(),n=J(y=>y.authToken)||e,r=Ae(y=>y.selectedConnectionId),s=Ae(y=>y.selectedDatabaseName),o=Ae(y=>y.selectedDatamodelId),i=Ae(y=>y.selectedSchemaName),a=Ae(y=>y.selectedTableName),{selectedConnection:l}=Ci(),u=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:m,refetch:p}=En({queryKey:["columns",r,s,o,i,a],queryFn:()=>rr(`${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:g(u)});function g(y){return n!=null&&n.accessToken?!!(r&&s&&s!=="NA"&&i&&a||r&&(y==="S3"||y==="API")||o&&o):!1}return{columns:(x=d==null?void 0:d.columns)==null?void 0:x.map(y=>({...y,data_type:y.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:m,refetchColumns:p}}function Ih(e,t){const[n,r]=C.useState(e);return C.useEffect(()=>{const s=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(s)}},[e,t]),n}var eCe=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,s,o;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(s=r;s--!==0;)if(!e(t[s],n[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(o=Object.keys(t),r=o.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[s]))return!1;for(s=r;s--!==0;){var i=o[s];if(!(i==="_owner"&&t.$$typeof)&&!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n};const PU=hf(eCe);function E0(e,t=PU){const[n,r]=C.useState(()=>({value:e,lastInput:e}));if(!t(n.lastInput,e)){const s=t(n.value,e)?n.value:e;return r({value:s,lastInput:e}),s}return n.value}function tCe(e=[],t=[]){var r,s,o,i;if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;const n=Math.min(5,e.length);for(let a=0;a<n;a++)if(((r=e[a])==null?void 0:r.id)!==((s=t[a])==null?void 0:s.id))return!1;for(let a=0;a<n;a++){const l=e.length-1-a;if(((o=e[l])==null?void 0:o.id)!==((i=t[l])==null?void 0:i.id))return!1}return PU(e,t)}gre();const IC=oa()(Im((e,t)=>({activeExports:new Map,actions:{addExport:n=>{e(r=>{r.activeExports.set(n.id,{...n,lastUpdatedAt:n.lastUpdatedAt??new Date})})},updateExport:(n,r)=>{e(s=>{const o=s.activeExports.get(n);if(o){const i={...o,...r};r.lastUpdatedAt||(i.lastUpdatedAt=new Date),s.activeExports.set(n,i)}})},removeExport:n=>{e(r=>{r.activeExports.delete(n)})},getInProgressExports:()=>Array.from(t().activeExports.values()).filter(r=>["pending","processing","chunking","compacting"].includes(r.status)),getAllExports:()=>Array.from(t().activeExports.values()).sort((n,r)=>r.startedAt.getTime()-n.startedAt.getTime()),clearCompleted:()=>{e(n=>{for(const[r,s]of n.activeExports)(s.status==="completed"||s.status==="failed")&&n.activeExports.delete(r)})},hasInProgressExports:()=>Array.from(t().activeExports.values()).some(r=>["pending","processing","chunking","compacting"].includes(r.status))}}))),OU=()=>IC(e=>e.actions),nCe=()=>IC(e=>e.activeExports),rCe=()=>IC(e=>Array.from(e.activeExports.values()).filter(n=>["pending","processing","chunking","compacting"].includes(n.status)).length);async function FU(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 tp(o.message||o.error||"Failed to create export",r.status,o)}return s}async function sCe(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 tp("Failed to fetch exports",s.status);return s.json()}async function oCe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new tp("Failed to fetch export status",r.status);return r.json()}async function iCe(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 tp("Failed to get download URL",r.status)}async function aCe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new tp("Failed to cancel export",r.status)}class tp extends Error{constructor(t,n,r){super(t),this.status=n,this.details=r,this.name="ExportError"}}function lCe(e){return["pending","processing","chunking","compacting"].includes(e)}function cCe(e){return["completed","failed","cancelled"].includes(e)}function uCe(e){return!e||e===0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}const O5={searchQuery:"",debouncedSearchQuery:"",selectedUsers:[],usersToRemove:[],usersToUpdate:[],selectedGroups:[],groupsToRemove:[],groupsToUpdate:[],selectedTab:"org",currentContext:"org-tab",currentMode:null,orgWideRole:"VIEWER",allTenantsRole:"VIEWER",tenantWideRole:"VIEWER",groupWideRole:"VIEWER",selectedTenant:"",message:""},Fs=oa()(Im(e=>({...O5,actions:{setSearchQuery:t=>{e(n=>{n.searchQuery=t})},setDebouncedSearchQuery:t=>{e(n=>{n.debouncedSearchQuery=t})},setSelectedUsers:t=>{e(n=>{n.selectedUsers=t})},addSelectedUser:t=>{e(n=>{n.selectedUsers.some(s=>s.id===t.id)||n.selectedUsers.push(t)})},removeSelectedUser:t=>{e(n=>{n.selectedUsers=n.selectedUsers.filter(r=>r.id!==t)})},updateSelectedUserRole:(t,n)=>{e(r=>{const s=r.selectedUsers.find(o=>o.id===t);s&&(s.role=n)})},setUsersToRemove:t=>{e(n=>{n.usersToRemove=t})},addUserToRemove:t=>{e(n=>{n.usersToRemove.includes(t)||n.usersToRemove.push(t)})},removeUserFromRemove:t=>{e(n=>{n.usersToRemove=n.usersToRemove.filter(r=>r!==t)})},setUsersToUpdate:t=>{e(n=>{n.usersToUpdate=t})},addUserToUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t.id),n.usersToUpdate.push(t)})},removeUserFromUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t)})},setSelectedTenant:t=>{e(n=>{n.selectedTenant=t})},setSelectedTab:t=>{e(n=>{n.selectedTab=t})},setCurrentContext:t=>{e(n=>{n.currentContext=t})},setCurrentMode:t=>{e(n=>{n.currentMode=t})},setOrgWideRole:t=>{e(n=>{n.orgWideRole=t})},setAllTenantsRole:t=>{e(n=>{n.allTenantsRole=t})},setTenantWideRole:t=>{e(n=>{n.tenantWideRole=t})},setGroupWideRole:t=>{e(n=>{n.groupWideRole=t})},setSelectedGroups:t=>{e(n=>{n.selectedGroups=t})},addSelectedGroup:t=>{e(n=>{n.selectedGroups.some(s=>s.id===t.id)||n.selectedGroups.push(t)})},removeSelectedGroup:t=>{e(n=>{n.selectedGroups=n.selectedGroups.filter(r=>r.id!==t)})},updateSelectedGroupRole:(t,n)=>{e(r=>{const s=r.selectedGroups.find(o=>o.id===t);s&&(s.role=n)})},setGroupsToRemove:t=>{e(n=>{n.groupsToRemove=t})},addGroupToRemove:t=>{e(n=>{n.groupsToRemove.includes(t)||n.groupsToRemove.push(t)})},removeGroupFromRemove:t=>{e(n=>{n.groupsToRemove=n.groupsToRemove.filter(r=>r!==t)})},setGroupsToUpdate:t=>{e(n=>{n.groupsToUpdate=t})},addGroupToUpdate:t=>{e(n=>{const r=n.groupsToUpdate.findIndex(s=>s.id===t.id);r!==-1?n.groupsToUpdate[r]=t:n.groupsToUpdate.push(t)})},removeGroupFromUpdate:t=>{e(n=>{n.groupsToUpdate=n.groupsToUpdate.filter(r=>r.id!==t)})},setMessage:t=>{e(n=>{n.message=t})},validateShareData:t=>fV(t),resetShareState:()=>{e(t=>{Object.assign(t,O5)})},resetUserSelections:()=>{e(t=>{t.selectedUsers=[],t.usersToRemove=[],t.usersToUpdate=[]})},resetGroupSelections:()=>{e(t=>{t.selectedGroups=[],t.groupsToRemove=[],t.groupsToUpdate=[]})}}}))),dCe=()=>Fs(e=>e.searchQuery),qx=()=>Fs(e=>e.selectedUsers),np=()=>Fs(e=>e.usersToRemove),Yx=()=>Fs(e=>e.usersToUpdate),Gx=()=>Fs(e=>e.selectedTenant),_D=()=>Fs(e=>e.selectedTab),$U=()=>Fs(e=>e.currentContext),ku=()=>Fs(e=>e.currentMode),TD=()=>Fs(e=>e.orgWideRole),MD=()=>Fs(e=>e.allTenantsRole),RC=()=>Fs(e=>e.tenantWideRole),LU=()=>Fs(e=>e.groupWideRole),Kx=()=>Fs(e=>e.selectedGroups),Zx=()=>Fs(e=>e.groupsToRemove),Xx=()=>Fs(e=>e.groupsToUpdate),rp=()=>Fs(e=>e.actions),zU=()=>{const e=dCe(),t=Ih(e,300),n=rp();return C.useEffect(()=>{n.setDebouncedSearchQuery(t)},[t,n]),{searchQuery:e,debouncedSearchQuery:t,setSearchQuery:n.setSearchQuery}};function fCe({currentUser:e,currentShare:t,isSharing:n,onUpdateAccess:r,allUsersToUpdate:s=null,allUsersToRemove:o=!1,isUpdating:i=!1,isRemoving:a=!1}){const l=ku(),u=$o().filter(y=>y.value==="VIEWER"||y.value==="EDITOR"||y.value==="CONTRIBUTOR"),d=t.role!=="NONE"?t.role:"NONE",f=s?s.newRole:d,h=t.role!=="NONE"&&!o&&(!s||s.newRole===d),m=s!==null&&s.newRole!==d,p=o,g=d==="NONE"||!d,b=y=>{switch(y){case"VIEWER":return c.jsx(tu,{className:"h-4 w-4"});case"EDITOR":return c.jsx(Y1,{className:"h-4 w-4"});case"CONTRIBUTOR":return c.jsx(nie,{className:"h-4 w-4"});default:return c.jsx(tu,{className:"h-4 w-4"})}},x=y=>{r(d,y)};return c.jsx("div",{className:"space-y-4",children:c.jsxs(Uo,{className:X("pb-6",m&&!p&&!g?"border-orange-300 bg-orange-50":h?"border-green-300 bg-green-50":p||g?"border-destructive bg-destructive/10":""),children:[c.jsxs(Zi,{children:[c.jsxs(Xi,{className:"flex items-center gap-2 text-base",children:[c.jsx(Pr,{className:"h-5 w-5"}),"Share with All"," ",l==="allOrgUsers"?"Organization":l==="allTenantUsers"?"Tenant":l==="specificOrgUsers"?"Org":"Tenant"," ","Users",h&&c.jsx(Ve,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),m&&c.jsx(Ve,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(p||g)&&c.jsx(Ve,{variant:"destructive",className:"ml-2",children:"No Access"})]}),c.jsx(Qz,{children:p||g?"No access for all users.":"This will share the dashboard with all users in your "+((e==null?void 0:e.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),c.jsx(Qi,{className:"space-y-4",children:c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),c.jsxs(Wm,{children:[c.jsx(qm,{asChild:!0,children:c.jsx(se,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:c.jsx(nr,{className:"h-3 w-3"})})}),c.jsx(Mf,{className:"w-80",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),c.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(e==null?void 0:e.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.jsxs("p",{children:[c.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),c.jsxs("p",{children:[c.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),c.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(y=>c.jsxs(se,{variant:f===y.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>x(y.value),disabled:n||i||a,children:[c.jsxs("div",{className:"flex items-center gap-2",children:[b(y.value),c.jsx("span",{className:"font-medium",children:y.label})]}),c.jsx("p",{className:"text-left text-xs text-muted-foreground",children:y.description})]},y.value))})]})})]})})}function BU({currentUser:e,currentShare:t,isSharing:n,isUpdating:r,isRemoving:s,onUpdateAccess:o,onRemoveAccess:i,allUsersToUpdate:a,allUsersToRemove:l}){const u=g=>g==="OWNER"?"CONTRIBUTOR":g,f=t?{role:u(t.role)}:{role:"NONE"},h=a?{currentRole:u(a.currentRole),newRole:u(a.newRole)}:null,m=(g,b)=>{o(g,b)},p=()=>{i()};return c.jsx(fCe,{currentUser:e,currentShare:f,isSharing:n,isUpdating:r,isRemoving:s,onUpdateAccess:m,onRemoveAccess:p,allUsersToUpdate:h,allUsersToRemove:l})}function hCe(e){const t=mCe(e),n=D.forwardRef((r,s)=>{const{children:o,...i}=r,a=D.Children.toArray(o),l=a.find(gCe);if(l){const u=l.props.children,d=a.map(f=>f===l?D.Children.count(u)>1?D.Children.only(null):D.isValidElement(u)?u.props.children:null:f);return c.jsx(t,{...i,ref:s,children:D.isValidElement(u)?D.cloneElement(u,void 0,d):null})}return c.jsx(t,{...i,ref:s,children:o})});return n.displayName=`${e}.Slot`,n}function mCe(e){const t=D.forwardRef((n,r)=>{const{children:s,...o}=n;if(D.isValidElement(s)){const i=xCe(s),a=bCe(o,s.props);return s.type!==D.Fragment&&(a.ref=r?to(r,i):i),D.cloneElement(s,a)}return D.Children.count(s)>1?D.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var pCe=Symbol("radix.slottable");function gCe(e){return D.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===pCe}function bCe(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...a)=>{const l=o(...a);return s(...a),l}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function xCe(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var AC="Popover",[VU]=Lr(AC,[Ka]),Qx=Ka(),[yCe,Eu]=VU(AC),HU=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:s,onOpenChange:o,modal:i=!1}=e,a=Qx(t),l=D.useRef(null),[u,d]=D.useState(!1),[f,h]=ss({prop:r,defaultProp:s??!1,onChange:o,caller:AC});return c.jsx(zm,{...a,children:c.jsx(yCe,{scope:t,contentId:xr(),triggerRef:l,open:f,onOpenChange:h,onOpenToggle:D.useCallback(()=>h(m=>!m),[h]),hasCustomAnchor:u,onCustomAnchorAdd:D.useCallback(()=>d(!0),[]),onCustomAnchorRemove:D.useCallback(()=>d(!1),[]),modal:i,children:n})})};HU.displayName=AC;var UU="PopoverAnchor",vCe=D.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Eu(UU,n),o=Qx(n),{onCustomAnchorAdd:i,onCustomAnchorRemove:a}=s;return D.useEffect(()=>(i(),()=>a()),[i,a]),c.jsx(Bm,{...o,...r,ref:t})});vCe.displayName=UU;var WU="PopoverTrigger",qU=D.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Eu(WU,n),o=Qx(n),i=ut(t,s.triggerRef),a=c.jsx(Ze.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":QU(s.open),...r,ref:i,onClick:Ie(e.onClick,s.onOpenToggle)});return s.hasCustomAnchor?a:c.jsx(Bm,{asChild:!0,...o,children:a})});qU.displayName=WU;var DD="PopoverPortal",[wCe,CCe]=VU(DD,{forceMount:void 0}),YU=e=>{const{__scopePopover:t,forceMount:n,children:r,container:s}=e,o=Eu(DD,t);return c.jsx(wCe,{scope:t,forceMount:n,children:c.jsx(vr,{present:n||o.open,children:c.jsx(yf,{asChild:!0,container:s,children:r})})})};YU.displayName=DD;var bm="PopoverContent",GU=D.forwardRef((e,t)=>{const n=CCe(bm,e.__scopePopover),{forceMount:r=n.forceMount,...s}=e,o=Eu(bm,e.__scopePopover);return c.jsx(vr,{present:r||o.open,children:o.modal?c.jsx(jCe,{...s,ref:t}):c.jsx(NCe,{...s,ref:t})})});GU.displayName=bm;var SCe=hCe("PopoverContent.RemoveScroll"),jCe=D.forwardRef((e,t)=>{const n=Eu(bm,e.__scopePopover),r=D.useRef(null),s=ut(t,r),o=D.useRef(!1);return D.useEffect(()=>{const i=r.current;if(i)return J1(i)},[]),c.jsx(Rx,{as:SCe,allowPinchZoom:!0,children:c.jsx(KU,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ie(e.onCloseAutoFocus,i=>{var a;i.preventDefault(),o.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Ie(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,u=a.button===2||l;o.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Ie(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),NCe=D.forwardRef((e,t)=>{const n=Eu(bm,e.__scopePopover),r=D.useRef(!1),s=D.useRef(!1);return c.jsx(KU,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,o),o.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const i=o.target;((u=n.triggerRef.current)==null?void 0:u.contains(i))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),KU=D.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:i,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:d,...f}=e,h=Eu(bm,n),m=Qx(n);return G1(),c.jsx(Fm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:c.jsx(xf,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:d,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>h.onOpenChange(!1),children:c.jsx(Mx,{"data-state":QU(h.open),role:"dialog",id:h.contentId,...m,...f,ref:t,style:{...f.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),ZU="PopoverClose",kCe=D.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Eu(ZU,n);return c.jsx(Ze.button,{type:"button",...r,ref:t,onClick:Ie(e.onClick,()=>s.onOpenChange(!1))})});kCe.displayName=ZU;var ECe="PopoverArrow",XU=D.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Qx(n);return c.jsx(Dx,{...s,...r,ref:t})});XU.displayName=ECe;function QU(e){return e?"open":"closed"}var ID=HU,RD=qU,_Ce=YU,sp=GU,TCe=XU,F5=1,MCe=.9,DCe=.8,ICe=.17,uN=.1,dN=.999,RCe=.9999,ACe=.99,PCe=/[\\\/_+.#"@\[\(\{&]/,OCe=/[\\\/_+.#"@\[\(\{&]/g,FCe=/[\s-]/,JU=/[\s-]/g;function PE(e,t,n,r,s,o,i){if(o===t.length)return s===e.length?F5:ACe;var a=`${s},${o}`;if(i[a]!==void 0)return i[a];for(var l=r.charAt(o),u=n.indexOf(l,s),d=0,f,h,m,p;u>=0;)f=PE(e,t,n,r,u+1,o+1,i),f>d&&(u===s?f*=F5:PCe.test(e.charAt(u-1))?(f*=DCe,m=e.slice(s,u-1).match(OCe),m&&s>0&&(f*=Math.pow(dN,m.length))):FCe.test(e.charAt(u-1))?(f*=MCe,p=e.slice(s,u-1).match(JU),p&&s>0&&(f*=Math.pow(dN,p.length))):(f*=ICe,s>0&&(f*=Math.pow(dN,u-s))),e.charAt(u)!==t.charAt(o)&&(f*=RCe)),(f<uN&&n.charAt(u-1)===r.charAt(o+1)||r.charAt(o+1)===r.charAt(o)&&n.charAt(u-1)!==r.charAt(o))&&(h=PE(e,t,n,r,u+1,o+2,i),h*uN>f&&(f=h*uN)),f>d&&(d=f),u=n.indexOf(l,u+1);return i[a]=d,d}function $5(e){return e.toLowerCase().replace(JU," ")}function $Ce(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,PE(e,t,$5(e),$5(t),0,0,{})}var Up='[cmdk-group=""]',fN='[cmdk-group-items=""]',LCe='[cmdk-group-heading=""]',eW='[cmdk-item=""]',L5=`${eW}:not([aria-disabled="true"])`,OE="cmdk-item-select",sh="data-value",zCe=(e,t,n)=>$Ce(e,t,n),tW=D.createContext(void 0),Jx=()=>D.useContext(tW),nW=D.createContext(void 0),AD=()=>D.useContext(nW),rW=D.createContext(void 0),sW=D.forwardRef((e,t)=>{let n=oh(()=>{var F,A;return{search:"",value:(A=(F=e.value)!=null?F:e.defaultValue)!=null?A:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=oh(()=>new Set),s=oh(()=>new Map),o=oh(()=>new Map),i=oh(()=>new Set),a=oW(e),{label:l,children:u,value:d,onValueChange:f,filter:h,shouldFilter:m,loop:p,disablePointerSelection:g=!1,vimBindings:b=!0,...x}=e,y=xr(),v=xr(),w=xr(),j=D.useRef(null),S=XCe();sf(()=>{if(d!==void 0){let F=d.trim();n.current.value=F,N.emit()}},[d]),sf(()=>{S(6,P)},[]);let N=D.useMemo(()=>({subscribe:F=>(i.current.add(F),()=>i.current.delete(F)),snapshot:()=>n.current,setState:(F,A,H)=>{var B,Y,q,U;if(!Object.is(n.current[F],A)){if(n.current[F]=A,F==="search")T(),k(),S(1,M);else if(F==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let G=document.getElementById(w);G?G.focus():(B=document.getElementById(y))==null||B.focus()}if(S(7,()=>{var G;n.current.selectedItemId=(G=O())==null?void 0:G.id,N.emit()}),H||S(5,P),((Y=a.current)==null?void 0:Y.value)!==void 0){let G=A??"";(U=(q=a.current).onValueChange)==null||U.call(q,G);return}}N.emit()}},emit:()=>{i.current.forEach(F=>F())}}),[]),E=D.useMemo(()=>({value:(F,A,H)=>{var B;A!==((B=o.current.get(F))==null?void 0:B.value)&&(o.current.set(F,{value:A,keywords:H}),n.current.filtered.items.set(F,_(A,H)),S(2,()=>{k(),N.emit()}))},item:(F,A)=>(r.current.add(F),A&&(s.current.has(A)?s.current.get(A).add(F):s.current.set(A,new Set([F]))),S(3,()=>{T(),k(),n.current.value||M(),N.emit()}),()=>{o.current.delete(F),r.current.delete(F),n.current.filtered.items.delete(F);let H=O();S(4,()=>{T(),(H==null?void 0:H.getAttribute("id"))===F&&M(),N.emit()})}),group:F=>(s.current.has(F)||s.current.set(F,new Set),()=>{o.current.delete(F),s.current.delete(F)}),filter:()=>a.current.shouldFilter,label:l||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:y,inputId:w,labelId:v,listInnerRef:j}),[]);function _(F,A){var H,B;let Y=(B=(H=a.current)==null?void 0:H.filter)!=null?B:zCe;return F?Y(F,n.current.search,A):0}function k(){if(!n.current.search||a.current.shouldFilter===!1)return;let F=n.current.filtered.items,A=[];n.current.filtered.groups.forEach(B=>{let Y=s.current.get(B),q=0;Y.forEach(U=>{let G=F.get(U);q=Math.max(G,q)}),A.push([B,q])});let H=j.current;I().sort((B,Y)=>{var q,U;let G=B.getAttribute("id"),Z=Y.getAttribute("id");return((q=F.get(Z))!=null?q:0)-((U=F.get(G))!=null?U:0)}).forEach(B=>{let Y=B.closest(fN);Y?Y.appendChild(B.parentElement===Y?B:B.closest(`${fN} > *`)):H.appendChild(B.parentElement===H?B:B.closest(`${fN} > *`))}),A.sort((B,Y)=>Y[1]-B[1]).forEach(B=>{var Y;let q=(Y=j.current)==null?void 0:Y.querySelector(`${Up}[${sh}="${encodeURIComponent(B[0])}"]`);q==null||q.parentElement.appendChild(q)})}function M(){let F=I().find(H=>H.getAttribute("aria-disabled")!=="true"),A=F==null?void 0:F.getAttribute(sh);N.setState("value",A||void 0)}function T(){var F,A,H,B;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let Y=0;for(let q of r.current){let U=(A=(F=o.current.get(q))==null?void 0:F.value)!=null?A:"",G=(B=(H=o.current.get(q))==null?void 0:H.keywords)!=null?B:[],Z=_(U,G);n.current.filtered.items.set(q,Z),Z>0&&Y++}for(let[q,U]of s.current)for(let G of U)if(n.current.filtered.items.get(G)>0){n.current.filtered.groups.add(q);break}n.current.filtered.count=Y}function P(){var F,A,H;let B=O();B&&(((F=B.parentElement)==null?void 0:F.firstChild)===B&&((H=(A=B.closest(Up))==null?void 0:A.querySelector(LCe))==null||H.scrollIntoView({block:"nearest"})),B.scrollIntoView({block:"nearest"}))}function O(){var F;return(F=j.current)==null?void 0:F.querySelector(`${eW}[aria-selected="true"]`)}function I(){var F;return Array.from(((F=j.current)==null?void 0:F.querySelectorAll(L5))||[])}function $(F){let A=I()[F];A&&N.setState("value",A.getAttribute(sh))}function V(F){var A;let H=O(),B=I(),Y=B.findIndex(U=>U===H),q=B[Y+F];(A=a.current)!=null&&A.loop&&(q=Y+F<0?B[B.length-1]:Y+F===B.length?B[0]:B[Y+F]),q&&N.setState("value",q.getAttribute(sh))}function W(F){let A=O(),H=A==null?void 0:A.closest(Up),B;for(;H&&!B;)H=F>0?KCe(H,Up):ZCe(H,Up),B=H==null?void 0:H.querySelector(L5);B?N.setState("value",B.getAttribute(sh)):V(F)}let L=()=>$(I().length-1),R=F=>{F.preventDefault(),F.metaKey?L():F.altKey?W(1):V(1)},z=F=>{F.preventDefault(),F.metaKey?$(0):F.altKey?W(-1):V(-1)};return D.createElement(Ze.div,{ref:t,tabIndex:-1,...x,"cmdk-root":"",onKeyDown:F=>{var A;(A=x.onKeyDown)==null||A.call(x,F);let H=F.nativeEvent.isComposing||F.keyCode===229;if(!(F.defaultPrevented||H))switch(F.key){case"n":case"j":{b&&F.ctrlKey&&R(F);break}case"ArrowDown":{R(F);break}case"p":case"k":{b&&F.ctrlKey&&z(F);break}case"ArrowUp":{z(F);break}case"Home":{F.preventDefault(),$(0);break}case"End":{F.preventDefault(),L();break}case"Enter":{F.preventDefault();let B=O();if(B){let Y=new Event(OE);B.dispatchEvent(Y)}}}}},D.createElement("label",{"cmdk-label":"",htmlFor:E.inputId,id:E.labelId,style:JCe},l),PC(e,F=>D.createElement(nW.Provider,{value:N},D.createElement(tW.Provider,{value:E},F))))}),BCe=D.forwardRef((e,t)=>{var n,r;let s=xr(),o=D.useRef(null),i=D.useContext(rW),a=Jx(),l=oW(e),u=(r=(n=l.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;sf(()=>{if(!u)return a.item(s,i==null?void 0:i.id)},[u]);let d=iW(s,o,[e.value,e.children,o],e.keywords),f=AD(),h=uu(S=>S.value&&S.value===d.current),m=uu(S=>u||a.filter()===!1?!0:S.search?S.filtered.items.get(s)>0:!0);D.useEffect(()=>{let S=o.current;if(!(!S||e.disabled))return S.addEventListener(OE,p),()=>S.removeEventListener(OE,p)},[m,e.onSelect,e.disabled]);function p(){var S,N;g(),(N=(S=l.current).onSelect)==null||N.call(S,d.current)}function g(){f.setState("value",d.current,!0)}if(!m)return null;let{disabled:b,value:x,onSelect:y,forceMount:v,keywords:w,...j}=e;return D.createElement(Ze.div,{ref:to(o,t),...j,id:s,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!h,"data-disabled":!!b,"data-selected":!!h,onPointerMove:b||a.getDisablePointerSelection()?void 0:g,onClick:b?void 0:p},e.children)}),VCe=D.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:s,...o}=e,i=xr(),a=D.useRef(null),l=D.useRef(null),u=xr(),d=Jx(),f=uu(m=>s||d.filter()===!1?!0:m.search?m.filtered.groups.has(i):!0);sf(()=>d.group(i),[]),iW(i,a,[e.value,e.heading,l]);let h=D.useMemo(()=>({id:i,forceMount:s}),[s]);return D.createElement(Ze.div,{ref:to(a,t),...o,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&D.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:u},n),PC(e,m=>D.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?u:void 0},D.createElement(rW.Provider,{value:h},m))))}),HCe=D.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,s=D.useRef(null),o=uu(i=>!i.search);return!n&&!o?null:D.createElement(Ze.div,{ref:to(s,t),...r,"cmdk-separator":"",role:"separator"})}),UCe=D.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,s=e.value!=null,o=AD(),i=uu(u=>u.search),a=uu(u=>u.selectedItemId),l=Jx();return D.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),D.createElement(Ze.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":a,id:l.inputId,type:"text",value:s?e.value:i,onChange:u=>{s||o.setState("search",u.target.value),n==null||n(u.target.value)}})}),WCe=D.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...s}=e,o=D.useRef(null),i=D.useRef(null),a=uu(u=>u.selectedItemId),l=Jx();return D.useEffect(()=>{if(i.current&&o.current){let u=i.current,d=o.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=u.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return h.observe(u),()=>{cancelAnimationFrame(f),h.unobserve(u)}}},[]),D.createElement(Ze.div,{ref:to(o,t),...s,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:l.listId},PC(e,u=>D.createElement("div",{ref:to(i,l.listInnerRef),"cmdk-list-sizer":""},u)))}),qCe=D.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:s,contentClassName:o,container:i,...a}=e;return D.createElement(RM,{open:n,onOpenChange:r},D.createElement(AM,{container:i},D.createElement(lC,{"cmdk-overlay":"",className:s}),D.createElement(cC,{"aria-label":e.label,"cmdk-dialog":"",className:o},D.createElement(sW,{ref:t,...a}))))}),YCe=D.forwardRef((e,t)=>uu(n=>n.filtered.count===0)?D.createElement(Ze.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),GCe=D.forwardRef((e,t)=>{let{progress:n,children:r,label:s="Loading...",...o}=e;return D.createElement(Ze.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":s},PC(e,i=>D.createElement("div",{"aria-hidden":!0},i)))}),$s=Object.assign(sW,{List:WCe,Item:BCe,Input:UCe,Group:VCe,Separator:HCe,Dialog:qCe,Empty:YCe,Loading:GCe});function KCe(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function ZCe(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function oW(e){let t=D.useRef(e);return sf(()=>{t.current=e}),t}var sf=typeof window>"u"?D.useEffect:D.useLayoutEffect;function oh(e){let t=D.useRef();return t.current===void 0&&(t.current=e()),t}function uu(e){let t=AD(),n=()=>e(t.snapshot());return D.useSyncExternalStore(t.subscribe,n,n)}function iW(e,t,n,r=[]){let s=D.useRef(),o=Jx();return sf(()=>{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}})(),l=r.map(u=>u.trim());o.value(e,a,l),(i=t.current)==null||i.setAttribute(sh,a),s.current=a}),s}var XCe=()=>{let[e,t]=D.useState(),n=oh(()=>new Map);return sf(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,s)=>{n.current.set(r,s),t({})}};function QCe(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function PC({asChild:e,children:t},n){return e&&D.isValidElement(t)?D.cloneElement(QCe(t),{ref:t.ref},n(t.props.children)):n(t)}var JCe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const op=D.forwardRef(({className:e,...t},n)=>c.jsx($s,{ref:n,className:X("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));op.displayName=$s.displayName;const ey=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[c.jsx(Ko,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx($s.Input,{ref:n,className:X("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})]}));ey.displayName=$s.Input.displayName;const ip=D.forwardRef(({className:e,...t},n)=>c.jsx($s.List,{ref:n,className:X("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));ip.displayName=$s.List.displayName;const ap=D.forwardRef((e,t)=>c.jsx($s.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));ap.displayName=$s.Empty.displayName;const lp=D.forwardRef(({className:e,...t},n)=>c.jsx($s.Group,{ref:n,className:X("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}));lp.displayName=$s.Group.displayName;const aW=D.forwardRef(({className:e,...t},n)=>c.jsx($s.Separator,{ref:n,className:X("-mx-1 h-px bg-border",e),...t}));aW.displayName=$s.Separator.displayName;const cp=D.forwardRef(({className:e,...t},n)=>c.jsx($s.Item,{ref:n,className:X("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}));cp.displayName=$s.Item.displayName;var OC="Checkbox",[eSe]=Lr(OC),[tSe,PD]=eSe(OC);function nSe(e){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:s,disabled:o,form:i,name:a,onCheckedChange:l,required:u,value:d="on",internal_do_not_use_render:f}=e,[h,m]=ss({prop:n,defaultProp:s??!1,onChange:l,caller:OC}),[p,g]=D.useState(null),[b,x]=D.useState(null),y=D.useRef(!1),v=p?!!i||!!p.closest("form"):!0,w={checked:h,disabled:o,setChecked:m,control:p,setControl:g,name:a,form:i,value:d,hasConsumerStoppedPropagationRef:y,required:u,defaultChecked:Xc(s)?!1:s,isFormControl:v,bubbleInput:b,setBubbleInput:x};return c.jsx(tSe,{scope:t,...w,children:rSe(f)?f(w):r})}var lW="CheckboxTrigger",cW=D.forwardRef(({__scopeCheckbox:e,onKeyDown:t,onClick:n,...r},s)=>{const{control:o,value:i,disabled:a,checked:l,required:u,setControl:d,setChecked:f,hasConsumerStoppedPropagationRef:h,isFormControl:m,bubbleInput:p}=PD(lW,e),g=ut(s,d),b=D.useRef(l);return D.useEffect(()=>{const x=o==null?void 0:o.form;if(x){const y=()=>f(b.current);return x.addEventListener("reset",y),()=>x.removeEventListener("reset",y)}},[o,f]),c.jsx(Ze.button,{type:"button",role:"checkbox","aria-checked":Xc(l)?"mixed":l,"aria-required":u,"data-state":mW(l),"data-disabled":a?"":void 0,disabled:a,value:i,...r,ref:g,onKeyDown:Ie(t,x=>{x.key==="Enter"&&x.preventDefault()}),onClick:Ie(n,x=>{f(y=>Xc(y)?!0:!y),p&&m&&(h.current=x.isPropagationStopped(),h.current||x.stopPropagation())})})});cW.displayName=lW;var OD=D.forwardRef((e,t)=>{const{__scopeCheckbox:n,name:r,checked:s,defaultChecked:o,required:i,disabled:a,value:l,onCheckedChange:u,form:d,...f}=e;return c.jsx(nSe,{__scopeCheckbox:n,checked:s,defaultChecked:o,disabled:a,required:i,onCheckedChange:u,name:r,form:d,value:l,internal_do_not_use_render:({isFormControl:h})=>c.jsxs(c.Fragment,{children:[c.jsx(cW,{...f,ref:t,__scopeCheckbox:n}),h&&c.jsx(hW,{__scopeCheckbox:n})]})})});OD.displayName=OC;var uW="CheckboxIndicator",dW=D.forwardRef((e,t)=>{const{__scopeCheckbox:n,forceMount:r,...s}=e,o=PD(uW,n);return c.jsx(vr,{present:r||Xc(o.checked)||o.checked===!0,children:c.jsx(Ze.span,{"data-state":mW(o.checked),"data-disabled":o.disabled?"":void 0,...s,ref:t,style:{pointerEvents:"none",...e.style}})})});dW.displayName=uW;var fW="CheckboxBubbleInput",hW=D.forwardRef(({__scopeCheckbox:e,...t},n)=>{const{control:r,hasConsumerStoppedPropagationRef:s,checked:o,defaultChecked:i,required:a,disabled:l,name:u,value:d,form:f,bubbleInput:h,setBubbleInput:m}=PD(fW,e),p=ut(n,m),g=$x(o),b=Tx(r);D.useEffect(()=>{const y=h;if(!y)return;const v=window.HTMLInputElement.prototype,j=Object.getOwnPropertyDescriptor(v,"checked").set,S=!s.current;if(g!==o&&j){const N=new Event("click",{bubbles:S});y.indeterminate=Xc(o),j.call(y,Xc(o)?!1:o),y.dispatchEvent(N)}},[h,g,o,s]);const x=D.useRef(Xc(o)?!1:o);return c.jsx(Ze.input,{type:"checkbox","aria-hidden":!0,defaultChecked:i??x.current,required:a,disabled:l,name:u,value:d,form:f,...t,tabIndex:-1,ref:p,style:{...t.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});hW.displayName=fW;function rSe(e){return typeof e=="function"}function Xc(e){return e==="indeterminate"}function mW(e){return Xc(e)?"indeterminate":e?"checked":"unchecked"}const cn=D.forwardRef(({className:e,...t},n)=>c.jsx(OD,{ref:n,className:X("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",e),...t,children:c.jsx(dW,{className:X("flex items-center justify-center text-current"),children:c.jsx(Ar,{className:"h-4 w-4"})})}));cn.displayName=OD.displayName;function pW({users:e,selectedUsers:t,existingUserIds:n,isLoading:r,onUserToggle:s,onSearchChange:o,currentUserId:i,placeholder:a="Search and select users..."}){const[l,u]=C.useState(!1),[d,f]=C.useState(""),h=b=>{f(b),o==null||o(b)},m=C.useMemo(()=>e.filter(b=>!(i&&b.id===i||n.includes(b.id))),[e,i,n]),p=b=>t.some(x=>x.id===b),g=()=>{const b=t.length;return b===0?a:`${b} user${b>1?"s":""} selected`};return c.jsxs(ID,{open:l,onOpenChange:u,children:[c.jsx(RD,{asChild:!0,children:c.jsxs(se,{variant:"outline",role:"combobox","aria-expanded":l,className:"w-full justify-between font-normal",children:[c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Ko,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:X(t.length===0&&"text-muted-foreground"),children:g()})]}),c.jsx(VT,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),c.jsxs(sp,{className:"z-[52] mt-1 rounded-md border bg-popover p-0 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",align:"start",sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},onOpenAutoFocus:b=>b.preventDefault(),children:[c.jsxs(op,{shouldFilter:!1,children:[c.jsx(ey,{placeholder:"Search by name, email, or department...",value:d,onValueChange:h}),c.jsx(ip,{className:"max-h-[250px] overflow-auto overscroll-contain",children:r?c.jsxs("div",{className:"flex items-center justify-center py-6",children:[c.jsx(xn,{className:"h-4 w-4 animate-spin"}),c.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading users..."})]}):m.length===0?c.jsx(ap,{children:d?"No users found matching your search.":"No users available to share with."}):c.jsx(lp,{children:m.map(b=>{const x=p(b.id);return c.jsx(cp,{value:b.id,onSelect:()=>s(b.id),className:"cursor-pointer",children:c.jsxs("div",{className:"flex w-full items-center gap-3",children:[c.jsx(cn,{checked:x,className:"pointer-events-none"}),c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"truncate font-medium",children:b.name}),c.jsx(Ve,{variant:"outline",className:"text-xs",children:b.role==="POWER_USER"?"Power User":b.role==="ADMIN"?"Admin":"Viewer"})]}),c.jsx("span",{className:"truncate text-xs text-muted-foreground",children:b.email})]}),x&&c.jsx(Ar,{className:"h-4 w-4 shrink-0 text-primary"})]})},b.id)})})})]}),t.length>0&&c.jsx("div",{className:"border-t p-2",children:c.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.length," user",t.length>1?"s":""," ","selected"]})})]})]})}var FC="Collapsible",[sSe,gW]=Lr(FC),[oSe,FD]=sSe(FC),bW=D.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:s,disabled:o,onOpenChange:i,...a}=e,[l,u]=ss({prop:r,defaultProp:s??!1,onChange:i,caller:FC});return c.jsx(oSe,{scope:n,disabled:o,contentId:xr(),open:l,onOpenToggle:D.useCallback(()=>u(d=>!d),[u]),children:c.jsx(Ze.div,{"data-state":BD(l),"data-disabled":o?"":void 0,...a,ref:t})})});bW.displayName=FC;var xW="CollapsibleTrigger",$D=D.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,s=FD(xW,n);return c.jsx(Ze.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":BD(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...r,ref:t,onClick:Ie(e.onClick,s.onOpenToggle)})});$D.displayName=xW;var LD="CollapsibleContent",zD=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=FD(LD,e.__scopeCollapsible);return c.jsx(vr,{present:n||s.open,children:({present:o})=>c.jsx(iSe,{...r,ref:t,present:o})})});zD.displayName=LD;var iSe=D.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:s,...o}=e,i=FD(LD,n),[a,l]=D.useState(r),u=D.useRef(null),d=ut(t,u),f=D.useRef(0),h=f.current,m=D.useRef(0),p=m.current,g=i.open||a,b=D.useRef(g),x=D.useRef(void 0);return D.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),Yr(()=>{const y=u.current;if(y){x.current=x.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const v=y.getBoundingClientRect();f.current=v.height,m.current=v.width,b.current||(y.style.transitionDuration=x.current.transitionDuration,y.style.animationName=x.current.animationName),l(r)}},[i.open,r]),c.jsx(Ze.div,{"data-state":BD(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...o,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":p?`${p}px`:void 0,...e.style},children:g&&s})});function BD(e){return e?"open":"closed"}var yW=bW,aSe=$D,lSe=zD;const bo=yW,xo=$D,yo=zD;function vW({existingShares:e,usersToRemove:t,usersToUpdate:n,allUsers:r,onUpdateRole:s,onRemoveAccess:o,onUndoRemove:i,onUndoUpdate:a,getRoleOptions:l,isLoading:u=!1,defaultExpanded:d=!0,userType:f="organization",selectedTenantId:h}){const[m,p]=C.useState(d),g=C.useMemo(()=>{if(!(e!=null&&e.shares))return[];if(f==="organization")return e.shares.specificOrgUsers||[];{const j=e.shares.specificTenantUsers||[];return h?j.filter(S=>S.tenantId===h):j}},[e,f,h]),b=C.useMemo(()=>g.map(j=>{const S=f==="organization"?j.orgUserId:j.tenantUserId,N=j.user,E=r.find(M=>M.id===S),_=t.includes(S),k=n.find(M=>M.id===S);return{share:j,user:N?{id:S,name:N.name||"Unknown User",email:N.email||"",role:(E==null?void 0:E.role)||"VIEWER",type:f}:null,userId:S,isMarkedForRemoval:_,updateInfo:k,displayRole:k?k.newRole:j.role}}).filter(j=>j.user),[g,r,t,n,f]),x=b.filter(j=>!j.isMarkedForRemoval).length,y=b.filter(j=>j.isMarkedForRemoval).length,v=b.filter(j=>j.updateInfo&&!j.isMarkedForRemoval).length;if(u||e===void 0)return c.jsx("div",{className:"rounded-lg border border-dashed p-4",children:c.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c.jsx(xn,{className:"h-4 w-4 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading current access..."})]})});if(g.length===0)return c.jsx("div",{className:"rounded-lg border border-dashed p-4 text-center",children:c.jsxs("p",{className:"text-sm text-muted-foreground",children:["This resource hasn't been shared with any"," ",f==="organization"?"organization":"tenant"," users yet."]})});return c.jsxs(bo,{open:m,onOpenChange:p,className:"space-y-2",children:[c.jsx(xo,{asChild:!0,children:c.jsx(se,{variant:"ghost",className:"flex w-full items-center justify-between p-2 hover:bg-muted/50",children:c.jsxs("div",{className:"flex items-center gap-2",children:[m?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx("span",{className:"text-sm font-medium",children:"Current Access"}),c.jsx(Ve,{variant:"secondary",className:"text-xs",children:x}),y>0&&c.jsxs(Ve,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:["-",y]}),v>0&&c.jsxs(Ve,{variant:"outline",className:"border-orange-200 bg-orange-50 text-xs text-orange-700",children:[v," updating"]})]})})}),c.jsx(yo,{className:"space-y-1",children:c.jsx("div",{className:"max-h-48 space-y-1 overflow-y-auto rounded-md border p-2",children:b.map(j=>w(j,l))})})]});function w({share:j,user:S,userId:N,isMarkedForRemoval:E,updateInfo:_,displayRole:k},M){if(!S)return null;const T=M(S.type);return c.jsxs("div",{className:X("flex items-center justify-between rounded-md p-2 transition-colors",E?"bg-red-50 opacity-60":_?"bg-orange-50":"hover:bg-muted/50"),children:[c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:X("truncate text-sm font-medium",E&&"line-through"),children:S.name}),c.jsx(Ve,{variant:"outline",className:"shrink-0 text-xs",children:S.role==="POWER_USER"?"Power User":S.role==="ADMIN"?"Admin":"Viewer"})]}),c.jsx("span",{className:"truncate text-xs text-muted-foreground",children:S.email})]}),c.jsx("div",{className:"flex shrink-0 items-center gap-2",children:E?c.jsxs(se,{variant:"ghost",size:"sm",onClick:()=>i(N),className:"h-7 gap-1 text-xs",children:[c.jsx(ew,{className:"h-3 w-3"}),"Undo"]}):c.jsxs(c.Fragment,{children:[c.jsx(dC,{currentRole:k,onRoleChange:P=>s(N,j.role,P),roleOptions:T,className:X(_&&"border-orange-300 bg-orange-100")}),_?c.jsx(se,{variant:"ghost",size:"sm",onClick:()=>a(N),className:"h-7 gap-1 px-2 text-xs",children:c.jsx(ew,{className:"h-3 w-3"})}):c.jsx(se,{variant:"ghost",size:"sm",onClick:()=>o(N),className:"h-7 px-2 text-destructive hover:bg-destructive/10 hover:text-destructive",children:c.jsx(ec,{className:"h-3 w-3"})})]})})]},N)}}const cSe=async(e,t,n={})=>{const r={};n.search&&(r.search=n.search),n.type&&(r.type=n.type),n.active!==void 0&&(r.active=n.active.toString()),n.tenantId&&(r.tenantId=n.tenantId),n.limit&&(r.limit=n.limit.toString()),n.offset&&(r.offset=n.offset.toString()),n.page&&(r.page=n.page.toString()),n.pageSize&&(r.pageSize=n.pageSize.toString());const s=`${e}/management/v1/unified-users`;return await rr(s,t,r)};function VD(e={}){var o,i,a;const{authToken:t,tokenProps:n}=Xe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=En({queryKey:["unified-users",e],queryFn:()=>cSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(l,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:l<2,retryDelay:l=>Math.min(1e3*2**l,3e4)});return{users:((o=s.data)==null?void 0:o.users)||[],userContext:(i=s.data)==null?void 0:i.userContext,total:((a=s.data)==null?void 0:a.total)||0,isLoading:s.isLoading,isError:s.isError,isFetching:s.isFetching,error:s.error,refetch:s.refetch}}function xm(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=Ut.DASHBOARD,userType:s,tenantId:o}=e,i=C.useMemo(()=>({search:t,active:!0,...s?{type:s}:{},...s==="tenant"&&o?{tenantId:o}:{}}),[t,s,o]),{users:a,isLoading:l,isError:u}=VD(i),d=Fde(r,n);return{allUsers:a,isLoadingUsers:l,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function uSe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var z,F;const a=_D(),l=Gx(),{setSearchQuery:u,debouncedSearchQuery:d}=zU(),f=qx(),h=np(),m=Yx(),p=ku(),g=TD(),b=rp(),[x,y]=C.useState("specific_users"),v=()=>{if(a==="org")return"organization";if(a==="tenant")return"tenant"},w=()=>{if(a==="tenant"&&l)return l},{allUsers:j,existingShares:S,isLoadingUsers:N,isLoadingShares:E}=xm({debouncedSearchQuery:d,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:v(),tenantId:w()});C.useEffect(()=>{b.setCurrentContext("org-tab"),b.setCurrentMode(x==="all_users"?"allOrgUsers":"specificOrgUsers")},[b,x]);const _=A=>{var B,Y;const H=A;if(y(H),r==null||r(H),b.setCurrentContext("org-tab"),H==="specific_users")b.setCurrentMode("specificOrgUsers");else if(H==="all_users"){b.setCurrentMode("allOrgUsers");const q=(Y=(B=S==null?void 0:S.shares)==null?void 0:B.orgUsersOnly)==null?void 0:Y[0];q&&q.role!==void 0&&b.setOrgWideRole(q.role)}},k=C.useMemo(()=>{var A;return(((A=S==null?void 0:S.shares)==null?void 0:A.specificOrgUsers)||[]).map(H=>H.orgUserId)},[S]),M=j.filter(A=>f.some(H=>H.id===A.id)),T=A=>{f.some(B=>B.id===A)?b.removeSelectedUser(A):b.addSelectedUser({id:A,role:"VIEWER"})},P=(A,H)=>{b.updateSelectedUserRole(A,H)},O=(A,H,B)=>{b.addUserToUpdate({id:A,currentRole:H,newRole:B})},I=A=>{b.addUserToRemove(A)},$=A=>{b.removeUserFromRemove(A)},V=A=>{b.removeUserFromUpdate(A)},W=(A,H)=>{b.setOrgWideRole(H)},L=()=>{b.setOrgWideRole((R==null?void 0:R.role)||"NONE")},R=(F=(z=S==null?void 0:S.shares)==null?void 0:z.orgUsersOnly)==null?void 0:F[0];return C.useEffect(()=>{x==="all_users"&&R&&R.role!==void 0&&b.setOrgWideRole(R.role)},[x,R,b]),n?c.jsxs(c.Fragment,{children:[c.jsx(zM,{shareType:x,onShareTypeChange:_,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:c.jsx(Kl,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:c.jsx(Pr,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),x==="specific_users"?c.jsxs("div",{className:"mt-3 space-y-4",children:[c.jsx(pW,{users:j,selectedUsers:f,existingUserIds:k,isLoading:N||E,onUserToggle:T,onSearchChange:u,getRoleOptions:$o,currentUserId:n==null?void 0:n.id,placeholder:"Search and select users to share with..."}),c.jsx(UB,{selectedUsers:f,selectedUserObjects:M,onRemove:T,onRoleChange:P,getRoleOptions:$o}),c.jsx(vW,{existingShares:S,usersToRemove:h,usersToUpdate:m,allUsers:j,onUpdateRole:O,onRemoveAccess:I,onUndoRemove:$,onUndoUpdate:V,getRoleOptions:$o,isLoading:N,userType:"organization"})]}):c.jsx("div",{className:"mt-3",children:c.jsx(BU,{currentUser:n,currentShare:R,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:W,onRemoveAccess:L,allUsersToUpdate:p==="allOrgUsers"&&g!==((R==null?void 0:R.role)||"NONE")?{currentRole:(R==null?void 0:R.role)||"NONE",newRole:g}:null,allUsersToRemove:p==="allOrgUsers"&&(R==null?void 0:R.role)===void 0})})]}):null}function wW({selectedGroups:e,groupObjects:t,onRemove:n,onRoleChange:r,getRoleOptions:s}){if(e.length===0)return null;const o=s();return c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",e.length,")"]}),c.jsx("div",{className:"space-y-1",children:e.map(i=>{const a=t.find(l=>l.id===i.id);return a?c.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[a.type==="ORG_GROUP"?c.jsx(ql,{className:"h-4 w-4 text-blue-600"}):c.jsx(Pr,{className:"h-4 w-4 text-green-600"}),c.jsx("span",{className:"text-sm font-medium",children:a.name}),c.jsxs(Ve,{variant:"secondary",className:"text-xs",children:[a.memberCount," members"]}),a.type==="TENANT_GROUP"&&a.tenantName&&c.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",a.tenantName]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(dC,{currentRole:i.role,onRoleChange:l=>r(i.id,l),roleOptions:o}),c.jsx(se,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>n(i.id),children:c.jsx(St,{className:"h-3 w-3"})})]})]},i.id):null})})]})}const ms=ID,ps=RD,gs=D.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>c.jsx(_Ce,{children:c.jsx(Za,{children:c.jsx(sp,{ref:s,align:t,sideOffset:n,className:X("z-49 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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),...r})})}));gs.displayName=sp.displayName;function CW(e){switch(e){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function SW(e){switch(e){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function jW({groups:e,selectedGroups:t,existingGroupIds:n,isLoading:r,onGroupToggle:s,placeholder:o="Search and select groups..."}){const[i,a]=C.useState(!1),[l,u]=C.useState(""),d=C.useMemo(()=>e.filter(p=>!n.includes(p.id)),[e,n]),f=C.useMemo(()=>{if(!l)return d;const p=l.toLowerCase();return d.filter(g=>g.name.toLowerCase().includes(p)||g.description&&g.description.toLowerCase().includes(p)||g.tenantName&&g.tenantName.toLowerCase().includes(p))},[d,l]),h=p=>t.some(g=>g.id===p),m=()=>{const p=t.length;return p===0?o:`${p} group${p>1?"s":""} selected`};return c.jsxs(ms,{open:i,onOpenChange:a,children:[c.jsx(ps,{asChild:!0,children:c.jsxs(se,{variant:"outline",role:"combobox","aria-expanded":i,className:"w-full justify-between font-normal",children:[c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Ko,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:X(t.length===0&&"text-muted-foreground"),children:m()})]}),c.jsx(VT,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),c.jsxs(gs,{className:"w-[400px] p-0",align:"start",children:[c.jsxs(op,{shouldFilter:!1,children:[c.jsx(ey,{placeholder:"Search by name or description...",value:l,onValueChange:u}),c.jsx(ip,{children:r?c.jsxs("div",{className:"flex items-center justify-center py-6",children:[c.jsx(xn,{className:"h-4 w-4 animate-spin"}),c.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading groups..."})]}):f.length===0?c.jsx(ap,{children:l?"No groups found matching your search.":"No groups available to share with."}):c.jsx(lp,{children:f.map(p=>{const g=h(p.id);return c.jsx(cp,{value:p.id,onSelect:()=>s(p.id),className:"cursor-pointer",children:c.jsxs("div",{className:"flex w-full items-center gap-3",children:[c.jsx(cn,{checked:g,className:"pointer-events-none"}),c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"truncate font-medium",children:p.name}),p.type==="ORG_GROUP"?c.jsx(ql,{className:"h-3 w-3 shrink-0 text-blue-600"}):c.jsx(Pr,{className:"h-3 w-3 shrink-0 text-green-600"}),c.jsxs(Ve,{variant:"secondary",className:"shrink-0 text-xs",children:[p.memberCount," members"]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:X("text-xs",SW(p.type)),children:CW(p.type)}),p.type==="TENANT_GROUP"&&p.tenantName&&c.jsx("span",{className:"text-xs text-muted-foreground",children:p.tenantName})]}),p.description&&c.jsx("span",{className:"truncate text-xs text-muted-foreground",children:p.description})]}),g&&c.jsx(Ar,{className:"h-4 w-4 shrink-0 text-primary"})]})},p.id)})})})]}),t.length>0&&c.jsx("div",{className:"border-t p-2",children:c.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.length," group",t.length>1?"s":""," ","selected"]})})]})]})}function NW({existingGroupShares:e,groupsToRemove:t,groupsToUpdate:n,allGroups:r,onUpdateRole:s,onRemoveAccess:o,onUndoRemove:i,onUndoUpdate:a,getRoleOptions:l,isLoading:u=!1,defaultExpanded:d=!0}){const[f,h]=C.useState(d),m=C.useMemo(()=>e.map(y=>{const v=r.find(S=>S.id===y.groupId),w=t.includes(y.groupId),j=n.find(S=>S.id===y.groupId);return{share:y,group:v,groupId:y.groupId,isMarkedForRemoval:w,updateInfo:j,displayRole:j?j.newRole:y.role}}).filter(y=>y.group),[e,r,t,n]),p=m.filter(y=>!y.isMarkedForRemoval).length,g=m.filter(y=>y.isMarkedForRemoval).length,b=m.filter(y=>y.updateInfo&&!y.isMarkedForRemoval).length,x=l();return u?c.jsx("div",{className:"rounded-lg border border-dashed p-4",children:c.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c.jsx(xn,{className:"h-4 w-4 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading current access..."})]})}):e.length===0?c.jsx("div",{className:"rounded-lg border border-dashed p-4 text-center",children:c.jsx("p",{className:"text-sm text-muted-foreground",children:"This resource hasn't been shared with any groups yet."})}):c.jsxs(bo,{open:f,onOpenChange:h,className:"space-y-2",children:[c.jsx(xo,{asChild:!0,children:c.jsx(se,{variant:"ghost",className:"flex w-full items-center justify-between p-2 hover:bg-muted/50",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx("span",{className:"text-sm font-medium",children:"Current Access"}),c.jsx(Ve,{variant:"secondary",className:"text-xs",children:p}),g>0&&c.jsxs(Ve,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:["-",g]}),b>0&&c.jsxs(Ve,{variant:"outline",className:"border-orange-200 bg-orange-50 text-xs text-orange-700",children:[b," updating"]})]})})}),c.jsx(yo,{className:"space-y-1",children:c.jsx("div",{className:"max-h-48 space-y-1 overflow-y-auto rounded-md border p-2",children:m.map(({share:y,group:v,groupId:w,isMarkedForRemoval:j,updateInfo:S,displayRole:N})=>v?c.jsxs("div",{className:X("flex items-center justify-between rounded-md p-2 transition-colors",j?"bg-red-50 opacity-60":S?"bg-orange-50":"hover:bg-muted/50"),children:[c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:X("truncate text-sm font-medium",j&&"line-through"),children:v.name}),v.type==="ORG_GROUP"?c.jsx(ql,{className:"h-3 w-3 shrink-0 text-blue-600"}):c.jsx(Pr,{className:"h-3 w-3 shrink-0 text-green-600"}),c.jsxs(Ve,{variant:"secondary",className:"shrink-0 text-xs",children:[v.memberCount," members"]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:X("text-xs",SW(v.type)),children:CW(v.type)}),v.type==="TENANT_GROUP"&&v.tenantName&&c.jsx("span",{className:"text-xs text-muted-foreground",children:v.tenantName})]})]}),c.jsx("div",{className:"flex shrink-0 items-center gap-2",children:j?c.jsxs(se,{variant:"ghost",size:"sm",onClick:()=>i(w),className:"h-7 gap-1 text-xs",children:[c.jsx(ew,{className:"h-3 w-3"}),"Undo"]}):c.jsxs(c.Fragment,{children:[c.jsx(dC,{currentRole:N,onRoleChange:E=>s(w,y.role,E),roleOptions:x,className:X(S&&"border-orange-300 bg-orange-100")}),S?c.jsx(se,{variant:"ghost",size:"sm",onClick:()=>a(w),className:"h-7 gap-1 px-2 text-xs",children:c.jsx(ew,{className:"h-3 w-3"})}):c.jsx(se,{variant:"ghost",size:"sm",onClick:()=>o(w),className:"h-7 px-2 text-destructive hover:bg-destructive/10 hover:text-destructive",children:c.jsx(ec,{className:"h-3 w-3"})})]})})]},w):null)})})]})}const dSe=async(e,t,n={})=>{const r={};n.search&&(r.search=n.search),n.type&&n.type!=="all"&&(r.type=n.type),n.tenantId&&(r.tenantId=n.tenantId),n.organizationId&&(r.organizationId=n.organizationId),n.includeMembers!==void 0&&(r.includeMembers=n.includeMembers.toString()),n.page&&(r.page=n.page.toString()),n.limit&&(r.limit=n.limit.toString());const s=`${e}/management/v1/groups`;return await rr(s,t,r)},fSe=async(e,t,n)=>{const r=`${e}/management/v1/groups/${n}/members`;return await rr(r,t)};function HD(e={}){var o,i,a;const{authToken:t,tokenProps:n}=Xe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=En({queryKey:["groups",e],queryFn:()=>dSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(l,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:l<2,retryDelay:l=>Math.min(1e3*2**l,3e4),staleTime:6e4});return{groups:((o=s.data)==null?void 0:o.groups)||[],total:((i=s.data)==null?void 0:i.total)||0,hasMore:((a=s.data)==null?void 0:a.hasMore)||!1,isLoading:s.isLoading,isError:s.isError,error:s.error,isFetching:s.isFetching,refetch:s.refetch}}function hSe(e){const{authToken:t,tokenProps:n}=Xe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId);return En({queryKey:["group-members",e],queryFn:()=>fSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r&&!!e,retry:1,staleTime:6e4})}function kW(e,t){const{tokenProps:n}=Xe(),r={limit:100};return e==="organization"||n!=null&&n.orgUserId?(r.type="all",t&&(r.tenantId=t)):(e==="tenant"||n!=null&&n.endUserId)&&(r.type="TENANT_GROUP",(t||n!=null&&n.tenantId)&&(r.tenantId=t||n.tenantId)),HD(r)}function Ib(e,[t,n]){return Math.min(n,Math.max(t,e))}function mSe(e){const t=pSe(e),n=D.forwardRef((r,s)=>{const{children:o,...i}=r,a=D.Children.toArray(o),l=a.find(bSe);if(l){const u=l.props.children,d=a.map(f=>f===l?D.Children.count(u)>1?D.Children.only(null):D.isValidElement(u)?u.props.children:null:f);return c.jsx(t,{...i,ref:s,children:D.isValidElement(u)?D.cloneElement(u,void 0,d):null})}return c.jsx(t,{...i,ref:s,children:o})});return n.displayName=`${e}.Slot`,n}function pSe(e){const t=D.forwardRef((n,r)=>{const{children:s,...o}=n;if(D.isValidElement(s)){const i=ySe(s),a=xSe(o,s.props);return s.type!==D.Fragment&&(a.ref=r?to(r,i):i),D.cloneElement(s,a)}return D.Children.count(s)>1?D.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var gSe=Symbol("radix.slottable");function bSe(e){return D.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===gSe}function xSe(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...a)=>{const l=o(...a);return s(...a),l}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function ySe(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var vSe=[" ","Enter","ArrowUp","ArrowDown"],wSe=[" ","Enter"],of="Select",[$C,LC,CSe]=Ex(of),[up]=Lr(of,[CSe,Ka]),zC=Ka(),[SSe,_u]=up(of),[jSe,NSe]=up(of),EW=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:s,onOpenChange:o,value:i,defaultValue:a,onValueChange:l,dir:u,name:d,autoComplete:f,disabled:h,required:m,form:p}=e,g=zC(t),[b,x]=D.useState(null),[y,v]=D.useState(null),[w,j]=D.useState(!1),S=bu(u),[N,E]=ss({prop:r,defaultProp:s??!1,onChange:o,caller:of}),[_,k]=ss({prop:i,defaultProp:a,onChange:l,caller:of}),M=D.useRef(null),T=b?p||!!b.closest("form"):!0,[P,O]=D.useState(new Set),I=Array.from(P).map($=>$.props.value).join(";");return c.jsx(zm,{...g,children:c.jsxs(SSe,{required:m,scope:t,trigger:b,onTriggerChange:x,valueNode:y,onValueNodeChange:v,valueNodeHasChildren:w,onValueNodeHasChildrenChange:j,contentId:xr(),value:_,onValueChange:k,open:N,onOpenChange:E,dir:S,triggerPointerDownPosRef:M,disabled:h,children:[c.jsx($C.Provider,{scope:t,children:c.jsx(jSe,{scope:e.__scopeSelect,onNativeOptionAdd:D.useCallback($=>{O(V=>new Set(V).add($))},[]),onNativeOptionRemove:D.useCallback($=>{O(V=>{const W=new Set(V);return W.delete($),W})},[]),children:n})}),T?c.jsxs(QW,{"aria-hidden":!0,required:m,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:$=>k($.target.value),disabled:h,form:p,children:[_===void 0?c.jsx("option",{value:""}):null,Array.from(P)]},I):null]})})};EW.displayName=of;var _W="SelectTrigger",TW=D.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=zC(n),i=_u(_W,n),a=i.disabled||r,l=ut(t,i.onTriggerChange),u=LC(n),d=D.useRef("touch"),[f,h,m]=eq(g=>{const b=u().filter(v=>!v.disabled),x=b.find(v=>v.value===i.value),y=tq(b,g,x);y!==void 0&&i.onValueChange(y.value)}),p=g=>{a||(i.onOpenChange(!0),m()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return c.jsx(Bm,{asChild:!0,...o,children:c.jsx(Ze.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":JW(i.value)?"":void 0,...s,ref:l,onClick:Ie(s.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&p(g)}),onPointerDown:Ie(s.onPointerDown,g=>{d.current=g.pointerType;const b=g.target;b.hasPointerCapture(g.pointerId)&&b.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(p(g),g.preventDefault())}),onKeyDown:Ie(s.onKeyDown,g=>{const b=f.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(b&&g.key===" ")&&vSe.includes(g.key)&&(p(),g.preventDefault())})})})});TW.displayName=_W;var MW="SelectValue",DW=D.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:i="",...a}=e,l=_u(MW,n),{onValueNodeHasChildrenChange:u}=l,d=o!==void 0,f=ut(t,l.onValueNodeChange);return Yr(()=>{u(d)},[u,d]),c.jsx(Ze.span,{...a,ref:f,style:{pointerEvents:"none"},children:JW(l.value)?c.jsx(c.Fragment,{children:i}):o})});DW.displayName=MW;var kSe="SelectIcon",IW=D.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return c.jsx(Ze.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});IW.displayName=kSe;var ESe="SelectPortal",RW=e=>c.jsx(yf,{asChild:!0,...e});RW.displayName=ESe;var af="SelectContent",AW=D.forwardRef((e,t)=>{const n=_u(af,e.__scopeSelect),[r,s]=D.useState();if(Yr(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?Bd.createPortal(c.jsx(PW,{scope:e.__scopeSelect,children:c.jsx($C.Slot,{scope:e.__scopeSelect,children:c.jsx("div",{children:e.children})})}),o):null}return c.jsx(OW,{...e,ref:t})});AW.displayName=af;var Ri=10,[PW,Tu]=up(af),_Se="SelectContentImpl",TSe=mSe("SelectContent.RemoveScroll"),OW=D.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:i,side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:m,sticky:p,hideWhenDetached:g,avoidCollisions:b,...x}=e,y=_u(af,n),[v,w]=D.useState(null),[j,S]=D.useState(null),N=ut(t,q=>w(q)),[E,_]=D.useState(null),[k,M]=D.useState(null),T=LC(n),[P,O]=D.useState(!1),I=D.useRef(!1);D.useEffect(()=>{if(v)return J1(v)},[v]),G1();const $=D.useCallback(q=>{const[U,...G]=T().map(K=>K.ref.current),[Z]=G.slice(-1),Q=document.activeElement;for(const K of q)if(K===Q||(K==null||K.scrollIntoView({block:"nearest"}),K===U&&j&&(j.scrollTop=0),K===Z&&j&&(j.scrollTop=j.scrollHeight),K==null||K.focus(),document.activeElement!==Q))return},[T,j]),V=D.useCallback(()=>$([E,v]),[$,E,v]);D.useEffect(()=>{P&&V()},[P,V]);const{onOpenChange:W,triggerPointerDownPosRef:L}=y;D.useEffect(()=>{if(v){let q={x:0,y:0};const U=Z=>{var Q,K;q={x:Math.abs(Math.round(Z.pageX)-(((Q=L.current)==null?void 0:Q.x)??0)),y:Math.abs(Math.round(Z.pageY)-(((K=L.current)==null?void 0:K.y)??0))}},G=Z=>{q.x<=10&&q.y<=10?Z.preventDefault():v.contains(Z.target)||W(!1),document.removeEventListener("pointermove",U),L.current=null};return L.current!==null&&(document.addEventListener("pointermove",U),document.addEventListener("pointerup",G,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",U),document.removeEventListener("pointerup",G,{capture:!0})}}},[v,W,L]),D.useEffect(()=>{const q=()=>W(!1);return window.addEventListener("blur",q),window.addEventListener("resize",q),()=>{window.removeEventListener("blur",q),window.removeEventListener("resize",q)}},[W]);const[R,z]=eq(q=>{const U=T().filter(Q=>!Q.disabled),G=U.find(Q=>Q.ref.current===document.activeElement),Z=tq(U,q,G);Z&&setTimeout(()=>Z.ref.current.focus())}),F=D.useCallback((q,U,G)=>{const Z=!I.current&&!G;(y.value!==void 0&&y.value===U||Z)&&(_(q),Z&&(I.current=!0))},[y.value]),A=D.useCallback(()=>v==null?void 0:v.focus(),[v]),H=D.useCallback((q,U,G)=>{const Z=!I.current&&!G;(y.value!==void 0&&y.value===U||Z)&&M(q)},[y.value]),B=r==="popper"?FE:FW,Y=B===FE?{side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:m,sticky:p,hideWhenDetached:g,avoidCollisions:b}:{};return c.jsx(PW,{scope:n,content:v,viewport:j,onViewportChange:S,itemRefCallback:F,selectedItem:E,onItemLeave:A,itemTextRefCallback:H,focusSelectedItem:V,selectedItemText:k,position:r,isPositioned:P,searchRef:R,children:c.jsx(Rx,{as:TSe,allowPinchZoom:!0,children:c.jsx(Fm,{asChild:!0,trapped:y.open,onMountAutoFocus:q=>{q.preventDefault()},onUnmountAutoFocus:Ie(s,q=>{var U;(U=y.trigger)==null||U.focus({preventScroll:!0}),q.preventDefault()}),children:c.jsx(xf,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:q=>q.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:c.jsx(B,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:q=>q.preventDefault(),...x,...Y,onPlaced:()=>O(!0),ref:N,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:Ie(x.onKeyDown,q=>{const U=q.ctrlKey||q.altKey||q.metaKey;if(q.key==="Tab"&&q.preventDefault(),!U&&q.key.length===1&&z(q.key),["ArrowUp","ArrowDown","Home","End"].includes(q.key)){let Z=T().filter(Q=>!Q.disabled).map(Q=>Q.ref.current);if(["ArrowUp","End"].includes(q.key)&&(Z=Z.slice().reverse()),["ArrowUp","ArrowDown"].includes(q.key)){const Q=q.target,K=Z.indexOf(Q);Z=Z.slice(K+1)}setTimeout(()=>$(Z)),q.preventDefault()}})})})})})})});OW.displayName=_Se;var MSe="SelectItemAlignedPosition",FW=D.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=_u(af,n),i=Tu(af,n),[a,l]=D.useState(null),[u,d]=D.useState(null),f=ut(t,N=>d(N)),h=LC(n),m=D.useRef(!1),p=D.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:x,focusSelectedItem:y}=i,v=D.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&u&&g&&b&&x){const N=o.trigger.getBoundingClientRect(),E=u.getBoundingClientRect(),_=o.valueNode.getBoundingClientRect(),k=x.getBoundingClientRect();if(o.dir!=="rtl"){const Q=k.left-E.left,K=_.left-Q,te=N.left-K,le=N.width+te,de=Math.max(le,E.width),ce=window.innerWidth-Ri,Ce=Ib(K,[Ri,Math.max(Ri,ce-de)]);a.style.minWidth=le+"px",a.style.left=Ce+"px"}else{const Q=E.right-k.right,K=window.innerWidth-_.right-Q,te=window.innerWidth-N.right-K,le=N.width+te,de=Math.max(le,E.width),ce=window.innerWidth-Ri,Ce=Ib(K,[Ri,Math.max(Ri,ce-de)]);a.style.minWidth=le+"px",a.style.right=Ce+"px"}const M=h(),T=window.innerHeight-Ri*2,P=g.scrollHeight,O=window.getComputedStyle(u),I=parseInt(O.borderTopWidth,10),$=parseInt(O.paddingTop,10),V=parseInt(O.borderBottomWidth,10),W=parseInt(O.paddingBottom,10),L=I+$+P+W+V,R=Math.min(b.offsetHeight*5,L),z=window.getComputedStyle(g),F=parseInt(z.paddingTop,10),A=parseInt(z.paddingBottom,10),H=N.top+N.height/2-Ri,B=T-H,Y=b.offsetHeight/2,q=b.offsetTop+Y,U=I+$+q,G=L-U;if(U<=H){const Q=M.length>0&&b===M[M.length-1].ref.current;a.style.bottom="0px";const K=u.clientHeight-g.offsetTop-g.offsetHeight,te=Math.max(B,Y+(Q?A:0)+K+V),le=U+te;a.style.height=le+"px"}else{const Q=M.length>0&&b===M[0].ref.current;a.style.top="0px";const te=Math.max(H,I+g.offsetTop+(Q?F:0)+Y)+G;a.style.height=te+"px",g.scrollTop=U-H+g.offsetTop}a.style.margin=`${Ri}px 0`,a.style.minHeight=R+"px",a.style.maxHeight=T+"px",r==null||r(),requestAnimationFrame(()=>m.current=!0)}},[h,o.trigger,o.valueNode,a,u,g,b,x,o.dir,r]);Yr(()=>v(),[v]);const[w,j]=D.useState();Yr(()=>{u&&j(window.getComputedStyle(u).zIndex)},[u]);const S=D.useCallback(N=>{N&&p.current===!0&&(v(),y==null||y(),p.current=!1)},[v,y]);return c.jsx(ISe,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:m,onScrollButtonChange:S,children:c.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:w},children:c.jsx(Ze.div,{...s,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});FW.displayName=MSe;var DSe="SelectPopperPosition",FE=D.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=Ri,...o}=e,i=zC(n);return c.jsx(Mx,{...i,...o,ref:t,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});FE.displayName=DSe;var[ISe,UD]=up(af,{}),$E="SelectViewport",$W=D.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Tu($E,n),i=UD($E,n),a=ut(t,o.onViewportChange),l=D.useRef(0);return c.jsxs(c.Fragment,{children:[c.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),c.jsx($C.Slot,{scope:n,children:c.jsx(Ze.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...s.style},onScroll:Ie(s.onScroll,u=>{const d=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const m=Math.abs(l.current-d.scrollTop);if(m>0){const p=window.innerHeight-Ri*2,g=parseFloat(f.style.minHeight),b=parseFloat(f.style.height),x=Math.max(g,b);if(x<p){const y=x+m,v=Math.min(p,y),w=y-v;f.style.height=v+"px",f.style.bottom==="0px"&&(d.scrollTop=w>0?w:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});$W.displayName=$E;var LW="SelectGroup",[RSe,ASe]=up(LW),zW=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=xr();return c.jsx(RSe,{scope:n,id:s,children:c.jsx(Ze.div,{role:"group","aria-labelledby":s,...r,ref:t})})});zW.displayName=LW;var BW="SelectLabel",VW=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=ASe(BW,n);return c.jsx(Ze.div,{id:s.id,...r,ref:t})});VW.displayName=BW;var Ow="SelectItem",[PSe,HW]=up(Ow),UW=D.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...i}=e,a=_u(Ow,n),l=Tu(Ow,n),u=a.value===r,[d,f]=D.useState(o??""),[h,m]=D.useState(!1),p=ut(t,y=>{var v;return(v=l.itemRefCallback)==null?void 0:v.call(l,y,r,s)}),g=xr(),b=D.useRef("touch"),x=()=>{s||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return c.jsx(PSe,{scope:n,value:r,disabled:s,textId:g,isSelected:u,onItemTextChange:D.useCallback(y=>{f(v=>v||((y==null?void 0:y.textContent)??"").trim())},[]),children:c.jsx($C.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:c.jsx(Ze.div,{role:"option","aria-labelledby":g,"data-highlighted":h?"":void 0,"aria-selected":u&&h,"data-state":u?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...i,ref:p,onFocus:Ie(i.onFocus,()=>m(!0)),onBlur:Ie(i.onBlur,()=>m(!1)),onClick:Ie(i.onClick,()=>{b.current!=="mouse"&&x()}),onPointerUp:Ie(i.onPointerUp,()=>{b.current==="mouse"&&x()}),onPointerDown:Ie(i.onPointerDown,y=>{b.current=y.pointerType}),onPointerMove:Ie(i.onPointerMove,y=>{var v;b.current=y.pointerType,s?(v=l.onItemLeave)==null||v.call(l):b.current==="mouse"&&y.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ie(i.onPointerLeave,y=>{var v;y.currentTarget===document.activeElement&&((v=l.onItemLeave)==null||v.call(l))}),onKeyDown:Ie(i.onKeyDown,y=>{var w;((w=l.searchRef)==null?void 0:w.current)!==""&&y.key===" "||(wSe.includes(y.key)&&x(),y.key===" "&&y.preventDefault())})})})})});UW.displayName=Ow;var pg="SelectItemText",WW=D.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,i=_u(pg,n),a=Tu(pg,n),l=HW(pg,n),u=NSe(pg,n),[d,f]=D.useState(null),h=ut(t,x=>f(x),l.onItemTextChange,x=>{var y;return(y=a.itemTextRefCallback)==null?void 0:y.call(a,x,l.value,l.disabled)}),m=d==null?void 0:d.textContent,p=D.useMemo(()=>c.jsx("option",{value:l.value,disabled:l.disabled,children:m},l.value),[l.disabled,l.value,m]),{onNativeOptionAdd:g,onNativeOptionRemove:b}=u;return Yr(()=>(g(p),()=>b(p)),[g,b,p]),c.jsxs(c.Fragment,{children:[c.jsx(Ze.span,{id:l.textId,...o,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Bd.createPortal(o.children,i.valueNode):null]})});WW.displayName=pg;var qW="SelectItemIndicator",YW=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return HW(qW,n).isSelected?c.jsx(Ze.span,{"aria-hidden":!0,...r,ref:t}):null});YW.displayName=qW;var LE="SelectScrollUpButton",GW=D.forwardRef((e,t)=>{const n=Tu(LE,e.__scopeSelect),r=UD(LE,e.__scopeSelect),[s,o]=D.useState(!1),i=ut(t,r.onScrollButtonChange);return Yr(()=>{if(n.viewport&&n.isPositioned){let a=function(){const u=l.scrollTop>0;o(u)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),s?c.jsx(ZW,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});GW.displayName=LE;var zE="SelectScrollDownButton",KW=D.forwardRef((e,t)=>{const n=Tu(zE,e.__scopeSelect),r=UD(zE,e.__scopeSelect),[s,o]=D.useState(!1),i=ut(t,r.onScrollButtonChange);return Yr(()=>{if(n.viewport&&n.isPositioned){let a=function(){const u=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<u;o(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),s?c.jsx(ZW,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});KW.displayName=zE;var ZW=D.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Tu("SelectScrollButton",n),i=D.useRef(null),a=LC(n),l=D.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return D.useEffect(()=>()=>l(),[l]),Yr(()=>{var d;const u=a().find(f=>f.ref.current===document.activeElement);(d=u==null?void 0:u.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),c.jsx(Ze.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:Ie(s.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:Ie(s.onPointerMove,()=>{var u;(u=o.onItemLeave)==null||u.call(o),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:Ie(s.onPointerLeave,()=>{l()})})}),OSe="SelectSeparator",XW=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c.jsx(Ze.div,{"aria-hidden":!0,...r,ref:t})});XW.displayName=OSe;var BE="SelectArrow",FSe=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=zC(n),o=_u(BE,n),i=Tu(BE,n);return o.open&&i.position==="popper"?c.jsx(Dx,{...s,...r,ref:t}):null});FSe.displayName=BE;var $Se="SelectBubbleInput",QW=D.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const s=D.useRef(null),o=ut(r,s),i=$x(t);return D.useEffect(()=>{const a=s.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),c.jsx(Ze.select,{...n,style:{...b7,...n.style},ref:o,defaultValue:t})});QW.displayName=$Se;function JW(e){return e===""||e===void 0}function eq(e){const t=qr(e),n=D.useRef(""),r=D.useRef(0),s=D.useCallback(i=>{const a=n.current+i;t(a),function l(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),o=D.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return D.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function tq(e,t,n){const s=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let i=LSe(e,Math.max(o,0));s.length===1&&(i=i.filter(u=>u!==n));const l=i.find(u=>u.textValue.toLowerCase().startsWith(s.toLowerCase()));return l!==n?l:void 0}function LSe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var zSe=EW,nq=TW,BSe=DW,VSe=IW,HSe=RW,rq=AW,USe=$W,WSe=zW,sq=VW,oq=UW,qSe=WW,YSe=YW,iq=GW,aq=KW,lq=XW;const ot=zSe,WD=WSe,at=BSe,nt=D.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(nq,{ref:r,className:X("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-0 focus:ring-ring focus:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,c.jsx(VSe,{asChild:!0,children:c.jsx(kr,{className:"h-4 w-4 opacity-50"})})]}));nt.displayName=nq.displayName;const cq=D.forwardRef(({className:e,...t},n)=>c.jsx(iq,{ref:n,className:X("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Ch,{className:"h-4 w-4"})}));cq.displayName=iq.displayName;const uq=D.forwardRef(({className:e,...t},n)=>c.jsx(aq,{ref:n,className:X("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(kr,{className:"h-4 w-4"})}));uq.displayName=aq.displayName;const rt=D.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>c.jsx(HSe,{children:c.jsx(Za,{children:c.jsxs(rq,{ref:s,className:X("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[c.jsx(cq,{}),c.jsx(USe,{className:X("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),c.jsx(uq,{})]})})}));rt.displayName=rq.displayName;const BC=D.forwardRef(({className:e,...t},n)=>c.jsx(sq,{ref:n,className:X("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));BC.displayName=sq.displayName;const ve=D.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(oq,{ref:r,className:X("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx(YSe,{children:c.jsx(Ar,{className:"h-4 w-4"})})}),c.jsx(qSe,{children:t})]}));ve.displayName=oq.displayName;const GSe=D.forwardRef(({className:e,...t},n)=>c.jsx(lq,{ref:n,className:X("-mx-1 my-1 h-px bg-muted",e),...t}));GSe.displayName=lq.displayName;function z5({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var Ne;const a=qx(),l=np(),u=Yx(),d=Kx(),f=Zx(),h=Xx(),{setSearchQuery:m,debouncedSearchQuery:p}=zU(),g=ku(),b=RC(),x=MD(),y=Gx(),v=rp(),{data:w,isLoading:j}=I7({enabled:(n==null?void 0:n.type)==="organization"}),{groups:S,isLoading:N}=kW("tenant",(n==null?void 0:n.tenantId)||y),[E,_]=C.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");C.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(v.setCurrentContext("tenant-dialog"),v.setCurrentMode("specificTenantUsers")):(v.setCurrentContext("tenant-tab"),v.setCurrentMode("allTenants"))},[v,n==null?void 0:n.type]);const k=fe=>{var ke,ie,xe,Oe;_(fe);let Me;if(fe==="specific_tenant_users"?Me="specific_users":fe==="all_tenant_users"||fe==="all_tenants"?Me="all_users":fe==="groups"?Me="groups":Me="specific_users",r==null||r(Me),fe==="groups"?(v.setCurrentContext("group-share"),v.setCurrentMode("specificGroups")):(n==null?void 0:n.type)==="tenant"?(v.setCurrentContext("tenant-dialog"),fe==="specific_tenant_users"?v.setCurrentMode("specificTenantUsers"):fe==="all_tenant_users"&&(v.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&v.setSelectedTenant(n.tenantId))):(v.setCurrentContext("tenant-tab"),fe==="specific_tenant_users"?v.setCurrentMode("specificTenantUsers"):fe==="all_tenant_users"?v.setCurrentMode("allTenantUsers"):fe==="all_tenants"&&v.setCurrentMode("allTenants")),fe==="all_tenant_users"){const be=(ie=(ke=P==null?void 0:P.shares)==null?void 0:ke.tenantWide)==null?void 0:ie[0];be&&be.role!==void 0&&v.setTenantWideRole(be.role)}else if(fe==="all_tenants"){const be=(Oe=(xe=P==null?void 0:P.shares)==null?void 0:xe.allTenantsOnly)==null?void 0:Oe[0];be&&be.role!==void 0&&v.setAllTenantsRole(be.role)}},M=fe=>{v.setSelectedTenant(fe)},{allUsers:T,existingShares:P,isLoadingUsers:O,isErrorLoadingUsers:I,isLoadingShares:$,isErrorLoadingShares:V}=xm({debouncedSearchQuery:p,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:y}),W=C.useMemo(()=>{var fe;return(((fe=P==null?void 0:P.shares)==null?void 0:fe.specificTenantUsers)||[]).map(Me=>Me.tenantUserId)},[P]),L=fe=>{a.some(ke=>ke.id===fe)?v.removeSelectedUser(fe):v.addSelectedUser({id:fe,role:"VIEWER"})},R=(fe,Me)=>{v.updateSelectedUserRole(fe,Me)},z=(fe,Me,ke)=>{v.addUserToUpdate({id:fe,currentRole:Me,newRole:ke})},F=fe=>{v.addUserToRemove(fe)},A=fe=>{v.removeUserFromRemove(fe)},H=fe=>{v.removeUserFromUpdate(fe)},B=(fe,Me)=>{E==="all_tenant_users"?v.setTenantWideRole(Me):E==="all_tenants"&&v.setAllTenantsRole(Me)},Y=()=>{E==="all_tenant_users"?v.setTenantWideRole("VIEWER"):E==="all_tenants"&&v.setAllTenantsRole("VIEWER")},U=(()=>{var fe,Me,ke,ie;return g==="allTenants"?(Me=(fe=P==null?void 0:P.shares)==null?void 0:fe.allTenantsOnly)==null?void 0:Me[0]:g==="allTenantUsers"?(ie=(ke=P==null?void 0:P.shares)==null?void 0:ke.tenantWide)==null?void 0:ie[0]:null})();C.useEffect(()=>{var fe,Me,ke,ie;if(E==="all_tenant_users"){const xe=(Me=(fe=P==null?void 0:P.shares)==null?void 0:fe.tenantWide)==null?void 0:Me[0];xe&&xe.role!==void 0&&v.setTenantWideRole(xe.role)}else if(E==="all_tenants"){const xe=(ie=(ke=P==null?void 0:P.shares)==null?void 0:ke.allTenantsOnly)==null?void 0:ie[0];xe&&xe.role!==void 0&&v.setAllTenantsRole(xe.role)}},[E,P,v]);const G=T.filter(fe=>a.some(Me=>Me.id===fe.id)),Z=fe=>{const Me=d.some(xe=>xe.id===fe),ke=f.includes(fe),ie=ge==null?void 0:ge.some(xe=>xe.groupId===fe);Me?v.removeSelectedGroup(fe):ke?v.removeGroupFromRemove(fe):ie||v.addSelectedGroup({id:fe,role:"VIEWER"})},Q=(fe,Me)=>{v.updateSelectedGroupRole(fe,Me)},K=fe=>{v.addGroupToRemove(fe),v.removeSelectedGroup(fe)},te=(fe,Me,ke)=>{v.addGroupToUpdate({id:fe,currentRole:Me,newRole:ke})},le=fe=>{v.removeGroupFromRemove(fe)},de=fe=>{v.removeGroupFromUpdate(fe)},ce=S.filter(fe=>d.some(Me=>Me.id===fe.id)),Ce=C.useMemo(()=>E!=="groups"?[]:S.filter(fe=>fe.type==="TENANT_GROUP"),[S,E]),ge=C.useMemo(()=>{var Me,ke;const fe=((Me=P==null?void 0:P.shares)==null?void 0:Me.specificGroups)||((ke=P==null?void 0:P.shares)==null?void 0:ke.groups)||[];return!fe||fe.length===0?[]:fe.filter(ie=>{const xe=S.find(Oe=>Oe.id===ie.groupId);return(xe==null?void 0:xe.type)==="TENANT_GROUP"})},[P,S]),he=C.useMemo(()=>ge.map(fe=>fe.groupId),[ge]),me=I||V,oe=()=>(n==null?void 0:n.type)==="tenant"||E==="all_tenants"||E==="groups"?!0:y&&(E==="specific_tenant_users"||E==="all_tenant_users");return c.jsxs(c.Fragment,{children:[me&&c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsxs("div",{className:"text-center",children:[c.jsx(Yl,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),c.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),c.jsx(se,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!me&&n&&c.jsxs("div",{className:"space-y-4",children:[c.jsx(zM,{shareType:E,onShareTypeChange:k,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:c.jsx(Pr,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:c.jsx(Kl,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:c.jsx(Pr,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:c.jsx(RP,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:c.jsx(hb,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:c.jsx(Kl,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(E==="specific_tenant_users"||E==="all_tenant_users")&&c.jsxs("div",{className:"mt-4",children:[c.jsx(ae,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),c.jsxs(ot,{value:y||"",onValueChange:M,disabled:j,children:[c.jsx(nt,{className:"w-full",children:c.jsx(at,{placeholder:j?"Loading tenants...":"Select a tenant..."})}),c.jsx(rt,{className:"z-[51]",children:(Ne=w==null?void 0:w.tenants)==null?void 0:Ne.map(fe=>c.jsx(ve,{value:fe.id,children:fe.name},fe.id))})]})]}),oe()?c.jsx(c.Fragment,{children:E==="specific_tenant_users"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(pW,{users:T,selectedUsers:a,existingUserIds:W,isLoading:O||$,onUserToggle:L,onSearchChange:m,getRoleOptions:$o,currentUserId:n==null?void 0:n.id,placeholder:"Search and select users to share with..."}),c.jsx(UB,{selectedUsers:a,selectedUserObjects:G,onRemove:fe=>L(fe),onRoleChange:R,getRoleOptions:$o}),c.jsx(vW,{existingShares:P,usersToRemove:l,usersToUpdate:u,allUsers:T,onUpdateRole:z,onRemoveAccess:F,onUndoRemove:A,onUndoUpdate:H,getRoleOptions:$o,userType:"tenant",selectedTenantId:y})]}):E==="groups"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(jW,{groups:Ce,selectedGroups:d,existingGroupIds:he,isLoading:N,onGroupToggle:Z,getRoleOptions:$o,placeholder:"Search and select groups to share with..."}),c.jsx(wW,{selectedGroups:d,groupObjects:ce,onRemove:Z,onRoleChange:Q,getRoleOptions:$o}),c.jsx(NW,{existingGroupShares:ge,groupsToRemove:f,groupsToUpdate:h,allGroups:Ce,onUpdateRole:te,onRemoveAccess:K,onUndoRemove:le,onUndoUpdate:de,getRoleOptions:$o,isLoading:$})]}):E==="all_tenant_users"||E==="all_tenants"?c.jsx("div",{className:"mt-6",children:c.jsx(BU,{currentUser:n,currentShare:U,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:B,onRemoveAccess:Y,allUsersToUpdate:g==="allTenantUsers"&&((U==null?void 0:U.role)===void 0||b!==U.role)||g==="allTenants"&&((U==null?void 0:U.role)===void 0||x!==U.role)?{currentRole:(U==null?void 0:U.role)||"VIEWER",newRole:g==="allTenantUsers"?b:x}:null,allUsersToRemove:g==="allTenantUsers"&&(U==null?void 0:U.role)===void 0||g==="allTenants"&&(U==null?void 0:U.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(E==="specific_tenant_users"||E==="all_tenant_users")&&c.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:c.jsxs("div",{className:"text-center",children:[c.jsx(RP,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function KSe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var W,L;const a=Kx(),l=Zx(),u=Xx(),d=rp(),[f,h]=C.useState("org_groups"),[m,p]=C.useState(""),{data:g,isLoading:b}=I7({enabled:(n==null?void 0:n.type)==="organization"&&f==="tenant_groups"}),x=Array.isArray(g)?g:(g==null?void 0:g.tenants)||[],y=()=>{if((n==null?void 0:n.type)==="organization")return"organization";if((n==null?void 0:n.type)==="tenant")return"tenant"},{groups:v,isLoading:w}=kW(y(),f==="tenant_groups"&&(n==null?void 0:n.type)==="organization"?m:n==null?void 0:n.tenantId),{existingShares:j,isLoadingShares:S}=xm({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t}),N=C.useMemo(()=>v.filter(R=>!(f==="org_groups"&&R.type!=="ORG_GROUP"||f==="tenant_groups"&&R.type!=="TENANT_GROUP"||f==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&(!m||R.tenantId&&R.tenantId!==m))),[v,f,m,n==null?void 0:n.type]),E=((W=j==null?void 0:j.shares)==null?void 0:W.specificGroups)||((L=j==null?void 0:j.shares)==null?void 0:L.groups)||[],_=C.useMemo(()=>E.map(R=>R.groupId),[E]);C.useEffect(()=>{d.setCurrentContext("group-share"),d.setCurrentMode("specificGroups")},[d]);const k=R=>{const z=R;h(z),z==="org_groups"&&p(""),r==null||r(z==="org_groups"?"specific_groups":"all_groups"),d.setCurrentContext("group-share"),d.setCurrentMode("specificGroups")},M=v.filter(R=>a.some(z=>z.id===R.id)),T=R=>{a.some(F=>F.id===R)?d.removeSelectedGroup(R):d.addSelectedGroup({id:R,role:"VIEWER"})},P=(R,z)=>{d.updateSelectedGroupRole(R,z)},O=(R,z,F)=>{d.addGroupToUpdate({id:R,currentRole:z,newRole:F})},I=R=>{d.addGroupToRemove(R)},$=R=>{d.removeGroupFromRemove(R)},V=R=>{d.removeGroupFromUpdate(R)};return n?c.jsxs(c.Fragment,{children:[c.jsx(zM,{shareType:f,onShareTypeChange:k,currentUser:n,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:c.jsx(ql,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:c.jsx(Pr,{className:"mb-3 h-6 w-6 text-green-500"})}]}),f==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsx(ae,{children:"Select Tenant"}),c.jsxs(ot,{value:m,onValueChange:p,disabled:b,children:[c.jsx(nt,{className:"w-full",children:c.jsx(at,{placeholder:b?"Loading tenants...":"Select a tenant to view its groups"})}),c.jsx(rt,{className:"z-[51]",children:x.map(R=>c.jsx(ve,{className:"hover:bg-muted",value:R.id,children:R.name},R.id))})]})]}),c.jsx("div",{className:"mt-3 space-y-2",children:f==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&!m?c.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:c.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):c.jsxs(c.Fragment,{children:[c.jsx(jW,{groups:N,selectedGroups:a,existingGroupIds:_,isLoading:w,onGroupToggle:T,getRoleOptions:$o,placeholder:"Search and select groups to share with..."}),c.jsx(wW,{selectedGroups:a,groupObjects:M,onRemove:T,onRoleChange:P,getRoleOptions:$o}),c.jsx(NW,{existingGroupShares:E,groupsToRemove:l,groupsToUpdate:u,allGroups:v,onUpdateRole:O,onRemoveAccess:I,onUndoRemove:$,onUndoUpdate:V,getRoleOptions:$o,isLoading:S})]})})]}):null}const dq=()=>{const e=$U(),t=ku(),n=qx(),r=np(),s=Yx(),o=Kx(),i=Zx(),a=Xx(),l=Gx(),u=TD(),d=MD(),f=RC(),h=LU(),m=C.useMemo(()=>()=>Qfe({currentContext:e,currentMode:t,selectedUsers:n,usersToRemove:r,usersToUpdate:s,selectedGroups:o,groupsToRemove:i,groupsToUpdate:a,selectedTenant:l,orgWideRole:u,allTenantsRole:d,tenantWideRole:f}),[e,t,n,r,s,o,i,a,l,u,d,f,h]),p=C.useMemo(()=>b=>fV(b),[]),g=C.useMemo(()=>{if(!e||!t)return!1;switch(e){case"org-tab":return t==="specificOrgUsers"?n.length>0||r.length>0||s.length>0:!0;case"tenant-tab":if(t==="allTenantUsers"){if(!l)return!1}else if(t==="specificTenantUsers")return l?n.length>0||r.length>0||s.length>0:!1;return!0;case"tenant-dialog":return t==="specificTenantUsers"?n.length>0||r.length>0||s.length>0:!0;case"group-share":return t==="specificGroups"?o.length>0||i.length>0||a.length>0:!0}return!1},[e,t,n,r,s,o,i,a,l]);return{buildShareData:m,validateShareData:p,isCurrentStateValid:g,currentContext:e,currentMode:t,selectedUsers:n,usersToRemove:r,usersToUpdate:s,selectedTenant:l,orgWideRole:u,allTenantsRole:d,tenantWideRole:f}};function B5({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllUsersShare:l,onRemoveAccess:u}){const d=qx(),f=np(),h=Yx(),m=Gx(),p=TD(),g=MD(),b=RC(),{buildShareData:x,validateShareData:y,isCurrentStateValid:v}=dq(),w=n||r||s,j=()=>{var k,M,T,P;if(w)return"Updating...";if(a==="specific_users"){if(d.length===0&&f.length===0&&h.length===0)return"Select users to share with";const O=d.length+f.length+h.length;return O===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${O} user${O!==1?"s":""}`:f.length>0&&d.length===0&&h.length===0?`Remove access for ${f.length} user${f.length!==1?"s":""}`:d.length>0&&f.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&f.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${O} user${O!==1?"s":""}`}else if(a==="all_users"){if(!l||l.role===void 0)return"Share with All Users";const O=l.role;return p===O?"Remove Access":"Update Access"}else if(a==="all_tenants"){const O=(M=(k=t==null?void 0:t.shares)==null?void 0:k.allTenantsOnly)==null?void 0:M[0];if(!O||O.role===void 0)return"Share with All Tenants";const I=O.role;return g===I?"Remove Access":"Update Access"}else if(a==="all_tenant_users"){const O=(P=(T=t==null?void 0:t.shares)==null?void 0:T.tenantWide)==null?void 0:P[0];if(!O||O.role===void 0)return"Share with All Tenant Users";const I=O.role;return b===I?"Remove Access":"Update Access"}else if(a==="specific_tenant_users"){if(d.length===0&&f.length===0&&h.length===0)return"Select users to share with";const O=d.length+f.length+h.length;return O===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${O} user${O!==1?"s":""}`:f.length>0&&d.length===0&&h.length===0?`Remove access for ${f.length} user${f.length!==1?"s":""}`:d.length>0&&f.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&f.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${O} user${O!==1?"s":""}`}return"Share"},S=()=>w||!e||a==="all_tenant_users"&&!m||a==="specific_tenant_users"&&!m?!0:!v,N=()=>{const k=x();k&&y(k)&&o(k)},E=()=>{var k,M,T,P;if(a==="all_users")if(!l||l.role===void 0){const O=x();O&&y(O)&&o(O)}else{const O=l.role;if(p===O)u==null||u();else{const $=x();if($&&y($)){const V={...$,updateAccess:!0};o(V)}}}else if(a==="all_tenants"){const O=(M=(k=t==null?void 0:t.shares)==null?void 0:k.allTenantsOnly)==null?void 0:M[0];if(!O||O.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=O.role;if(g===I)u==null||u();else{const V=x();if(V&&y(V)){const W={...V,updateAccess:!0};o(W)}}}}else if(a==="all_tenant_users"){const O=(P=(T=t==null?void 0:t.shares)==null?void 0:T.tenantWide)==null?void 0:P[0];if(!O||O.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=O.role;if(b===I)u==null||u();else{const V=x();if(V&&y(V)){const W={...V,updateAccess:!0};o(W)}}}}},_=()=>{var k,M,T,P;if(a==="all_users"){if(!l||l.role===void 0)return"default";const O=l.role;return p===O?"destructive":"default"}else if(a==="all_tenants"){const O=(M=(k=t==null?void 0:t.shares)==null?void 0:k.allTenantsOnly)==null?void 0:M[0];if(!O||O.role===void 0)return"default";const I=O.role;return g===I?"destructive":"default"}else if(a==="all_tenant_users"){const O=(P=(T=t==null?void 0:t.shares)==null?void 0:T.tenantWide)==null?void 0:P[0];if(!O||O.role===void 0)return"default";const I=O.role;return b===I?"destructive":"default"}return"default"};return c.jsxs(os,{children:[c.jsxs(se,{variant:"outline",onClick:i,disabled:w,children:[c.jsx(St,{className:"mr-2 h-4 w-4"}),"Close"]}),(a==="specific_users"||a==="specific_tenant_users")&&c.jsx(c.Fragment,{children:(d.length>0||f.length>0||h.length>0)&&c.jsxs(se,{onClick:N,disabled:!e||w,variant:"default",children:[w?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Sh,{className:"mr-2 h-4 w-4"}),!w&&j()]})}),(a==="all_users"||a==="all_tenants"||a==="all_tenant_users")&&c.jsxs(se,{onClick:E,disabled:S(),variant:_(),children:[w?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Pr,{className:"mr-2 h-4 w-4"}),!w&&j()]})]})}function ZSe({resource:e,isSharing:t,isRemoving:n,isUpdating:r,onShare:s,onClose:o,shareTabType:i,currentAllUsersShare:a}){const l=qx(),u=np(),d=Yx(),f=Kx(),h=Zx(),m=Xx();ku(),$U();const p=RC();Gx();const{buildShareData:g,validateShareData:b,isCurrentStateValid:x}=dq(),y=t||n||r,v=()=>{if(y)return"Updating...";if(i==="specific_users"){if(l.length===0&&u.length===0&&d.length===0)return"Select users to share with";const _=l.length+u.length+d.length;return _===0?"Select users to share with":l.length>0&&u.length>0?`Update access for ${_} user${_!==1?"s":""}`:u.length>0&&l.length===0&&d.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:l.length>0&&u.length===0&&d.length===0?`Share with ${l.length} user${l.length!==1?"s":""}`:d.length>0&&l.length===0&&u.length===0?`Update access for ${d.length} user${d.length!==1?"s":""}`:`Update access for ${_} user${_!==1?"s":""}`}else if(i==="groups"){if(f.length===0&&h.length===0&&m.length===0)return"Select groups to share with";const _=f.length+h.length+m.length;return _===0?"Select groups to share with":f.length>0&&h.length>0?`Update access for ${_} group${_!==1?"s":""}`:h.length>0&&f.length===0&&m.length===0?`Remove access for ${h.length} group${h.length!==1?"s":""}`:f.length>0&&h.length===0&&m.length===0?`Share with ${f.length} group${f.length!==1?"s":""}`:m.length>0&&f.length===0&&h.length===0?`Update access for ${m.length} group${m.length!==1?"s":""}`:`Update access for ${_} group${_!==1?"s":""}`}else if(i==="all_users"){if(!a||a.role==="NONE")return"Share with All Users";const _=a.role;return p===_?"Remove Access":"Update Access"}return"Share"},w=()=>y||!e?!0:!x,j=()=>{const _=g();_&&b(_)&&s(_)},S=()=>{const _=g();_&&b(_)&&s(_)},N=()=>{if(!a||a.role==="NONE"){const _=g();_&&b(_)&&s(_)}else{const _=a.role;if(p===_){const M=g();if(M&&b(M)){const T={...M,removeAccess:!0};s(T)}}else{const M=g();if(M&&b(M)){const T={...M,updateAccess:!0};s(T)}}}},E=()=>!a||a.role==="NONE"?"default":"destructive";return c.jsxs(os,{children:[c.jsxs(se,{variant:"outline",onClick:o,disabled:y,children:[c.jsx(St,{className:"mr-2 h-4 w-4"}),"Close"]}),i==="specific_users"&&c.jsx(c.Fragment,{children:(l.length>0||u.length>0||d.length>0)&&c.jsxs(se,{onClick:j,disabled:!e||y,variant:"default",children:[y?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Sh,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="groups"&&c.jsx(c.Fragment,{children:(f.length>0||h.length>0||m.length>0)&&c.jsxs(se,{onClick:S,disabled:!e||y,variant:"default",children:[y?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Sh,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="all_users"&&c.jsxs(se,{onClick:N,disabled:w(),variant:E(),children:[y?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Sh,{className:"mr-2 h-4 w-4"}),!y&&v()]})]})}function XSe({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllGroupsShare:l,onRemoveAccess:u}){const d=Kx(),f=Zx(),h=Xx();LU(),ku();const m=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:d,groupsToRemove:f,groupsToUpdate:h})},p=()=>d.length>0||f.length>0||h.length>0,g=()=>f.length>0&&d.length===0&&h.length===0?"Remove Access":h.length>0&&d.length===0&&f.length===0?"Update Access":"Share with Groups",b=n||r||s;return c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"text-sm text-muted-foreground",children:[d.length>0&&c.jsxs("span",{children:[d.length," groups selected"]}),f.length>0&&c.jsxs("span",{className:"ml-2 text-destructive",children:["• ",f.length," to remove"]}),h.length>0&&c.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",h.length," to update"]})]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(se,{variant:"outline",onClick:i,disabled:b,children:"Cancel"}),c.jsxs(se,{onClick:m,disabled:!p()||b,children:[b&&c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),g()]})]})]})}function Eo(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function Sl(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function QSe(e,t,n){const{resourceType:r,resourceId:s,shareMutation:o,removeMutation:i,existingShares:a,resetUserSelections:l}=t;if(s)switch(e.context){case"org-tab":if(e.mode==="allOrgUsers"){const u=Eo(r,s,[{scope:"org_users_only",role:e.orgWideRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:d,usersToUpdate:f}=e;if(u&&u.length>0){const h=Eo(r,s,u.map(m=>({scope:"specific_org_user",orgUserId:m.id,role:m.role})));o(h,{onSuccess:()=>{l()}})}if(d&&d.length>0){const h=Sl(r,s,d.map(m=>{var g,b;const p=(b=(g=a==null?void 0:a.shares)==null?void 0:g.specificOrgUsers)==null?void 0:b.find(x=>x.orgUserId===m);return{scope:"specific_org_user",orgUserId:m,role:(p==null?void 0:p.role)||"VIEWER"}}));i(h,{onSuccess:()=>{l()}})}f&&f.length>0&&f.forEach(h=>{const m=Eo(r,s,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);o(m,{onSuccess:()=>{l()}})})}break;case"tenant-tab":if(e.mode==="allTenants"){const u=Eo(r,s,[{scope:"all_tenants_only",role:e.allTenantsRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="allTenantUsers"){const u=Eo(r,s,[{scope:"all_tenant_users",tenantId:e.tenantId,role:e.tenantWideRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:d,usersToUpdate:f,tenantId:h}=e;if(d&&d.length>0){const m=Sl(r,s,d.map(p=>{var b,x;const g=(x=(b=a==null?void 0:a.shares)==null?void 0:b.specificTenantUsers)==null?void 0:x.find(y=>y.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,tenantId:h,role:(g==null?void 0:g.role)||"VIEWER"}}));i(m,{onSuccess:()=>{l()}})}if(f&&f.length>0&&f.forEach(m=>{const p=Eo(r,s,[{scope:"specific_tenant_user",tenantUserId:m.id,tenantId:h,role:m.newRole}]);o(p,{onSuccess:()=>{l()}})}),u&&u.length>0){const m=Eo(r,s,u.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.role})));o(m,{onSuccess:()=>{l()}})}}break;case"tenant-dialog":if(e.mode==="allTenantUsers")if(e.removeAccess){const u=Sl(r,s,[{scope:"all_tenant_users",role:"VIEWER"}]);i(u,{onSuccess:()=>{l()}})}else if(e.updateAccess){const u=Eo(r,s,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:e.tenantWideRole}]);o(u,{onSuccess:()=>{l()}})}else{const u=Eo(r,s,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:e.tenantWideRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:d,usersToUpdate:f}=e;if(u&&u.length>0){const h=Eo(r,s,u.map(m=>({scope:"specific_tenant_user",tenantUserId:m.id,role:m.role})));o(h,{onSuccess:()=>{l()}})}if(d&&d.length>0){const h=Sl(r,s,d.map(m=>{var g,b;const p=(b=(g=a==null?void 0:a.shares)==null?void 0:g.specificTenantUsers)==null?void 0:b.find(x=>x.tenantUserId===m);return{scope:"specific_tenant_user",tenantUserId:m,role:(p==null?void 0:p.role)||"VIEWER"}}));i(h,{onSuccess:()=>{l()}})}f&&f.length>0&&f.forEach(h=>{const m=Eo(r,s,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);o(m,{onSuccess:()=>{l()}})})}break;case"group-share":if(e.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:d,groupsToUpdate:f}=e;if(u&&u.length>0){const h=Eo(r,s,u.map(m=>({scope:"group",groupId:m.id,role:m.role})));o(h,{onSuccess:()=>{var m;l(),(m=t.resetGroupSelections)==null||m.call(t),ze.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(d&&d.length>0){const h=Sl(r,s,d.map(m=>({scope:"group",groupId:m,role:"VIEWER"})));i(h,{onSuccess:()=>{var m;l(),(m=t.resetGroupSelections)==null||m.call(t),ze.success(`Removed access from ${d.length} group${d.length!==1?"s":""}`)}})}f&&f.length>0&&f.forEach(h=>{const m=Eo(r,s,[{scope:"group",groupId:h.id,role:h.newRole}]);o(m,{onSuccess:()=>{var p;l(),(p=t.resetGroupSelections)==null||p.call(t),ze.success("Updated access for group")}})})}break}}function JSe(e,t,n,r){var u,d,f,h,m,p;const{resourceType:s,resourceId:o,removeMutation:i,existingShares:a,resetUserSelections:l}=r;if(o)if(e.length>0){const g=Sl(s,o,e.map(b=>{var y,v;const x=(v=(y=a==null?void 0:a.shares)==null?void 0:y.specificTenantUsers)==null?void 0:v.find(w=>w.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,role:(x==null?void 0:x.role)||"VIEWER"}}));i(g,{onSuccess:()=>{l()},onError:b=>{console.error("Remove access failed:",b)}})}else{const g=t==="tenant"&&n==="allTenants",b=t==="tenant"&&n==="allTenantUsers";if(g){const x=(d=(u=a==null?void 0:a.shares)==null?void 0:u.allTenantsOnly)==null?void 0:d[0];if(x){const y=Sl(s,o,[{scope:"all_tenants_only",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove all-tenants access failed:",v)}})}}else if(b){const x=(h=(f=a==null?void 0:a.shares)==null?void 0:f.tenantWide)==null?void 0:h[0];if(x){const y=Sl(s,o,[{scope:"all_tenant_users",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove all-tenant-users access failed:",v)}})}}else{const x=(p=(m=a==null?void 0:a.shares)==null?void 0:m.orgUsersOnly)==null?void 0:p[0];if(x){const y=Sl(s,o,[{scope:"org_users_only",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove org-wide access failed:",v)}})}}}}function eje(e,t,n){const r=rp(),s=np(),o=_D(),i=ku(),{currentUser:a}=Ps(),{existingShares:l}=xm({debouncedSearchQuery:"",resourceId:e||"",resourceType:Ut.DASHBOARD,userType:"tenant"}),u=C.useCallback(()=>{r.resetUserSelections()},[r]),d=C.useCallback(()=>{r.resetGroupSelections()},[r]),f=C.useCallback(m=>{if(!e)return;const p={resourceType:Ut.DASHBOARD,resourceId:e,shareMutation:t,removeMutation:n,existingShares:l,resetUserSelections:u,resetGroupSelections:d};QSe(m,p,a)},[e,t,n,l,u,d,a]),h=C.useCallback(()=>{if(!e)return;const m={resourceType:Ut.DASHBOARD,resourceId:e,removeMutation:n,existingShares:l,resetUserSelections:u};JSe(s,o||"",i||"",m)},[e,t,n,l,u,d,s,o,i]);return{handleShareSubmit:f,handleRemoveAccess:h}}function tje(e,t){return D.useReducer((n,r)=>t[n][r]??n,e)}var qD="ScrollArea",[fq]=Lr(qD),[nje,Si]=fq(qD),hq=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:s,scrollHideDelay:o=600,...i}=e,[a,l]=D.useState(null),[u,d]=D.useState(null),[f,h]=D.useState(null),[m,p]=D.useState(null),[g,b]=D.useState(null),[x,y]=D.useState(0),[v,w]=D.useState(0),[j,S]=D.useState(!1),[N,E]=D.useState(!1),_=ut(t,M=>l(M)),k=bu(s);return c.jsx(nje,{scope:n,type:r,dir:k,scrollHideDelay:o,scrollArea:a,viewport:u,onViewportChange:d,content:f,onContentChange:h,scrollbarX:m,onScrollbarXChange:p,scrollbarXEnabled:j,onScrollbarXEnabledChange:S,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:N,onScrollbarYEnabledChange:E,onCornerWidthChange:y,onCornerHeightChange:w,children:c.jsx(Ze.div,{dir:k,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":x+"px","--radix-scroll-area-corner-height":v+"px",...e.style}})})});hq.displayName=qD;var mq="ScrollAreaViewport",pq=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:s,...o}=e,i=Si(mq,n),a=D.useRef(null),l=ut(t,a,i.onViewportChange);return c.jsxs(c.Fragment,{children:[c.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),c.jsx(Ze.div,{"data-radix-scroll-area-viewport":"",...o,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});pq.displayName=mq;var Xa="ScrollAreaScrollbar",YD=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Si(Xa,e.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:i}=s,a=e.orientation==="horizontal";return D.useEffect(()=>(a?o(!0):i(!0),()=>{a?o(!1):i(!1)}),[a,o,i]),s.type==="hover"?c.jsx(rje,{...r,ref:t,forceMount:n}):s.type==="scroll"?c.jsx(sje,{...r,ref:t,forceMount:n}):s.type==="auto"?c.jsx(gq,{...r,ref:t,forceMount:n}):s.type==="always"?c.jsx(GD,{...r,ref:t}):null});YD.displayName=Xa;var rje=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Si(Xa,e.__scopeScrollArea),[o,i]=D.useState(!1);return D.useEffect(()=>{const a=s.scrollArea;let l=0;if(a){const u=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),s.scrollHideDelay)};return a.addEventListener("pointerenter",u),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",u),a.removeEventListener("pointerleave",d)}}},[s.scrollArea,s.scrollHideDelay]),c.jsx(vr,{present:n||o,children:c.jsx(gq,{"data-state":o?"visible":"hidden",...r,ref:t})})}),sje=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Si(Xa,e.__scopeScrollArea),o=e.orientation==="horizontal",i=HC(()=>l("SCROLL_END"),100),[a,l]=tje("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return D.useEffect(()=>{if(a==="idle"){const u=window.setTimeout(()=>l("HIDE"),s.scrollHideDelay);return()=>window.clearTimeout(u)}},[a,s.scrollHideDelay,l]),D.useEffect(()=>{const u=s.viewport,d=o?"scrollLeft":"scrollTop";if(u){let f=u[d];const h=()=>{const m=u[d];f!==m&&(l("SCROLL"),i()),f=m};return u.addEventListener("scroll",h),()=>u.removeEventListener("scroll",h)}},[s.viewport,o,l,i]),c.jsx(vr,{present:n||a!=="hidden",children:c.jsx(GD,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Ie(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:Ie(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),gq=D.forwardRef((e,t)=>{const n=Si(Xa,e.__scopeScrollArea),{forceMount:r,...s}=e,[o,i]=D.useState(!1),a=e.orientation==="horizontal",l=HC(()=>{if(n.viewport){const u=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?u:d)}},10);return ym(n.viewport,l),ym(n.content,l),c.jsx(vr,{present:r||o,children:c.jsx(GD,{"data-state":o?"visible":"hidden",...s,ref:t})})}),GD=D.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,s=Si(Xa,e.__scopeScrollArea),o=D.useRef(null),i=D.useRef(0),[a,l]=D.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),u=wq(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:u>0&&u<1,onThumbChange:h=>o.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,m){return uje(h,i.current,a,m)}return n==="horizontal"?c.jsx(oje,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const h=s.viewport.scrollLeft,m=V5(h,a,s.dir);o.current.style.transform=`translate3d(${m}px, 0, 0)`}},onWheelScroll:h=>{s.viewport&&(s.viewport.scrollLeft=h)},onDragScroll:h=>{s.viewport&&(s.viewport.scrollLeft=f(h,s.dir))}}):n==="vertical"?c.jsx(ije,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const h=s.viewport.scrollTop,m=V5(h,a);o.current.style.transform=`translate3d(0, ${m}px, 0)`}},onWheelScroll:h=>{s.viewport&&(s.viewport.scrollTop=h)},onDragScroll:h=>{s.viewport&&(s.viewport.scrollTop=f(h))}}):null}),oje=D.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Si(Xa,e.__scopeScrollArea),[i,a]=D.useState(),l=D.useRef(null),u=ut(t,l,o.onScrollbarXChange);return D.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c.jsx(xq,{"data-orientation":"horizontal",...s,ref:u,sizes:n,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":VC(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(o.viewport){const h=o.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),Sq(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&o.viewport&&i&&r({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:$w(i.paddingLeft),paddingEnd:$w(i.paddingRight)}})}})}),ije=D.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Si(Xa,e.__scopeScrollArea),[i,a]=D.useState(),l=D.useRef(null),u=ut(t,l,o.onScrollbarYChange);return D.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c.jsx(xq,{"data-orientation":"vertical",...s,ref:u,sizes:n,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":VC(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(o.viewport){const h=o.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),Sq(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&o.viewport&&i&&r({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:$w(i.paddingTop),paddingEnd:$w(i.paddingBottom)}})}})}),[aje,bq]=fq(Xa),xq=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:s,onThumbChange:o,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:u,onWheelScroll:d,onResize:f,...h}=e,m=Si(Xa,n),[p,g]=D.useState(null),b=ut(t,_=>g(_)),x=D.useRef(null),y=D.useRef(""),v=m.viewport,w=r.content-r.viewport,j=qr(d),S=qr(l),N=HC(f,10);function E(_){if(x.current){const k=_.clientX-x.current.left,M=_.clientY-x.current.top;u({x:k,y:M})}}return D.useEffect(()=>{const _=k=>{const M=k.target;(p==null?void 0:p.contains(M))&&j(k,w)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[v,p,w,j]),D.useEffect(S,[r,S]),ym(p,N),ym(m.content,N),c.jsx(aje,{scope:n,scrollbar:p,hasThumb:s,onThumbChange:qr(o),onThumbPointerUp:qr(i),onThumbPositionChange:S,onThumbPointerDown:qr(a),children:c.jsx(Ze.div,{...h,ref:b,style:{position:"absolute",...h.style},onPointerDown:Ie(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),x.current=p.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",m.viewport&&(m.viewport.style.scrollBehavior="auto"),E(_))}),onPointerMove:Ie(e.onPointerMove,E),onPointerUp:Ie(e.onPointerUp,_=>{const k=_.target;k.hasPointerCapture(_.pointerId)&&k.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=y.current,m.viewport&&(m.viewport.style.scrollBehavior=""),x.current=null})})})}),Fw="ScrollAreaThumb",yq=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=bq(Fw,e.__scopeScrollArea);return c.jsx(vr,{present:n||s.hasThumb,children:c.jsx(lje,{ref:t,...r})})}),lje=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...s}=e,o=Si(Fw,n),i=bq(Fw,n),{onThumbPositionChange:a}=i,l=ut(t,f=>i.onThumbChange(f)),u=D.useRef(void 0),d=HC(()=>{u.current&&(u.current(),u.current=void 0)},100);return D.useEffect(()=>{const f=o.viewport;if(f){const h=()=>{if(d(),!u.current){const m=dje(f,a);u.current=m,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[o.viewport,d,a]),c.jsx(Ze.div,{"data-state":i.hasThumb?"visible":"hidden",...s,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Ie(e.onPointerDownCapture,f=>{const m=f.target.getBoundingClientRect(),p=f.clientX-m.left,g=f.clientY-m.top;i.onThumbPointerDown({x:p,y:g})}),onPointerUp:Ie(e.onPointerUp,i.onThumbPointerUp)})});yq.displayName=Fw;var KD="ScrollAreaCorner",vq=D.forwardRef((e,t)=>{const n=Si(KD,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?c.jsx(cje,{...e,ref:t}):null});vq.displayName=KD;var cje=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,s=Si(KD,n),[o,i]=D.useState(0),[a,l]=D.useState(0),u=!!(o&&a);return ym(s.scrollbarX,()=>{var f;const d=((f=s.scrollbarX)==null?void 0:f.offsetHeight)||0;s.onCornerHeightChange(d),l(d)}),ym(s.scrollbarY,()=>{var f;const d=((f=s.scrollbarY)==null?void 0:f.offsetWidth)||0;s.onCornerWidthChange(d),i(d)}),u?c.jsx(Ze.div,{...r,ref:t,style:{width:o,height:a,position:"absolute",right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function $w(e){return e?parseInt(e,10):0}function wq(e,t){const n=e/t;return isNaN(n)?0:n}function VC(e){const t=wq(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function uje(e,t,n,r="ltr"){const s=VC(n),o=s/2,i=t||o,a=s-i,l=n.scrollbar.paddingStart+i,u=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return Cq([l,u],f)(e)}function V5(e,t,n="ltr"){const r=VC(t),s=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,o=t.scrollbar.size-s,i=t.content-t.viewport,a=o-r,l=n==="ltr"?[0,i]:[i*-1,0],u=Ib(e,l);return Cq([0,i],[0,a])(u)}function Cq(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 Sq(e,t){return e>0&&e<t}var dje=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function s(){const o={left:e.scrollLeft,top:e.scrollTop},i=n.left!==o.left,a=n.top!==o.top;(i||a)&&t(),n=o,r=window.requestAnimationFrame(s)}(),()=>window.cancelAnimationFrame(r)};function HC(e,t){const n=qr(e),r=D.useRef(0);return D.useEffect(()=>()=>window.clearTimeout(r.current),[]),D.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function ym(e,t){const n=qr(t);Yr(()=>{let r=0;if(e){const s=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return s.observe(e),()=>{window.cancelAnimationFrame(r),s.unobserve(e)}}},[e,n])}var UC=hq,jq=pq,Nq=vq;const ro=D.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(UC,{ref:r,className:X("relative overflow-hidden",e),...n,children:[c.jsx(jq,{className:"h-full w-full rounded-[inherit]",children:t}),c.jsx(bi,{}),c.jsx(Nq,{})]}));ro.displayName=UC.displayName;const bi=D.forwardRef(({className:e,orientation:t="vertical",...n},r)=>c.jsx(YD,{ref:r,orientation:t,className:X("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:c.jsx(yq,{className:"relative flex-1 rounded-full bg-border"})}));bi.displayName=YD.displayName;function fje({existingShares:e,isLoading:t}){var p,g,b,x,y,v,w,j,S,N,E,_,k,M,T,P,O,I,$,V,W,L;const[n,r]=C.useState(new Set(["org-users","tenant-users","groups"])),[s,o]=C.useState(new Set),i=R=>{r(z=>{const F=new Set(z);return F.has(R)?F.delete(R):F.add(R),F})},a=R=>{o(z=>{const F=new Set(z);return F.has(R)?F.delete(R):F.add(R),F})},l=C.useMemo(()=>{var F;const R=((F=e==null?void 0:e.shares)==null?void 0:F.specificTenantUsers)||[],z={};return R.forEach(A=>{var Y;const H=A.tenantId||"unknown",B=((Y=A.tenant)==null?void 0:Y.name)||"Unknown Tenant";z[H]||(z[H]={tenantName:B,users:[]}),z[H].users.push(A)}),z},[e]),u=(((g=(p=e==null?void 0:e.shares)==null?void 0:p.specificOrgUsers)==null?void 0:g.length)||0)+(((x=(b=e==null?void 0:e.shares)==null?void 0:b.orgUsersOnly)==null?void 0:x.length)||0),d=(((v=(y=e==null?void 0:e.shares)==null?void 0:y.specificTenantUsers)==null?void 0:v.length)||0)+(((j=(w=e==null?void 0:e.shares)==null?void 0:w.tenantWide)==null?void 0:j.length)||0)+(((N=(S=e==null?void 0:e.shares)==null?void 0:S.allTenantsOnly)==null?void 0:N.length)||0),f=((_=(E=e==null?void 0:e.shares)==null?void 0:E.specificGroups)==null?void 0:_.length)||0,h=u+d+f,m=R=>{switch(R){case"EDITOR":return"bg-blue-100 text-blue-800 border-blue-200";case"CONTRIBUTOR":return"bg-purple-100 text-purple-800 border-purple-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}};return c.jsxs(ID,{children:[c.jsx(RD,{asChild:!0,children:c.jsxs(se,{variant:"ghost",size:"sm",className:"gap-2",children:[c.jsx(tu,{className:"h-4 w-4"}),"Access Overview",c.jsx(Ve,{variant:"secondary",className:"ml-1",children:h})]})}),c.jsxs(sp,{align:"end",sideOffset:8,className:"z-[100] w-[400px] rounded-md border bg-popover p-0 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",children:[c.jsxs("div",{className:"border-b p-3",children:[c.jsx("h4",{className:"text-sm font-semibold",children:"Current Access"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Users and groups with access to this resource"})]}),t?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(xn,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):c.jsx(ro,{className:"h-[400px]",children:c.jsxs("div",{className:"space-y-2 p-3 pr-4",children:[c.jsxs(bo,{open:n.has("org-users"),onOpenChange:()=>i("org-users"),children:[c.jsxs(xo,{className:"flex w-full items-center gap-2 rounded-md p-2 hover:bg-muted/50",children:[n.has("org-users")?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx(ql,{className:"h-4 w-4 text-blue-500"}),c.jsx("span",{className:"text-sm font-medium",children:"Organization Users"}),c.jsx(Ve,{variant:"secondary",className:"ml-auto text-xs",children:u})]}),c.jsx(yo,{className:"pl-6",children:c.jsxs("div",{className:"space-y-1 pt-1",children:[(M=(k=e==null?void 0:e.shares)==null?void 0:k.orgUsersOnly)==null?void 0:M.map(R=>c.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted/30 p-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Pr,{className:"h-3 w-3 text-muted-foreground"}),c.jsx("span",{className:"text-xs",children:"All Org Users"})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)),(P=(T=e==null?void 0:e.shares)==null?void 0:T.specificOrgUsers)==null?void 0:P.map(R=>{var z,F;return c.jsxs("div",{className:"flex items-center justify-between rounded-md p-2 hover:bg-muted/30",children:[c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-xs font-medium",children:((z=R.user)==null?void 0:z.name)||"Unknown User"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:(F=R.user)==null?void 0:F.email})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)}),u===0&&c.jsx("p",{className:"py-2 text-xs text-muted-foreground",children:"No organization users have access"})]})})]}),c.jsxs(bo,{open:n.has("tenant-users"),onOpenChange:()=>i("tenant-users"),children:[c.jsxs(xo,{className:"flex w-full items-center gap-2 rounded-md p-2 hover:bg-muted/50",children:[n.has("tenant-users")?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx(hb,{className:"h-4 w-4 text-green-500"}),c.jsx("span",{className:"text-sm font-medium",children:"Tenant Users"}),c.jsx(Ve,{variant:"secondary",className:"ml-auto text-xs",children:d})]}),c.jsx(yo,{className:"pl-6",children:c.jsxs("div",{className:"space-y-2 pt-1",children:[(I=(O=e==null?void 0:e.shares)==null?void 0:O.allTenantsOnly)==null?void 0:I.map(R=>c.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted/30 p-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Pr,{className:"h-3 w-3 text-muted-foreground"}),c.jsx("span",{className:"text-xs",children:"All Tenants"})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)),(V=($=e==null?void 0:e.shares)==null?void 0:$.tenantWide)==null?void 0:V.map(R=>c.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted/30 p-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Pr,{className:"h-3 w-3 text-muted-foreground"}),c.jsx("span",{className:"text-xs",children:"All Tenant Users"})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)),Object.entries(l).map(([R,{tenantName:z,users:F}])=>c.jsxs(bo,{open:s.has(R),onOpenChange:()=>a(R),children:[c.jsxs(xo,{className:"flex w-full items-center gap-2 rounded-md border bg-muted/20 p-2 hover:bg-muted/40",children:[s.has(R)?c.jsx(kr,{className:"h-3 w-3"}):c.jsx(ns,{className:"h-3 w-3"}),c.jsx(hb,{className:"h-3 w-3 text-muted-foreground"}),c.jsx("span",{className:"text-xs font-medium",children:z}),c.jsx(Ve,{variant:"outline",className:"ml-auto text-xs",children:F.length})]}),c.jsx(yo,{className:"pl-4",children:c.jsx("div",{className:"space-y-1 pt-1",children:F.map(A=>{var H,B;return c.jsxs("div",{className:"flex items-center justify-between rounded-md p-2 hover:bg-muted/30",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Kl,{className:"h-3 w-3 text-muted-foreground"}),c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-xs",children:((H=A.user)==null?void 0:H.name)||"Unknown User"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:(B=A.user)==null?void 0:B.email})]})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(A.role)}`,children:A.role})]},A.id)})})})]},R)),d===0&&c.jsx("p",{className:"py-2 text-xs text-muted-foreground",children:"No tenant users have access"})]})})]}),c.jsxs(bo,{open:n.has("groups"),onOpenChange:()=>i("groups"),children:[c.jsxs(xo,{className:"flex w-full items-center gap-2 rounded-md p-2 hover:bg-muted/50",children:[n.has("groups")?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx(Pr,{className:"h-4 w-4 text-purple-500"}),c.jsx("span",{className:"text-sm font-medium",children:"Groups"}),c.jsx(Ve,{variant:"secondary",className:"ml-auto text-xs",children:f})]}),c.jsx(yo,{className:"pl-6",children:c.jsxs("div",{className:"space-y-1 pt-1",children:[(L=(W=e==null?void 0:e.shares)==null?void 0:W.specificGroups)==null?void 0:L.map(R=>{var z,F;return c.jsxs("div",{className:"flex items-center justify-between rounded-md p-2 hover:bg-muted/30",children:[c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-xs font-medium",children:((z=R.group)==null?void 0:z.name)||"Unknown Group"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:((F=R.group)==null?void 0:F.type)==="ORG_GROUP"?"Organization Group":"Tenant Group"})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)}),f===0&&c.jsx("p",{className:"py-2 text-xs text-muted-foreground",children:"No groups have access"})]})})]})]})})]})]})}function kq({resource:e,resourceType:t,onClose:n,onShareSuccess:r,onRemoveSuccess:s}){var O,I,$,V,W,L,R,z;const{currentUser:o}=Ps(),[i,a]=C.useState("specific_users"),[l,u]=C.useState("specific_users"),[d,f]=C.useState("specific_groups"),h=rp(),m=_D(),p=ku(),g=A7(),b=P7(),{handleShareSubmit:x,handleRemoveAccess:y}=eje(e.id,(F,A)=>{g.mutate(F,{...A,onSuccess:()=>{var H;(H=A==null?void 0:A.onSuccess)==null||H.call(A),r==null||r()}})},(F,A)=>{b.mutate(F,{...A,onSuccess:()=>{var H;(H=A==null?void 0:A.onSuccess)==null||H.call(A),s==null||s()}})}),v=g.isPending,w=b.isPending,j=g.isPending,{existingShares:S}=xm({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant"}),{existingShares:N,isLoadingShares:E}=xm({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"organization"}),_=(I=(O=S==null?void 0:S.shares)==null?void 0:O.tenantWide)==null?void 0:I[0],k=(V=($=N==null?void 0:N.shares)==null?void 0:$.orgUsersOnly)==null?void 0:V[0],M=()=>{if(m==="org")return l;switch(p){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},T=C.useCallback(()=>{h.resetShareState(),n()},[h,n]),P=(o==null?void 0:o.type)==="organization";return c.jsx(Gr,{open:!0,onOpenChange:T,children:c.jsxs(zr,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[c.jsxs(Br,{children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Vr,{children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Sh,{className:"h-5 w-5"}),' Share "',e==null?void 0:e.title,'"']})}),P&&c.jsx(fje,{existingShares:N,isLoading:E})]}),c.jsx(is,{children:P?"Share this resource with org users or tenant users.":"Share this resource with other users in your tenant."})]}),P?c.jsxs(Os,{value:m,onValueChange:F=>{const A=F;h.setSelectedTab(A),h.resetUserSelections(),h.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[c.jsxs(ys,{className:"mb-2 grid w-full grid-cols-3",children:[c.jsx(nn,{value:"org",children:"Org Users"}),c.jsx(nn,{value:"tenant",children:"Tenant Users"}),c.jsx(nn,{value:"groups",children:"Groups"})]}),c.jsx(pr,{value:"org",className:"mt-0 min-h-0 flex-1",children:c.jsx("div",{className:"max-h-[calc(80vh-280px)] overflow-y-auto",children:c.jsx(uSe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:u,isSharing:v,isUpdating:j,isRemoving:w})})}),c.jsx(pr,{value:"tenant",className:"mt-0 min-h-0 flex-1",children:c.jsx("div",{className:"max-h-[calc(80vh-280px)] overflow-y-auto",children:c.jsx(z5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:F=>a(F),isSharing:v,isUpdating:j,isRemoving:w})})}),c.jsx(pr,{value:"groups",className:"mt-0 min-h-0 flex-1",children:c.jsx("div",{className:"max-h-[calc(80vh-280px)] overflow-y-auto",children:c.jsx(KSe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:f,isSharing:v,isUpdating:j,isRemoving:w})})})]}):c.jsx("div",{className:"mb-4 min-h-0 flex-1",children:c.jsx("div",{className:"max-h-[calc(80vh-220px)] overflow-y-auto",children:c.jsx(z5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:F=>a(F),isSharing:v,isUpdating:j,isRemoving:w})})}),c.jsx("div",{className:"mt-auto flex-shrink-0",children:P?m==="org"?c.jsx(B5,{resource:e,existingShares:N,isSharing:v,isRemoving:w,isUpdating:j,onShare:x,onClose:n,shareTabType:l,currentAllUsersShare:k,onRemoveAccess:y}):m==="tenant"?c.jsx(B5,{resource:e,existingShares:S,isSharing:v,isRemoving:w,isUpdating:j,onShare:x,onClose:n,shareTabType:M(),currentAllUsersShare:_,onRemoveAccess:y}):c.jsx(XSe,{resource:e,existingShares:N,isSharing:v,isRemoving:w,isUpdating:j,onShare:x,onClose:n,shareTabType:d,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(L=(W=N==null?void 0:N.shares)==null?void 0:W.allOrgGroups)==null?void 0:L[0]:(z=(R=S==null?void 0:S.shares)==null?void 0:R.allTenantGroups)==null?void 0:z[0],onRemoveAccess:y}):c.jsx(ZSe,{resource:e,isSharing:v,isRemoving:w,isUpdating:j,onShare:x,onClose:n,shareTabType:i,currentAllUsersShare:_,onRemoveAccess:y})})]})})}const mn=D.forwardRef(({className:e,type:t,...n},r)=>c.jsx("input",{type:t,className:X("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-inset ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,...n}));mn.displayName="Input";function Eq({open:e,resourceLabel:t,initialTitle:n,initialDescription:r="",onClose:s,onSave:o,isSaving:i=!1}){const[a,l]=C.useState(n),[u,d]=C.useState(r??"");C.useEffect(()=>{e&&(l(n),d(r??""))},[e,n,r]);const f=h=>{h.preventDefault();const m=a.trim();m&&o({title:m,description:u.trim()})};return c.jsx(Gr,{open:e,onOpenChange:h=>h?null:s(),children:c.jsx(zr,{className:"sm:max-w-md",children:c.jsxs("form",{onSubmit:f,className:"space-y-4",children:[c.jsxs(Br,{children:[c.jsxs(Vr,{children:["Edit ",t]}),c.jsxs(is,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"resource-title",children:"Title"}),c.jsx(mn,{id:"resource-title",value:a,onChange:h=>l(h.target.value),placeholder:`Enter ${t.toLowerCase()} title`,autoFocus:!0})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"resource-description",children:"Description"}),c.jsx(vu,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),c.jsxs(os,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[c.jsx(se,{type:"button",variant:"outline",onClick:s,disabled:i,children:"Cancel"}),c.jsx(se,{type:"submit",disabled:i||!a.trim(),children:i?"Saving...":"Save changes"})]})]})})})}function hje({onDashboardSelect:e}){var G,Z;const{authToken:t}=Xe(),[n,r]=C.useState(!1),[s,o]=C.useState(!1),[i,a]=C.useState(null),[l,u]=C.useState(!1),[d,f]=C.useState(null),[h,m]=C.useState(null),[p,g]=C.useState(null),{data:b}=cB(),x=((G=b==null?void 0:b.preference)==null?void 0:G.defaultDashboardId)||null,y=hs(Q=>Q.actions.selectDashboard),{userContext:v}=Ps(),w=((Z=v==null?void 0:v.permissions)==null?void 0:Z.canCreateDashboard)??!1,{onCreateSuccess:j}=z7({onDashboardSelect:e}),{resources:S,isLoading:N,isError:E,createResource:_,updateResource:k,deleteResource:M,duplicateResource:T,isCreating:P,isUpdating:O,isDeleting:I,isDuplicating:$,refetch:V}=L7(()=>{u(!1),f(null)},Q=>{r(!1),j(Q,V)}),{startUpdating:W,stopUpdating:L,isUpdating:R}=$7(),z=Q=>{const K=S.find(te=>te.id===Q);K&&(y(K),e==null||e(Q))},F=Q=>{_({title:Q.title,description:Q.description,isPrivate:!1})},A=Q=>{f(Q),u(!0)},H=()=>{d&&M(d.id)},B=Q=>{m(Q),T(Q,{onSettled:()=>m(null)})},Y=(Q,K,te)=>{var Ce;const le=Object.fromEntries(Object.entries(K).filter(([,ge])=>ge!==void 0));if(Object.keys(le).length===0){(Ce=te==null?void 0:te.onSuccess)==null||Ce.call(te);return}const de=Object.keys(le),ce=de.length===1?de[0]:void 0;W(Q,ce),k({resourceId:Q,data:le},{onSuccess:()=>{var ge;L(Q,ce),(ge=te==null?void 0:te.onSuccess)==null||ge.call(te)},onError:()=>{var ge;L(Q,ce),(ge=te==null?void 0:te.onError)==null||ge.call(te)}})},q=Q=>{a(Q),o(!0)},U=Q=>new Date(Q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return t?N?c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"flex flex-col items-center gap-3",children:[c.jsx(xn,{className:"h-8 w-8 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading dashboards..."})]})}):E?c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"text-center",children:[c.jsx(Yl,{className:"mx-auto mb-4 h-12 w-12 text-destructive"}),c.jsx("h2",{className:"mb-2 text-lg font-semibold",children:"Error Loading Dashboards"}),c.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Unable to fetch your dashboards. Please try again."}),c.jsx(se,{onClick:()=>window.location.reload(),children:"Retry"})]})}):c.jsxs("div",{"data-content-type":"dashboard-hub",className:"flex h-full grow flex-col",children:[c.jsx("div",{className:"border-b bg-background px-6 py-8 lg:px-8",children:c.jsx("div",{className:"mx-auto max-w-7xl",children:c.jsxs("div",{className:"flex items-start justify-between",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Welcome to your analytics workspace"}),c.jsx("p",{className:"mt-2 text-muted-foreground",children:"Get started with existing dashboards or create a new one tailored to your needs"}),S.length>0&&w&&c.jsx("div",{className:"mt-6 flex gap-3",children:c.jsxs(se,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(Tr,{className:"h-4 w-4"}),"Create New Dashboard"]})})]}),S.length>0&&c.jsxs("div",{className:"rounded-md bg-orange-500 px-3 py-1 text-sm font-medium text-white",children:[S.length," dashboard",S.length!==1?"s":""]})]})})}),c.jsx("div",{className:"flex-1 overflow-y-auto bg-muted/30 px-6 py-6 lg:px-8",children:c.jsx("div",{className:"mx-auto max-w-7xl",children:S.length===0?c.jsx("div",{className:"flex h-[400px] items-center justify-center rounded-lg border-2 border-dashed",children:c.jsxs("div",{className:"text-center",children:[c.jsx(qT,{className:"mx-auto mb-4 h-12 w-12 text-muted-foreground"}),c.jsx("h3",{className:"mb-2 text-lg font-semibold",children:"No dashboards yet"}),c.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:w?"Create your first dashboard to get started with analytics":"No dashboards have been shared with you yet"}),w&&c.jsxs(se,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(Tr,{className:"h-4 w-4"}),"Create Dashboard"]})]})}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"mb-4 flex items-center justify-between",children:c.jsx("h2",{className:"text-lg font-semibold",children:"Your Dashboards"})}),c.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:S.map(Q=>c.jsx(jde,{dashboard:Q,isDefault:Q.id===x,onView:z,isDeleting:I&&(d==null?void 0:d.id)===Q.id,isDuplicating:h===Q.id,onEditDetails:g,onDeleteClick:A,onDuplicateDashboard:B,onShareDashboard:q,formatDate:U},Q.id))})]})})}),c.jsx(lB,{open:n,onOpenChange:r,onSubmit:F,isCreating:P}),p&&c.jsx(Eq,{open:!!p,resourceLabel:"Dashboard",initialTitle:p.title||"",initialDescription:p.description||"",onClose:()=>g(null),onSave:Q=>{Y(p.id,Q,{onSuccess:()=>{g(null)}})},isSaving:R(p.id)}),c.jsx(Um,{open:l,onOpenChange:u,children:c.jsxs(Sf,{children:[c.jsxs(jf,{children:[c.jsx(kf,{children:"Delete Dashboard?"}),c.jsxs(Ef,{children:['Are you sure you want to delete "',d==null?void 0:d.title,'"? This action cannot be undone.']})]}),c.jsxs(Nf,{children:[c.jsx(Tf,{disabled:I,children:"Cancel"}),c.jsx(_f,{onClick:H,disabled:I,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:I?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete"})]})]})}),i&&s&&c.jsx(kq,{resource:i,resourceType:Ut.DASHBOARD,onClose:()=>{o(!1),a(null)}})]}):c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"text-center",children:[c.jsx(Yl,{className:"mx-auto mb-4 h-12 w-12 text-muted-foreground"}),c.jsx("h2",{className:"mb-2 text-lg font-semibold",children:"Authentication Required"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Please provide authentication to view dashboards"})]})})}const Od=oa()(nz(e=>({panels:{dashboard:{isOpen:!1,container:null},editor:{isOpen:!1,container:null}},fullscreen:null,setPanelOpen:(t,n)=>e(r=>r.panels[t].isOpen===n?r:{panels:{...r.panels,[t]:{...r.panels[t],isOpen:n}},fullscreen:!n&&r.fullscreen===t?null:r.fullscreen}),setFullscreen:t=>e(n=>n.fullscreen===t?n:{fullscreen:t}),setContainer:(t,n)=>e(r=>r.panels[t].container===n?r:{panels:{...r.panels,[t]:{...r.panels[t],container:n}}})}),{name:"assistant-layout-store",partialize:e=>({panels:{dashboard:{isOpen:e.panels.dashboard.isOpen,container:null},editor:{isOpen:e.panels.editor.isOpen,container:null}},fullscreen:e.fullscreen})})),_q=e=>Od(t=>t.panels[e]),Tq=()=>Od(e=>e.fullscreen),Mq=e=>Od(t=>t.panels[e].container??null);function Dq(e){return Array.isArray(e)?e.reduce((t,n)=>n.role!=="assistant"?(t.push(n),t):n.parts.some(s=>{var o;return!!(s.type==="reasoning"&&s.state==="streaming"||s.type==="text"&&s.state==="streaming"||(o=s.type)!=null&&o.startsWith("tool-")&&s.state==="input-streaming")})?(console.log("Removing aborted assistant message:",n.id),t):(t.push(n),t),[]):e}function mje(e){const{selectedEntities:t}=e,n=t.map(r=>({...r,qualifiedEntityName:gh(r)}));return{...e,selectedEntities:n}}const H5={selectedEntities:[]},la=oa()(Im((e,t)=>({currentAIContext:H5,activeAssistantType:null,reasoningEffort:"low",showReasoning:!1,messageQueues:{dashboard:[],editor:[]},fileAttachments:{dashboard:[],editor:[]},uploadProgress:new Map,actions:{setCurrentAIContext:n=>{e(r=>{r.currentAIContext=mje(n)})},setActiveAssistantType:n=>{e(r=>{r.activeAssistantType=n})},updateSelectedEntities:n=>{e(r=>{r.currentAIContext.selectedEntities=n})},clearAIContext:()=>{e(n=>{n.currentAIContext=H5})},mergeAIContext:n=>{e(r=>{r.currentAIContext={...r.currentAIContext,...n}})},setReasoningEffort:n=>{e(r=>{r.reasoningEffort=n})},setShowReasoning:n=>{e(r=>{r.showReasoning=n})},queueMessage:(n,r,s)=>{e(o=>{o.messageQueues[n].push({id:crypto.randomUUID(),text:r,timestamp:Date.now(),fileAttachments:s})})},dequeueMessage:n=>{if(t().messageQueues[n].length===0)return;let s;return e(o=>{const i=o.messageQueues[n].shift();i&&(s={id:i.id,text:i.text,timestamp:i.timestamp})}),s},removeFromQueue:(n,r)=>{e(s=>{s.messageQueues[n]=s.messageQueues[n].filter(o=>o.id!==r)})},clearQueue:n=>{e(r=>{r.messageQueues[n]=[]})},addFileAttachment:(n,r)=>{e(s=>{s.fileAttachments[n].push(r)})},removeFileAttachment:(n,r)=>{e(s=>{s.fileAttachments[n]=s.fileAttachments[n].filter(o=>o.id!==r)})},clearFileAttachments:n=>{e(r=>{r.fileAttachments[n]=[]})},updateUploadProgress:(n,r)=>{e(s=>{s.uploadProgress.set(n,r)})},getFileAttachments:n=>t().fileAttachments[n]}}))),dp=()=>la(e=>e.currentAIContext),ZD=()=>la(e=>e.activeAssistantType),pje=()=>la(e=>e.reasoningEffort),gje=()=>la(e=>e.showReasoning),WC=()=>la(e=>e.actions),Iq=e=>la(t=>t.messageQueues[e]),fp=()=>la(bx(e=>({queueMessage:e.actions.queueMessage,dequeueMessage:e.actions.dequeueMessage,removeFromQueue:e.actions.removeFromQueue,clearQueue:e.actions.clearQueue}))),XD=e=>la(t=>t.fileAttachments[e]),QD=()=>la(bx(e=>({addFileAttachment:e.actions.addFileAttachment,removeFileAttachment:e.actions.removeFileAttachment,clearFileAttachments:e.actions.clearFileAttachments,updateUploadProgress:e.actions.updateUploadProgress,getFileAttachments:e.actions.getFileAttachments})));function Rq(){const{tokenProps:e,id:t}=Xe(),n=hs(s=>s.selectedDashboard);return hs(s=>s.showHub)?!1:!!(n!=null&&n.id||t||e!=null&&e.dashboard_id)}function JD({className:e,customStyle:t,onSave:n,onEvent:r,LoadingComponent:s,ErrorComponent:o,onChartElementClicked:i,id:a,authToken:l,currentTheme:u,version:d,customCards:f,showAssistant:h,defaultFilterValues:m,onFilterValuesChange:p,selectedSheetId:g,eventHandlers:b,type:x="dashboard",cardId:y,dashboardId:v,...w}){const{placeholders:j,tokenProps:S,id:N}=Xe();hs(P=>P.selectedDashboard);const E=J(P=>P.themeStyle),_=J(P=>P.isSessionExpired),{isLoading:k,isError:M}=Ooe({customStyle:t,currentTheme:u,onSave:n,onEvent:r,defaultFilterValues:m,onFilterValuesChange:p,selectedSheetId:g}),T=Rq();return l&&!T&&!k?c.jsx(hje,{}):k||!l?(r==null||r({type:"info",message:"Loading dashboard"}),s?c.jsx(s,{message:"loading"}):c.jsx("div",{className:"flex items-center gap-3",children:c.jsx(Xs,{className:"h-1 w-full dark:h-[2px]"})})):M?(r==null||r({type:"error",message:"Error fetching dashboard"}),o?(console.log("Error fetching dashboard"),c.jsx(o,{})):c.jsx("div",{children:"Error"})):_?(r==null||r({type:"error",message:"Session Expired"}),j!=null&&j.SessionExpired?c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsx("div",{children:j.SessionExpired})}):c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsxs("div",{className:"space-y-4 rounded-md border border-muted p-10",children:[c.jsx(Xi,{children:"Session Expired"}),c.jsx("p",{className:"text-muted-foreground",children:"Please refresh your page to continue"})]})})):c.jsx("div",{className:X("isolate flex grow flex-col",{"h-full":x==="visual"},E==null?void 0:E.dashboardPanel,e),style:{},"data-role":"semaphor-container",...w})}var Aq={exports:{}},ty={},VE={exports:{}};(function(e,t){(function(n,r){r(t)})(kl,function(n){function r(U){return function(Z,Q,K,te,le,de,ce){return U(Z,Q,ce)}}function s(U){return function(Z,Q,K,te){if(!Z||!Q||typeof Z!="object"||typeof Q!="object")return U(Z,Q,K,te);var le=te.get(Z),de=te.get(Q);if(le&&de)return le===Q&&de===Z;te.set(Z,Q),te.set(Q,Z);var ce=U(Z,Q,K,te);return te.delete(Z),te.delete(Q),ce}}function o(U,G){var Z={};for(var Q in U)Z[Q]=U[Q];for(var Q in G)Z[Q]=G[Q];return Z}function i(U){return U.constructor===Object||U.constructor==null}function a(U){return typeof U.then=="function"}function l(U,G){return U===G||U!==U&&G!==G}var u="[object Arguments]",d="[object Boolean]",f="[object Date]",h="[object RegExp]",m="[object Map]",p="[object Number]",g="[object Object]",b="[object Set]",x="[object String]",y=Object.prototype.toString;function v(U){var G=U.areArraysEqual,Z=U.areDatesEqual,Q=U.areMapsEqual,K=U.areObjectsEqual,te=U.areRegExpsEqual,le=U.areSetsEqual,de=U.createIsNestedEqual,ce=de(Ce);function Ce(ge,he,me){if(ge===he)return!0;if(!ge||!he||typeof ge!="object"||typeof he!="object")return ge!==ge&&he!==he;if(i(ge)&&i(he))return K(ge,he,ce,me);var oe=Array.isArray(ge),Ne=Array.isArray(he);if(oe||Ne)return oe===Ne&&G(ge,he,ce,me);var fe=y.call(ge);return fe!==y.call(he)?!1:fe===f?Z(ge,he,ce,me):fe===h?te(ge,he,ce,me):fe===m?Q(ge,he,ce,me):fe===b?le(ge,he,ce,me):fe===g||fe===u?a(ge)||a(he)?!1:K(ge,he,ce,me):fe===d||fe===p||fe===x?l(ge.valueOf(),he.valueOf()):!1}return Ce}function w(U,G,Z,Q){var K=U.length;if(G.length!==K)return!1;for(;K-- >0;)if(!Z(U[K],G[K],K,K,U,G,Q))return!1;return!0}var j=s(w);function S(U,G){return l(U.valueOf(),G.valueOf())}function N(U,G,Z,Q){var K=U.size===G.size;if(!K)return!1;if(!U.size)return!0;var te={},le=0;return U.forEach(function(de,ce){if(K){var Ce=!1,ge=0;G.forEach(function(he,me){!Ce&&!te[ge]&&(Ce=Z(ce,me,le,ge,U,G,Q)&&Z(de,he,ce,me,U,G,Q))&&(te[ge]=!0),ge++}),le++,K=Ce}}),K}var E=s(N),_="_owner",k=Object.prototype.hasOwnProperty;function M(U,G,Z,Q){var K=Object.keys(U),te=K.length;if(Object.keys(G).length!==te)return!1;for(var le;te-- >0;){if(le=K[te],le===_){var de=!!U.$$typeof,ce=!!G.$$typeof;if((de||ce)&&de!==ce)return!1}if(!k.call(G,le)||!Z(U[le],G[le],le,le,U,G,Q))return!1}return!0}var T=s(M);function P(U,G){return U.source===G.source&&U.flags===G.flags}function O(U,G,Z,Q){var K=U.size===G.size;if(!K)return!1;if(!U.size)return!0;var te={};return U.forEach(function(le,de){if(K){var ce=!1,Ce=0;G.forEach(function(ge,he){!ce&&!te[Ce]&&(ce=Z(le,ge,de,he,U,G,Q))&&(te[Ce]=!0),Ce++}),K=ce}}),K}var I=s(O),$=Object.freeze({areArraysEqual:w,areDatesEqual:S,areMapsEqual:N,areObjectsEqual:M,areRegExpsEqual:P,areSetsEqual:O,createIsNestedEqual:r}),V=Object.freeze({areArraysEqual:j,areDatesEqual:S,areMapsEqual:E,areObjectsEqual:T,areRegExpsEqual:P,areSetsEqual:I,createIsNestedEqual:r}),W=v($);function L(U,G){return W(U,G,void 0)}var R=v(o($,{createIsNestedEqual:function(){return l}}));function z(U,G){return R(U,G,void 0)}var F=v(V);function A(U,G){return F(U,G,new WeakMap)}var H=v(o(V,{createIsNestedEqual:function(){return l}}));function B(U,G){return H(U,G,new WeakMap)}function Y(U){return v(o($,U($)))}function q(U){var G=v(o(V,U(V)));return function(Z,Q,K){return K===void 0&&(K=new WeakMap),G(Z,Q,K)}}n.circularDeepEqual=A,n.circularShallowEqual=B,n.createCustomCircularEqual=q,n.createCustomEqual=Y,n.deepEqual=L,n.sameValueZeroEqual=l,n.shallowEqual=z,Object.defineProperty(n,"__esModule",{value:!0})})})(VE,VE.exports);var eI=VE.exports;const qC=dz(wne);var qt={},bje=function(t,n,r){return t===n?!0:t.className===n.className&&r(t.style,n.style)&&t.width===n.width&&t.autoSize===n.autoSize&&t.cols===n.cols&&t.draggableCancel===n.draggableCancel&&t.draggableHandle===n.draggableHandle&&r(t.verticalCompact,n.verticalCompact)&&r(t.compactType,n.compactType)&&r(t.layout,n.layout)&&r(t.margin,n.margin)&&r(t.containerPadding,n.containerPadding)&&t.rowHeight===n.rowHeight&&t.maxRows===n.maxRows&&t.isBounded===n.isBounded&&t.isDraggable===n.isDraggable&&t.isResizable===n.isResizable&&t.allowOverlap===n.allowOverlap&&t.preventCollision===n.preventCollision&&t.useCSSTransforms===n.useCSSTransforms&&t.transformScale===n.transformScale&&t.isDroppable===n.isDroppable&&r(t.resizeHandles,n.resizeHandles)&&r(t.resizeHandle,n.resizeHandle)&&t.onLayoutChange===n.onLayoutChange&&t.onDragStart===n.onDragStart&&t.onDrag===n.onDrag&&t.onDragStop===n.onDragStop&&t.onResizeStart===n.onResizeStart&&t.onResize===n.onResize&&t.onResizeStop===n.onResizeStop&&t.onDrop===n.onDrop&&r(t.droppingItem,n.droppingItem)&&r(t.innerRef,n.innerRef)};Object.defineProperty(qt,"__esModule",{value:!0});qt.bottom=tI;qt.childrenEqual=wje;qt.cloneLayout=Pq;qt.cloneLayoutItem=Fd;qt.collides=YC;qt.compact=Fq;qt.compactItem=$q;qt.compactType=Aje;qt.correctBounds=Lq;qt.fastPositionEqual=Cje;qt.fastRGLPropsEqual=void 0;qt.getAllCollisions=zq;qt.getFirstCollision=hd;qt.getLayoutItem=nI;qt.getStatics=rI;qt.modifyLayout=Oq;qt.moveElement=bg;qt.moveElementAwayFromCollision=UE;qt.noop=void 0;qt.perc=jje;qt.resizeItemInDirection=Mje;qt.setTopLeft=Ije;qt.setTransform=Dje;qt.sortLayoutItems=cI;qt.sortLayoutItemsByColRow=Wq;qt.sortLayoutItemsByRowCol=Uq;qt.synchronizeLayoutWithChildren=Rje;qt.validateLayout=qq;qt.withLayoutItem=vje;var U5=eI,gg=xje(C);function xje(e){return e&&e.__esModule?e:{default:e}}const yje=process.env.NODE_ENV==="production";function tI(e){let t=0,n;for(let r=0,s=e.length;r<s;r++)n=e[r].y+e[r].h,n>t&&(t=n);return t}function Pq(e){const t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=Fd(e[n]);return t}function Oq(e,t){const n=Array(e.length);for(let r=0,s=e.length;r<s;r++)t.i===e[r].i?n[r]=t:n[r]=e[r];return n}function vje(e,t,n){let r=nI(e,t);return r?(r=n(Fd(r)),e=Oq(e,r),[e,r]):[e,null]}function Fd(e){return{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,minW:e.minW,maxW:e.maxW,minH:e.minH,maxH:e.maxH,moved:!!e.moved,static:!!e.static,isDraggable:e.isDraggable,isResizable:e.isResizable,resizeHandles:e.resizeHandles,isBounded:e.isBounded}}function wje(e,t){return(0,U5.deepEqual)(gg.default.Children.map(e,n=>n==null?void 0:n.key),gg.default.Children.map(t,n=>n==null?void 0:n.key))&&(0,U5.deepEqual)(gg.default.Children.map(e,n=>n==null?void 0:n.props["data-grid"]),gg.default.Children.map(t,n=>n==null?void 0:n.props["data-grid"]))}qt.fastRGLPropsEqual=bje;function Cje(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function YC(e,t){return!(e.i===t.i||e.x+e.w<=t.x||e.x>=t.x+t.w||e.y+e.h<=t.y||e.y>=t.y+t.h)}function Fq(e,t,n,r){const s=rI(e),o=cI(e,t),i=Array(e.length);for(let a=0,l=o.length;a<l;a++){let u=Fd(o[a]);u.static||(u=$q(s,u,t,n,o,r),s.push(u)),i[e.indexOf(o[a])]=u,u.moved=!1}return i}const Sje={x:"w",y:"h"};function HE(e,t,n,r){const s=Sje[r];t[r]+=1;const o=e.map(i=>i.i).indexOf(t.i);for(let i=o+1;i<e.length;i++){const a=e[i];if(!a.static){if(a.y>t.y+t.h)break;YC(t,a)&&HE(e,a,n+t[s],r)}}t[r]=n}function $q(e,t,n,r,s,o){const i=n==="vertical",a=n==="horizontal";if(i)for(t.y=Math.min(tI(e),t.y);t.y>0&&!hd(e,t);)t.y--;else if(a)for(;t.x>0&&!hd(e,t);)t.x--;let l;for(;(l=hd(e,t))&&!(n===null&&o);)if(a?HE(s,t,l.x+l.w,"x"):HE(s,t,l.y+l.h,"y"),a&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!hd(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function Lq(e,t){const n=rI(e);for(let r=0,s=e.length;r<s;r++){const o=e[r];if(o.x+o.w>t.cols&&(o.x=t.cols-o.w),o.x<0&&(o.x=0,o.w=t.cols),!o.static)n.push(o);else for(;hd(n,o);)o.y++}return e}function nI(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function hd(e,t){for(let n=0,r=e.length;n<r;n++)if(YC(e[n],t))return e[n]}function zq(e,t){return e.filter(n=>YC(n,t))}function rI(e){return e.filter(t=>t.static)}function bg(e,t,n,r,s,o,i,a,l){if(t.static&&t.isDraggable!==!0||t.y===r&&t.x===n)return e;`${t.i}${String(n)}${String(r)}${t.x}${t.y}`;const u=t.x,d=t.y;typeof n=="number"&&(t.x=n),typeof r=="number"&&(t.y=r),t.moved=!0;let f=cI(e,i);(i==="vertical"&&typeof r=="number"?d>=r:i==="horizontal"&&typeof n=="number"?u>=n:!1)&&(f=f.reverse());const m=zq(f,t),p=m.length>0;if(p&&l)return Pq(e);if(p&&o)return`${t.i}`,t.x=u,t.y=d,t.moved=!1,e;for(let g=0,b=m.length;g<b;g++){const x=m[g];`${t.i}${t.x}${t.y}${x.i}${x.x}${x.y}`,!x.moved&&(x.static?e=UE(e,x,t,s,i):e=UE(e,t,x,s,i))}return e}function UE(e,t,n,r,s,o){const i=s==="horizontal",a=s==="vertical",l=t.static;if(r){r=!1;const f={x:i?Math.max(t.x-n.w,0):n.x,y:a?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:"-1"},h=hd(e,f),m=h&&h.y+h.h>t.y,p=h&&t.x+t.w>h.x;if(h){if(m&&a)return bg(e,n,void 0,t.y+1,r,l,s);if(m&&s==null)return t.y=n.y,n.y=n.y+n.h,e;if(p&&i)return bg(e,t,n.x,void 0,r,l,s)}else return`${n.i}${f.x}${f.y}`,bg(e,n,i?f.x:void 0,a?f.y:void 0,r,l,s)}const u=i?n.x+1:void 0,d=a?n.y+1:void 0;return u==null&&d==null?e:bg(e,n,i?n.x+1:void 0,a?n.y+1:void 0,r,l,s)}function jje(e){return e*100+"%"}const Bq=(e,t,n,r)=>e+n>r?t:n,Vq=(e,t,n)=>e<0?t:n,Hq=e=>Math.max(0,e),sI=e=>Math.max(0,e),oI=(e,t,n)=>{let{left:r,height:s,width:o}=t;const i=e.top-(s-e.height);return{left:r,width:o,height:Vq(i,e.height,s),top:sI(i)}},iI=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{top:r,height:o,width:Bq(e.left,e.width,i,n),left:Hq(s)}},aI=(e,t,n)=>{let{top:r,height:s,width:o}=t;const i=e.left-(o-e.width);return{height:s,width:i<0?e.width:Bq(e.left,e.width,o,n),top:sI(r),left:Hq(i)}},lI=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{width:i,left:s,height:Vq(r,e.height,o),top:sI(r)}},Nje=function(){return oI(arguments.length<=0?void 0:arguments[0],iI(...arguments))},kje=function(){return oI(arguments.length<=0?void 0:arguments[0],aI(...arguments))},Eje=function(){return lI(arguments.length<=0?void 0:arguments[0],iI(...arguments))},_je=function(){return lI(arguments.length<=0?void 0:arguments[0],aI(...arguments))},Tje={n:oI,ne:Nje,e:iI,se:Eje,s:lI,sw:_je,w:aI,nw:kje};function Mje(e,t,n,r){const s=Tje[e];return s?s(t,{...t,...n},r):n}function Dje(e){let{top:t,left:n,width:r,height:s}=e;const o=`translate(${n}px,${t}px)`;return{transform:o,WebkitTransform:o,MozTransform:o,msTransform:o,OTransform:o,width:`${r}px`,height:`${s}px`,position:"absolute"}}function Ije(e){let{top:t,left:n,width:r,height:s}=e;return{top:`${t}px`,left:`${n}px`,width:`${r}px`,height:`${s}px`,position:"absolute"}}function cI(e,t){return t==="horizontal"?Wq(e):t==="vertical"?Uq(e):e}function Uq(e){return e.slice(0).sort(function(t,n){return t.y>n.y||t.y===n.y&&t.x>n.x?1:t.y===n.y&&t.x===n.x?0:-1})}function Wq(e){return e.slice(0).sort(function(t,n){return t.x>n.x||t.x===n.x&&t.y>n.y?1:-1})}function Rje(e,t,n,r,s){e=e||[];const o=[];gg.default.Children.forEach(t,a=>{if((a==null?void 0:a.key)==null)return;const l=nI(e,String(a.key)),u=a.props["data-grid"];l&&u==null?o.push(Fd(l)):u?(yje||qq([u],"ReactGridLayout.children"),o.push(Fd({...u,i:a.key}))):o.push(Fd({w:1,h:1,x:0,y:tI(o),i:String(a.key)}))});const i=Lq(o,{cols:n});return s?i:Fq(i,r,n)}function qq(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Layout";const n=["x","y","w","h"];if(!Array.isArray(e))throw new Error(t+" must be an array!");for(let r=0,s=e.length;r<s;r++){const o=e[r];for(let i=0;i<n.length;i++){const a=n[i],l=o[a];if(typeof l!="number"||Number.isNaN(l))throw new Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${l} (${typeof l})`)}if(typeof o.i<"u"&&typeof o.i!="string")throw new Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${o.i} (${typeof o.i})`)}}function Aje(e){const{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}const Pje=()=>{};qt.noop=Pje;var Qa={};Object.defineProperty(Qa,"__esModule",{value:!0});Qa.calcGridColWidth=GC;Qa.calcGridItemPosition=Oje;Qa.calcGridItemWHPx=WE;Qa.calcWH=$je;Qa.calcXY=Fje;Qa.clamp=md;function GC(e){const{margin:t,containerPadding:n,containerWidth:r,cols:s}=e;return(r-t[0]*(s-1)-n[0]*2)/s}function WE(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function Oje(e,t,n,r,s,o){const{margin:i,containerPadding:a,rowHeight:l}=e,u=GC(e),d={};return o&&o.resizing?(d.width=Math.round(o.resizing.width),d.height=Math.round(o.resizing.height)):(d.width=WE(r,u,i[0]),d.height=WE(s,l,i[1])),o&&o.dragging?(d.top=Math.round(o.dragging.top),d.left=Math.round(o.dragging.left)):o&&o.resizing&&typeof o.resizing.top=="number"&&typeof o.resizing.left=="number"?(d.top=Math.round(o.resizing.top),d.left=Math.round(o.resizing.left)):(d.top=Math.round((l+i[1])*n+a[1]),d.left=Math.round((u+i[0])*t+a[0])),d}function Fje(e,t,n,r,s){const{margin:o,containerPadding:i,cols:a,rowHeight:l,maxRows:u}=e,d=GC(e);let f=Math.round((n-i[0])/(d+o[0])),h=Math.round((t-i[1])/(l+o[1]));return f=md(f,0,a-r),h=md(h,0,u-s),{x:f,y:h}}function $je(e,t,n,r,s,o){const{margin:i,maxRows:a,cols:l,rowHeight:u}=e,d=GC(e);let f=Math.round((t+i[0])/(d+i[0])),h=Math.round((n+i[1])/(u+i[1])),m=md(f,0,l-r),p=md(h,0,a-s);return["sw","w","nw"].indexOf(o)!==-1&&(m=md(f,0,l)),["nw","n","ne"].indexOf(o)!==-1&&(p=md(h,0,a)),{w:m,h:p}}function md(e,t,n){return Math.max(Math.min(e,n),t)}var KC={},qE={exports:{}},_0={exports:{}},wn={};/** @license React v16.13.1
|
|
753
|
+
${T}`:T},color:E=>{if(f)return f;const _=E==null?void 0:E.raw,k=M5({raw:_,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a});return wo(k)},font:{size:((x=(b=o==null?void 0:o.chart)==null?void 0:b.font)==null?void 0:x.size)||((y=u==null?void 0:u.font)==null?void 0:y.size)||12,weight:((w=(v=o==null?void 0:o.chart)==null?void 0:v.font)==null?void 0:w.weight)||((j=u==null?void 0:u.font)==null?void 0:j.weight)||"bold",family:((N=(S=o==null?void 0:o.chart)==null?void 0:S.font)==null?void 0:N.family)||"Inter"}},backgroundColor:E=>{const _=E==null?void 0:E.raw;return M5({raw:_,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a})}}}function wwe({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 Ewe(o==null?void 0:o.raw,e)},label:s=>{const o=s==null?void 0:s.raw,i=bU(o,e),a=Number((o==null?void 0:o.v)??0),l=xU(a,n),u=t||"Value";return i?`${i} — ${u}: ${l}`:`${u}: ${l}`}}}}}}function Cwe(e){return e.reduce((t,n)=>jr(t,n||{}),{})}function Swe(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 jwe(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))??Df();return t.map((l,u)=>{const d=new Map;return u>0||Array.from(new Set(e.map(h=>h[l]).filter(h=>!!h))).forEach((h,m)=>{var p,g;if((g=(p=n==null?void 0:n.colorConfig)==null?void 0:p.segments)!=null&&g[h]){d.set(h,n.colorConfig.segments[h]);return}d.set(h,s[m%s.length])}),d})}function Nwe(e){var i,a,l;const t=((i=e==null?void 0:e.dataLabelsConfig)==null?void 0:i.format)||((a=e==null?void 0:e.numberAxisFormat)==null?void 0:a.format)||"number",n=t&&t!=="none"?t:"number",r=((l=e==null?void 0:e.dataLabelsConfig)==null?void 0:l.formatOptions)||(e==null?void 0:e.numberAxisFormat)||(e==null?void 0:e.formatNumber)||{},s=["decimalPlaces","currency","locale","useSuffix","prefix","suffix","negativeInParentheses","multiplyBy"],o=Object.fromEntries(Object.entries(r).filter(([u])=>s.includes(u)));return{format:n,formatOptions:o}}function bU(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 kwe(e._data,t);if(e.path){const r=e.path.split("."),s=r[r.length-1];if(s)return s}return""}function kwe(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 Ewe(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 xU(e,t){return Er(e,t.format,t.formatOptions)}function M5({raw:e,dimensionKeys:t,colorLookups:n,themeStyle:r,preferences:s,colorMode:o}){var p,g,b,x,y,v,w;if(!e)return"#999999";const i=((b=(g=(p=r==null?void 0:r.chart)==null?void 0:p.dataset)==null?void 0:g.backgroundColor)==null?void 0:b.filter(Boolean))??Df(),a=_we(e,t),l=a[0]||((x=e._data)==null?void 0:x[t[0]])||e.g||"",u=((v=(y=s==null?void 0:s.colorConfig)==null?void 0:y.segments)==null?void 0:v[l])||((w=n[0])==null?void 0:w.get(l))||i[0]||"#999999",d=Math.max(t.length-1,0),f=typeof e.l=="number"?e.l:a.length-1,h=CD(f,0,d);if(h===0||o==="category")return u;const m=Twe(e);return Mwe(u,m,h)}function _we(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 Twe(e){if(!e)return 1;const t=Number(e.v??0),n=Number(e.gs??e.s??0);return n>0&&Number.isFinite(t)?CD(t/n,0,1):1}function Mwe(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=D5(e,"#ffffff",o);return a=D5(a,"#000000",i),a}function D5(e,t,n){const r=CD(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=I5(e),o=I5(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),l=Math.round(s.b+(o.b-s.b)*r);return Dwe(i,a,l)}function I5(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 Dwe(e,t,n){const r=s=>s.toString(16).padStart(2,"0");return`#${r(nN(e))}${r(nN(t))}${r(nN(n))}`}function nN(e){return Math.min(255,Math.max(0,Math.round(e)))}function CD(e,t,n){return Math.max(t,Math.min(n,e))}function yU(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 Iwe(e,t,n){var i;if(e==null)return"";const r=Number(e);if(isNaN(r))return String(e);const s=t.format||"auto",o=t.formatOptions||{};switch(s){case"currency":return Er(r,"currency",{currency:o.currency||"USD",decimalPlaces:o.decimalPlaces??2,useSuffix:o.useSuffix,locale:o.locale});case"number":return Er(r,"number",{decimalPlaces:o.decimalPlaces??0,useSuffix:o.useSuffix,locale:o.locale});case"percent":return Er(r,"percent",{decimalPlaces:o.decimalPlaces??1,locale:o.locale});case"none":return String(e);case"auto":default:return(i=n==null?void 0:n.formatOptions)!=null&&i.type&&n.formatOptions.type!=="auto"?Er(r,n.formatOptions.type,n.formatOptions):String(e)}}function TC(e,t,n){var h,m;if(!(e.enabled??!1))return{display:!1};const s=e.position||"auto";let o,i;if(s==="custom")o=e.anchor||"center",i=e.align||"center";else{const g=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"}},b=g[s]||g.auto;o=b.anchor,i=b.align}const a=e.color,l=p=>{var b,x,y;if(a&&a!=="auto")return a;if(s!=="center"||n==="line"||n==="area")return wo(Hi());const g=((x=(b=p.dataset)==null?void 0:b.backgroundColor)==null?void 0:x[p.dataIndex])||((y=p.dataset)==null?void 0:y.backgroundColor)||Hi();return wo(g)},u=((h=e.font)==null?void 0:h.size)||11,d=((m=e.font)==null?void 0:m.weight)||"normal",f=e.rotation||0;return{display:e.display==="auto"?"auto":!0,formatter:p=>Iwe(p,e,t),anchor:o,align:i,color:l,font:{size:u,weight:d},rotation:f,clamp:e.clamp??!0,clip:e.clip??!1,offset:e.offset??4}}function MC(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 SD(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 DC(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 Rwe(e,t){return Array.from({length:e},(n,r)=>({idx:r,fill:t&&r>0?"-1":"origin"}))}function Awe(e,t,n){const r=Rwe(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 Pwe(e,t,n,r){const s=n==null?void 0:n.lineStyleConfig,o=n==null?void 0:n.yAxisConfig;return e.map((i,a)=>{const l=t.find(m=>m.idx===a),u={...i};u.type="line",u.fill=(l==null?void 0:l.fill)??"origin",u.borderWidth=u.borderWidth??2,u.tension=u.tension??.1,u.pointRadius=(l==null?void 0:l.pointRadius)??(s==null?void 0:s.pointRadius)??3,u.pointStyle=(l==null?void 0:l.pointStyle)??(s==null?void 0:s.pointStyle)??"circle";const d=(l==null?void 0:l.pointRadius)??(s==null?void 0:s.pointRadius)??3;u.pointHoverRadius=(l==null?void 0:l.pointHoverRadius)??d+2,u.borderDash=SD((l==null?void 0:l.lineStyle)??(s==null?void 0:s.lineStyle));const f=u.borderColor||u.backgroundColor;f&&typeof f=="string"&&(u.backgroundColor=yU(f,.5));const h=DC(n==null?void 0:n.dataLabelsConfig,l==null?void 0:l.dataLabels);return h&&(u.datalabels=TC(h,o,"area")),u})}function Owe(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 Fwe({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var j,S;const{keys:i}=zn(t),a=vb(i),l=a.length,u=o==="stackedArea",d=Awe(s==null?void 0:s.datasetOptions,l,u),f=i==null?void 0:i[0],h=nc(t,f),m=Gm(a,t,s,1,"none",f,!1,Ym(t)),p=Pwe(m,d,s),g=ta(p,r),{options:b,plugins:x}=ou({cardType:o||"area",cfg:n,preferences:s,customCfg:r,card:e}),y=Owe(b==null?void 0:b.scales,u),v={...b,scales:y},w=(((S=(j=e.interactionConfig)==null?void 0:j.interactions)==null?void 0:S.length)??0)>0;return MC(v,w),{type:"line",data:{labels:h,datasets:g},options:v,plugins:x}}const vU=["poor","satisfactory","good"],rN={poor:"Poor",satisfactory:"Average",good:"Good"},$we=["#F5F6F8","#E3E6EC","#CED4DD"],Lwe=["#1F2933","#27323D","#303B47"];function zwe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s}){var le,de,ce,Ce,ge,he,me;if(!e||e.length===0)return{type:"bar",data:{labels:[],datasets:[]}};const{dimensionKeys:o,metricKeys:i,keys:a}=zn(e),l=o[0]??a[0];if(!l)return{type:"bar",data:{labels:[],datasets:[]}};const u=i[0]??a.find(oe=>oe!==l);if(!u)return{type:"bar",data:{labels:[],datasets:[]}};const d=r==null?void 0:r.bulletConfig,f=(d==null?void 0:d.targetMetricKey)??i.find(oe=>oe!==u),h=(d==null?void 0:d.comparativeMetricKey)??(d!=null&&d.disableAutoComparative?void 0:i.find(oe=>oe!==u&&oe!==f)),m=J.getState(),p=s??m.themeStyle,g=m.theme==="dark",b=Bwe({data:e,dimensionKey:l,actualKey:u,targetKey:f,comparativeKey:h,bulletConfig:d}),x=b.map(oe=>oe.label),y=(d==null?void 0:d.showRanges)??t1e(d),v=Uwe(b,y),w=(le=r==null?void 0:r.chartOptions)==null?void 0:le.indexAxis,S=(w?w==="y"?"horizontal":"vertical":void 0)??(d==null?void 0:d.orientation)??"horizontal",N=S==="vertical"?"x":"y",E=r?{...r,chartOptions:{...r.chartOptions||{},indexAxis:N}}:{chartOptions:{indexAxis:N}},_=Qwe(r),k=e1e(d),M=Jwe(g),T=Df().filter(Boolean),P=(((ce=(de=p==null?void 0:p.chart)==null?void 0:de.dataset)==null?void 0:ce.backgroundColor)||[]).filter(Boolean),O=(((ge=(Ce=p==null?void 0:p.chart)==null?void 0:Ce.dataset)==null?void 0:ge.borderColor)||[]).filter(Boolean),I=P.length>0?P:T.length>0?T:["#3b82f6"],$=O.length>0?O:I.length>0?I:["#111827"],V=oN({metricKey:u,metricIndex:0,preferences:r,backgroundPalette:I,borderPalette:$}),L=oN({metricKey:f||`${u}__target`,metricIndex:1,preferences:r,backgroundPalette:I,borderPalette:$}).borderColor||V.borderColor||"#111827",R=oN({metricKey:h,metricIndex:2,preferences:r,backgroundPalette:I,borderPalette:$}),z=y?Wwe(b,M,S,g,k):[],F=qwe(b,V,S,u),A=Ywe(b,R,S,h),H=[...z,F];A&&H.push(A);let B=Gwe({orientation:S,chartMax:v,formatConfig:_,series:b,preferences:E,rangeLabelMap:k,showRanges:y});const Y=(me=(he=r==null?void 0:r.chartOptions)==null?void 0:he.plugins)==null?void 0:me.legend;B=aD(B,Y);const{plugins:q=[],options:U}=Cu((r==null?void 0:r.customVisualCode)||""),G=o1e([B,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,U]),Z=b.some(oe=>oe.target!=null)&&v>0?Xwe({series:b,orientation:S,color:L}):null,Q={type:"bar",data:{labels:x,datasets:H},options:G,plugins:Z?[...q,Z]:q},K=Vx("bullet",r),te=(r==null?void 0:r.dataLabelsConfig)??K;return Q.options=Zm(Q.options||{},te,E,"bar"),Q.options=Km.applyAxisConfig(Q.options||{},"bar",E),Q.options=Q.options||{},Q.options.indexAxis=N,Q}function Bwe({data:e,dimensionKey:t,actualKey:n,targetKey:r,comparativeKey:s,bulletConfig:o}){const i=e.map(l=>{const u=Hwe(l[t]),d=Iv(l[n]),f=r&&l[r]!=null?Iv(l[r]):(o==null?void 0:o.targetValue)??null,h=s&&l[s]!=null?Iv(l[s]):null;return{label:u,actual:d,target:f,comparative:h,row:l}}),a=i.reduce((l,u)=>{var d;return Math.max(l,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(l=>{const u=Vwe({row:l.row,actual:l.actual,target:l.target,globalMax:a||l.actual||1,bulletConfig:o});return{label:l.label,actual:l.actual,target:l.target??void 0,comparative:l.comparative??void 0,ranges:u,actualKey:n,targetKey:r||void 0}})}function Vwe({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),l={poor:sN("poor",e,o,i,a*.5,s,a),satisfactory:sN("satisfactory",e,o,i,a*.8,s,a),good:sN("good",e,o,i,a,s,a)};let u=0;return vU.forEach(d=>{const f=l[d];if(!Number.isFinite(f)||f<0){l[d]=u;return}f<u?l[d]=u:u=f}),l}function sN(e,t,n,r,s,o,i){const a=n==null?void 0:n[e];if(a&&t[a]!=null)return Iv(t[a]);if((r==null?void 0:r[e])!=null){const l=r[e];return o!=null&&o.rangesArePercentages?l*i:l}return s}function Iv(e){const t=Number(e);return Number.isFinite(t)?t:0}function Hwe(e){return e==null||e===""?"(Blank)":String(e)}function Uwe(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 Wwe(e,t,n,r,s){const o=[];return vU.forEach((i,a)=>{const l=[],u=e.map(f=>{const h=f.ranges[i];return l.push({start:0,end:h}),h}),d={type:"bar",label:s[i],data:u,order:10,backgroundColor:r1e(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:l};o.push(d)}),o}function qwe(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 Ywe(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 Gwe({orientation:e,chartMax:t,formatConfig:n,series:r,preferences:s,rangeLabelMap:o,showRanges:i}){var f,h,m,p,g,b,x,y,v;const a={type:"linear",stacked:!1,beginAtZero:!0,suggestedMax:t,ticks:{callback:w=>Er(Number(w),n.format,n.options)},grid:{drawOnChartArea:!0}},l={type:"category",stacked:!0,grid:{display:!1}};return{responsive:!0,maintainAspectRatio:!1,scales:{x:e==="vertical"?l:a,y:e==="vertical"?a:l},plugins:{legend:{display:((m=(h=(f=s==null?void 0:s.chartOptions)==null?void 0:f.plugins)==null?void 0:h.legend)==null?void 0:m.display)??!0,position:((b=(g=(p=s==null?void 0:s.chartOptions)==null?void 0:p.plugins)==null?void 0:g.legend)==null?void 0:b.position)??"top",align:((v=(y=(x=s==null?void 0:s.chartOptions)==null?void 0:x.plugins)==null?void 0:y.legend)==null?void 0:v.align)??"center"},tooltip:{filter:w=>{const j=w.dataset.customRole;return j?j!=="range":!0},callbacks:Kwe(r,n,o,i)}},indexAxis:e==="vertical"?"x":"y"}}function Kwe(e,t,n,r){return{title:s=>{var o;return s.length?((o=e[s[0].dataIndex])==null?void 0:o.label)??"":""},label:s=>{const o=e[s.dataIndex];return o?`${o.actualKey||"Actual"}: ${Er(o.actual,t.format,t.options)}`:s.formattedValue},afterBody:s=>{if(!s.length)return[];const o=e[s[0].dataIndex];if(!o)return[];const i=[];if(o.target!=null){const u=Er(o.target,t.format,t.options),d=o.actual-o.target,f=Er(d,t.format,t.options),h=o.targetKey||"Target";i.push(`${h}: ${u} (${f})`)}const a=Zwe(o,n);r&&a&&i.push(`Range: ${a}`);const l=o.comparative;return l!=null&&i.push(`Comparative: ${Er(l,t.format,t.options)}`),i}}}function Zwe(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 Xwe({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,l=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 b,x,y,v,w;if(d.target==null)return;const h=(b=r.data.labels)==null?void 0:b[f],m=((y=(x=r.getDatasetMeta(u>=0?u:l>=0?l:0))==null?void 0:x.data)==null?void 0:y[f])||((w=(v=r.getDatasetMeta(0))==null?void 0:v.data)==null?void 0:w[f]),p=m?t==="horizontal"?m.height??m.width??20:m.width??m.height??20:20,g=Math.max(Math.min(p/2,12),6);if(t==="horizontal"){const j=o.getPixelForValue(d.target),S=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(j,S-g),s.lineTo(j,S+g),s.stroke(),s.beginPath(),s.moveTo(j-4,S-g),s.lineTo(j+4,S-g),s.moveTo(j-4,S+g),s.lineTo(j+4,S+g),s.stroke()}else{const j=o.getPixelForValue(d.target),S=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(S-g,j),s.lineTo(S+g,j),s.stroke(),s.beginPath(),s.moveTo(S-g,j-4),s.lineTo(S-g,j+4),s.moveTo(S+g,j-4),s.lineTo(S+g,j+4),s.stroke()}}),s.restore()}}}function Qwe(e){var r,s,o;const t=((r=e==null?void 0:e.dataLabelsConfig)==null?void 0:r.format)??((s=e==null?void 0:e.numberAxisFormat)==null?void 0:s.format)??"number",n=((o=e==null?void 0:e.dataLabelsConfig)==null?void 0:o.formatOptions)??(e==null?void 0:e.numberAxisFormat)??(e==null?void 0:e.formatNumber)??{};return{format:t==="none"?"number":t,options:n}}function Jwe(e){return[...e?Lwe:$we]}function e1e(e){var n,r,s;const t=(e==null?void 0:e.rangeLabels)||{};return{poor:((n=t.poor)==null?void 0:n.trim())||rN.poor,satisfactory:((r=t.satisfactory)==null?void 0:r.trim())||rN.satisfactory,good:((s=t.good)==null?void 0:s.trim())||rN.good}}function t1e(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 n1e(e,t,n){const r=wU(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=R5(e),o=R5(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),l=Math.round(s.b+(o.b-s.b)*r);return s1e(i,a,l)}function r1e(e,t,n){return n1e(e,n?"#000000":"#ffffff",t)}function oN({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 R5(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 s1e(e,t,n){return`#${iN(e)}${iN(t)}${iN(n)}`}function iN(e){return wU(Math.round(e),0,255).toString(16).padStart(2,"0")}function wU(e,t,n){return Math.max(t,Math.min(n,e))}function o1e(e){return e.reduce((t,n)=>jr(t,n||{}),{})}const RE={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"}},CU=["#dcfce7","#15803d"],k0={type:"matrix",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function i1e({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o}){var B,Y,q;if(!Array.isArray(e)||e.length===0)return k0;const{dimensionKeys:i,metricKeys:a,keys:l}=zn(e),u=i[0]??l[0];if(!u)return k0;const d=i[1],f=l.find(U=>U!==u&&!a.includes(U)&&U!==d)??d,h=!d&&(!f||typeof((B=e[0])==null?void 0:B[f])!="string")&&a.length>1,m=a[0]??l.find(U=>U!==u&&U!==f);if(!m&&!h)return k0;const p=r==null?void 0:r.heatmapConfig,g=(p==null?void 0:p.legendPosition)??"bottom",b=h?l1e({data:e,dimensionKey:u,metricKeys:a}):a1e({data:e,xKey:u,yKey:f||m,metricKey:m});if(b.length===0)return k0;const x=h?a.map(gm):aN(b.map(U=>U.x)),y=aN(h?e.map(U=>gm(U==null?void 0:U[u])):b.map(U=>U.y)),v=c1e(b),w=o??J.getState().themeStyle,j=p1e({min:v.min,max:v.max,heatmapConfig:p,themeStyle:w}),S=u1e({points:b,xLabels:x,yLabels:y,fill:(p==null?void 0:p.fillMissingCells)!==!1}),N=v1e(r),_=["auto","number","currency","percent","none"].includes(N.format)?N.format:"auto",k=Vx("heatmap",r),M=k?{...k,format:k.format??_,formatOptions:k.formatOptions??N.options}:void 0,T=(r==null?void 0:r.dataLabelsConfig)??M,P=d1e({points:S,xLabels:x,yLabels:y,colorScale:j,datasetLabel:h?"Value":m||"Value",dataLabelPrefs:T,formatConfig:N}),O=f1e({xLabels:x,yLabels:y,heatmapConfig:p,formatConfig:N,themeStyle:w,legendPreferences:(q=(Y=r==null?void 0:r.chartOptions)==null?void 0:Y.plugins)==null?void 0:q.legend,cardType:s,legendPosition:g}),{plugins:I=[],options:$}=Cu((r==null?void 0:r.customVisualCode)||""),V=w1e([O,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,$]),W=(p==null?void 0:p.showLegend)===!1?null:g1e({stops:j.stops,min:v.min,max:v.max,formatConfig:N,position:g}),L={type:"matrix",data:{datasets:[P]},options:V,plugins:W?[...I,W]:I};L.options=Zm(L.options||{},T,r,"matrix");const R=Qk(s??"heatmap","x"),z=Qk(s??"heatmap","y"),F=Jk(R,r==null?void 0:r.xAxisConfig),A=Jk(z,r==null?void 0:r.yAxisConfig),H=F||A||r?{...r||{},...F?{xAxisConfig:F}:{},...A?{yAxisConfig:A}:{}}:r;return L.options=Km.applyAxisConfig(L.options||{},"heatmap",H),L}function a1e({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 l=gm(i),u=gm(a),d=`${l}__${u}`,f=SU(o==null?void 0:o[r]);if(!s.has(d)){s.set(d,{x:l,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 l1e({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=gm(o);n.forEach(a=>{if(a===t)return;const l=SU(s==null?void 0:s[a]),u=gm(a);r.push({x:u,y:i,v:l,raw:{...s,_metricKey:a}})})}),r}function gm(e){return e==null||e===""?"Unknown":String(e)}function SU(e){const t=Number(e);return Number.isFinite(t)?t:null}function aN(e){const t=new Set,n=[];return e.forEach(r=>{t.has(r)||(t.add(r),n.push(r))}),n}function c1e(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 u1e({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 l=`${i}__${a}`,u=s.get(l);u?o.push(u):o.push({x:i,y:a,v:null})})}),o}function d1e({points:e,xLabels:t,yLabels:n,colorScale:r,datasetLabel:s,dataLabelPrefs:o,formatConfig:i}){const a=Zxe(e.length,o),l=Math.max(t.length||1,n.length||1);return{label:s,data:e,backgroundColor:d=>{const f=d==null?void 0:d.raw;return r.getColor((f==null?void 0:f.v)??null)},hoverBackgroundColor:d=>{const f=d==null?void 0:d.raw,h=r.getColor((f==null?void 0:f.v)??null);return y1e(h,.85)},borderWidth:1,borderColor:"rgba(255, 255, 255, 0.65)",width:({chart:d})=>{var f;return A5((f=d==null?void 0:d.chartArea)==null?void 0:f.width,t.length)},height:({chart:d})=>{var f;return A5((f=d==null?void 0:d.chartArea)==null?void 0:f.height,n.length)},datalabels:{display:a,anchor:"center",align:"center",formatter:d=>{let f=null;return typeof d=="number"?f=d:d&&typeof d=="object"&&"v"in d&&(f=Number(d.v)),f==null||Number.isNaN(f)?"":jD(f,i??{format:"number",options:{}})},color:d=>{const f=d==null?void 0:d.raw,h=r.getColor((f==null?void 0:f.v)??null)||"rgba(148,163,184,0.35)";return wo(x1e(h))},font:{size:Math.max(10,Math.min(14,120/l))}}}}function A5(e,t){return!e||t===0?0:Math.max(4,e/t-2)}function f1e({xLabels:e,yLabels:t,heatmapConfig:n,formatConfig:r,themeStyle:s,legendPreferences:o,cardType:i,legendPosition:a}){var m,p,g;const l=(n==null?void 0:n.showLegend)??!0,u=((g=(p=(m=s==null?void 0:s.chart)==null?void 0:m.options)==null?void 0:p.plugins)==null?void 0:g.tooltip)||{},d=lD(i??"heatmap"),f=xH(d,o);return{responsive:!0,maintainAspectRatio:!1,layout:{padding:h1e(l,a)},plugins:{legend:f,tooltip:{...u,filter:b=>{const x=b==null?void 0:b.raw;return(x==null?void 0:x.v)!=null&&x.v!==0},callbacks:m1e(r)}},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 h1e(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 m1e(e){return{title(t){var r;const n=(r=t==null?void 0:t[0])==null?void 0:r.raw;return n&&(n.y||n.x)||""},label(t){var i;const n=t==null?void 0:t.raw;if(!n||n.v==null)return"";const r=((i=t==null?void 0:t.dataset)==null?void 0:i.label)||n.x||"Value",s=n.x,o=jD(n.v,e);return s?`${s}: ${o}`:`${r}: ${o}`}}}function p1e({min:e,max:t,heatmapConfig:n,themeStyle:r}){var y,v;const s=((v=(y=r==null?void 0:r.chart)==null?void 0:y.dataset)==null?void 0:v.backgroundColor)||[],o=["#0ea5e9","#f97316"],i=(n==null?void 0:n.colorPalette)??"green",a=i!=="custom"?RE[i]??RE.blue:void 0,l=n==null?void 0:n.colorRange,u=l&&l[0]&&l[1]?l:a?[a.start,a.end]:i==="custom"?CU: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",m=Math.max(3,(n==null?void 0:n.steps)??5),p=(n==null?void 0:n.nullFillColor)??"rgba(148, 163, 184, 0.25)",g=Math.max(t-e,Number.EPSILON),b=h==="continuous"?[{offset:0,color:Uu(d)},{offset:1,color:Uu(f)}]:Array.from({length:m}).map((w,j)=>{const S=m===1?0:j/(m-1||1);return{offset:S,color:P5(Uu(d),Uu(f),S)}}),x=h==="continuous"?null:b.map(w=>w.color);return{getColor(w){if(w==null||w===0)return p;if(h==="continuous"){const N=Db((w-e)/g,0,1);return P5(Uu(d),Uu(f),N)}const j=Db((w-e)/g,0,1),S=Math.min(m-1,Math.max(0,Math.floor(j*m)));return(x==null?void 0:x[S])??Uu(d)},stops:b}}function g1e({stops:e,min:t,max:n,formatConfig:r,position:s}){if(!e||e.length===0)return null;const o=i=>jD(i,r);return{id:"heatmapLegend",afterDraw(i){var p,g,b,x;const{ctx:a,chartArea:l}=i;if(!a||!l)return;a.save();const u=((x=(b=(g=(p=i.options)==null?void 0:p.plugins)==null?void 0:g.legend)==null?void 0:b.labels)==null?void 0:x.font)||{},d=u.size??12,f=u.family??"sans-serif",h=wo(Hi()),m=24;if(a.font=`${d}px ${f}`,a.fillStyle=h,s==="bottom"||s==="top"){const v=l.left,w=l.right,j=s==="bottom"?l.bottom+m/2:l.top-10-m/2,S=a.createLinearGradient(v,0,w,0);e.forEach(E=>S.addColorStop(E.offset,E.color)),a.fillStyle=S,a.fillRect(v,j,w-v,10),a.fillStyle=h,a.textAlign="left",a.textBaseline=s==="bottom"?"top":"bottom";const N=s==="bottom"?j+10+4:j-4;a.fillText(o(t),v,N),a.textAlign="center",a.fillText(o(t+(n-t)/2),(v+w)/2,N),a.textAlign="right",a.fillText(o(n),w,N)}else{const v=l.top,w=l.bottom,j=s==="left"?l.left-10-m/2:l.right+m/2,S=a.createLinearGradient(0,v,0,w);e.forEach(E=>S.addColorStop(E.offset,E.color)),a.fillStyle=S,a.fillRect(j,v,10,w-v),a.fillStyle=h,a.textAlign=s==="left"?"right":"left",a.textBaseline="middle";const N=s==="left"?j-6:j+10+6;a.fillText(o(n),N,v),a.fillText(o(t+(n-t)/2),N,(v+w)/2),a.fillText(o(t),N,w)}a.restore()}}}function Uu(e){if(!e)return"#3b82f6";if(e.startsWith("rgb"))return e;if(e.startsWith("#")){const t=jU(e);return t?b1e(t.r,t.g,t.b,1):e}return e}function P5(e,t,n){const r=Aw(e),s=Aw(t);if(!r||!s)return e;const o=Db(n,0,1),i=Math.round(r.r+(s.r-r.r)*o),a=Math.round(r.g+(s.g-r.g)*o),l=Math.round(r.b+(s.b-r.b)*o),u=r.a+(s.a-r.a)*o;return`rgba(${i}, ${a}, ${l}, ${u})`}function Aw(e){if(e.startsWith("#")){const n=jU(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 jU(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 b1e(e,t,n,r){return`rgba(${e}, ${t}, ${n}, ${r})`}function x1e(e){const t=Aw(e);return t?`#${lN(t.r)}${lN(t.g)}${lN(t.b)}`:"#000000"}function lN(e){return Db(Math.round(e),0,255).toString(16).padStart(2,"0")}function y1e(e,t){const n=Aw(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${Db(t,0,1)})`:e}function Db(e,t,n){return Math.min(n,Math.max(t,e))}function jD(e,t){return e==null||Number.isNaN(e)?"—":Er(e,t.format,t.options)}function v1e(e){var r,s,o;const t=((r=e==null?void 0:e.dataLabelsConfig)==null?void 0:r.format)??((s=e==null?void 0:e.numberAxisFormat)==null?void 0:s.format)??"number",n=((o=e==null?void 0:e.dataLabelsConfig)==null?void 0:o.formatOptions)??(e==null?void 0:e.numberAxisFormat)??(e==null?void 0:e.formatNumber)??{};return{format:!t||t==="none"?"number":t,options:n}}function w1e(e){return e.reduce((t,n)=>n?Jh({},t,n):t,{})}function AE(){return{enabled:!0,position:"right",labels:{enabled:!0,rotation:"auto"},name:{enabled:!1}}}function C1e(e){return Array.from({length:e},(t,n)=>({idx:n,type:"bar",yAxisId:"y"}))}function S1e(e){return!e||e.length===0?!1:e.some(t=>t.yAxisId==="y2")}function j1e(e,t){var r,s,o,i,a,l,u,d,f,h,m,p,g,b;if(!t)return e||AE();const n=AE();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:((l=t==null?void 0:t.name)==null?void 0:l.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)??((m=e==null?void 0:e.labels)==null?void 0:m.enabled)??((p=n.labels)==null?void 0:p.enabled)??!0,rotation:((g=t==null?void 0:t.labels)==null?void 0:g.rotation)??((b=e==null?void 0:e.labels)==null?void 0:b.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 N1e(e,t){const n=C1e(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 k1e(e,t,n){const r=n==null?void 0:n.yAxisConfig,s=n==null?void 0:n.secondaryYAxisConfig,o=n==null?void 0:n.dataLabelsConfig;return e.map((i,a)=>{const l=t.find(p=>p.idx===a),u={...i},d=(l==null?void 0:l.type)||"bar";u.type=d;const f=(l==null?void 0:l.fill)!==void 0&&(l==null?void 0:l.fill)!=="";if(d==="line"){if(u.borderWidth=u.borderWidth??2,u.tension=u.tension??.1,u.pointRadius=(l==null?void 0:l.pointRadius)??3,u.pointStyle=(l==null?void 0:l.pointStyle)??"circle",u.pointHoverRadius=(l==null?void 0:l.pointHoverRadius)??((l==null?void 0:l.pointRadius)??3)+2,u.borderDash=SD(l==null?void 0:l.lineStyle),f){const p=u.borderColor||u.backgroundColor;p&&typeof p=="string"&&(u.backgroundColor=yU(p,.3)),u.fill=l.fill}u.order=0}else u.order=1;l!=null&&l.yAxisId&&(u.yAxisID=l.yAxisId);const h=(l==null?void 0:l.yAxisId)==="y2"?s:r,m=DC(o,l==null?void 0:l.dataLabels);return m&&(u.datalabels=TC(m,h,d==="line"?"line":"bar")),u})}function E1e(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 l=j1e(AE(),n==null?void 0:n.secondaryYAxisConfig);r.y2={...e==null?void 0:e.y2,type:"linear",display:l.enabled!==!1,position:l.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=l.labels)==null?void 0:i.enabled)!==!1},title:(a=l.name)!=null&&a.enabled?{display:!0,text:l.name.text||"",font:{size:l.name.fontSize||12,weight:l.name.fontWeight||"normal"}}:void 0},l.scale&&(l.scale.min!==void 0&&l.scale.min!=="auto"&&(r.y2.min=l.scale.min),l.scale.max!==void 0&&l.scale.max!=="auto"&&(r.y2.max=l.scale.max),l.scale.stepSize!==void 0&&l.scale.stepSize!=="auto"&&(r.y2.ticks={...r.y2.ticks,stepSize:l.scale.stepSize}))}return r}function _1e({card:e,data:t,cfg:n,customCfg:r,preferences:s}){var w,j;const{keys:o}=zn(t),i=vb(o),a=i.length,l=N1e(s==null?void 0:s.datasetOptions,a),u=S1e(l),d=o==null?void 0:o[0],f=nc(t,d),h=Gm(i,t,s,1,"none",d,!1,Ym(t)),m=k1e(h,l,s),p=ta(m,r),{options:g,plugins:b}=ou({cardType:"combo",cfg:n,preferences:s,customCfg:r,card:e}),x=E1e(g==null?void 0:g.scales,u,s),y={...g,scales:x},v=(((j=(w=e.interactionConfig)==null?void 0:w.interactions)==null?void 0:j.length)??0)>0;return MC(y,v),{type:"bar",data:{labels:f,datasets:p},options:y,plugins:b}}function T1e(e,t,n,r){const s=n==null?void 0:n.lineStyleConfig,o=n==null?void 0:n.yAxisConfig,i=(r==null?void 0:r.some(a=>a._forecast))??!1;return e.map((a,l)=>{const u=t.find(m=>m.idx===l),d={...a};d.type="line",d.fill=!1,d.borderWidth=d.borderWidth??2,d.tension=d.tension??.1;const f=(u==null?void 0:u.pointRadius)??(s==null?void 0:s.pointRadius)??3;d.pointRadius=f,d.pointStyle=(u==null?void 0:u.pointStyle)??(s==null?void 0:s.pointStyle)??"circle",d.pointHoverRadius=(u==null?void 0:u.pointHoverRadius)??f+2,d.borderDash=SD((u==null?void 0:u.lineStyle)??(s==null?void 0:s.lineStyle)),i&&r&&M1e(d,r,a.borderColor);const h=DC(n==null?void 0:n.dataLabelsConfig,u==null?void 0:u.dataLabels);return h&&(d.datalabels=TC(h,o,"line")),d})}function M1e(e,t,n){const r=J.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 D1e(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 I1e({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var v,w;const{keys:i}=zn(t),a=vb(i),l=(s==null?void 0:s.datasetOptions)||[],u=i==null?void 0:i[0],d=nc(t,u),f=Gm(a,t,s,1,"none",u,!1,Ym(t)),h=T1e(f,l,s,t),m=ta(h,r),{options:p,plugins:g}=ou({cardType:o||"line",cfg:n,preferences:s,customCfg:r,card:e}),b=D1e(p==null?void 0:p.scales),x={...p,scales:b},y=(((w=(v=e.interactionConfig)==null?void 0:v.interactions)==null?void 0:w.length)??0)>0;return MC(x,y),{type:"line",data:{labels:d,datasets:m},options:x,plugins:g}}function R1e(e,t,n,r,s){const o=n==null?void 0:n.barStyleConfig,i=s==="horizontalBar"?n==null?void 0:n.xAxisConfig:n==null?void 0:n.yAxisConfig,a=(r==null?void 0:r.some(l=>l._forecast))??!1;return e.map((l,u)=>{const d=t.find(m=>m.idx===u),f={...l};f.borderRadius=(d==null?void 0:d.borderRadius)??(o==null?void 0:o.borderRadius)??0,f.borderWidth=(d==null?void 0:d.barBorderWidth)??(o==null?void 0:o.borderWidth)??0,f.barPercentage=(d==null?void 0:d.barPercentage)??(o==null?void 0:o.barPercentage)??.9,f.categoryPercentage=(d==null?void 0:d.categoryPercentage)??(o==null?void 0:o.categoryPercentage)??.8,a&&r&&A1e(f,r,l.backgroundColor);const h=DC(n==null?void 0:n.dataLabelsConfig,d==null?void 0:d.dataLabels);if(h){const m=s==="horizontalBar"?"horizontalBar":"bar";f.datalabels=TC(h,i,m)}return f})}function A1e(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 P1e(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 O1e(e){return e==="horizontalBar"?"y":void 0}function cN({card:e,data:t,cfg:n,customCfg:r,preferences:s,cardType:o}){var k,M,T,P;let i=t;const{keys:a}=zn(i),l=vb(a),u=(s==null?void 0:s.datasetOptions)||[],d=a==null?void 0:a[0],f=Ym(i),h=o==="stackedBar",m=((k=e.config)==null?void 0:k.pivotByColumns)&&e.config.pivotByColumns.length>0,p=((M=e.config)==null?void 0:M.groupByColumns)&&e.config.groupByColumns.length>0;h&&!f&&(!m||!p)&&(i=Lx({dataArray:i,groupKey:a[0],pivotKey:a[1],valueKey:a[2],sortChart:s==null?void 0:s.sortChart}));const g=nc(i,d),b=Gm(h?vb(zn(i).keys):l,i,s,1,"none",d,h,f),x=R1e(b,u,s,i,o),y=ta(x,r),{options:v,plugins:w}=ou({cardType:o||"bar",cfg:n,preferences:s,customCfg:r,card:e}),j=o||"bar",S=P1e(v==null?void 0:v.scales,j,f),N=O1e(j),E={...v,scales:S,...N&&{indexAxis:N}},_=(((P=(T=e.interactionConfig)==null?void 0:T.interactions)==null?void 0:P.length)??0)>0;return MC(E,_),{type:"bar",data:{labels:g,datasets:y},options:E,plugins:w}}function ND({card:e,data:t,cardType:n="bar",cfg:r,customCfg:s,provider:o="chartjs",userSettings:i,preferences:a,topoJson:l,queryConfig:u,isDevMode:d}){var b,x,y,v,w,j,S,N;const f=e.config,h=d??!!e.sql;let m=t;const p=f&&f.pivotByColumns&&f.pivotByColumns.length>0,g=f&&f.groupByColumns&&f.groupByColumns.length>0;if(p&&g&&(m=Ahe(t,(f==null?void 0:f.metricColumns)||[])),n==="map"){if(!l)return null;const E=(b=a==null?void 0:a.mapVisualOptions)==null?void 0:b.objectKey;if(!E)return null;const _=zve(l,(x=l==null?void 0:l.objects)==null?void 0:x[E]).features;if(!_)return null;const k={plugins:{datalabels:{display:!1}},scales:{x:{display:!1,grid:{display:!1}},y:{display:!1,grid:{display:!1}},projection:{axis:"x",projection:((y=a==null?void 0:a.mapVisualOptions)==null?void 0:y.projection)||"mercator",projectionScale:((v=a==null?void 0:a.mapVisualOptions)==null?void 0:v.projectionScale)||1,projectionOffset:((w=a==null?void 0:a.mapVisualOptions)==null?void 0:w.projectionOffset)||[0,0]},color:{axis:"x",interpolate:((j=a==null?void 0:a.mapVisualOptions)==null?void 0:j.colorScale)||"blues",quantize:5,legend:{position:"bottom-right",align:"right"}}}},{keys:M}=zn(m),T=_.map(W=>{var F;const L=M==null?void 0:M[0],R=M==null?void 0:M[1],z=(F=m.find(A=>(A==null?void 0:A[L])===W.properties.NAME||(A==null?void 0:A[L])===W.properties.name))==null?void 0:F[R];return{feature:W,value:z}}),O=ta([{label:E,data:T,borderColor:"lightgray"}],s),I={type:"choropleth",data:{labels:_.map(W=>W.properties.NAME||W.properties.name),datasets:O},options:k},{options:$}=ou({cfg:I,preferences:a,customCfg:s,cardType:n});return{...I,options:$}}if(n==="bar")return cN({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="horizontalBar")return cN({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="funnel")return pwe({data:m,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="tornado"||n==="pyramid")return xwe({data:m,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="treemap")return ywe({data:m,cfg:r,customCfg:s,preferences:a});if(n==="heatmap")return i1e({data:m,cfg:r,customCfg:s,preferences:a,cardType:n});if(n==="bullet")return zwe({data:m,cfg:r,customCfg:s,preferences:a});if(n==="stackedBar")return cN({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="stackedLine"){const E=Ym(m),_=Kve(r,n,E),{keys:k}=zn(m);return!E&&(!p||!g)&&(m=Lx({dataArray:m,groupKey:k[0],pivotKey:k[1],valueKey:k[2],sortChart:a==null?void 0:a.sortChart})),Kj({card:e,data:m,cfg:_,customCfg:s,cardType:n,preferences:a})}if(n==="line")return I1e({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="area"||n==="stackedArea")return Fwe({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a});if(n==="combo")return _1e({card:e,data:m,cfg:r,customCfg:s,preferences:a});if(n==="range")return gwe({data:m,cfg:r,customCfg:s,preferences:a,card:e});if(n==="pie"||n==="doughnut"||n==="polarArea"){const E=Zve(n,r),{keys:_}=zn(m),k=_.slice(0,1),M=_.slice(1),T=gV(M,m,a,k==null?void 0:k[0]),P=ta(T,s),{plugins:O,options:I}=Cu((a==null?void 0:a.customVisualCode)||""),$=k[0],V=nc(m,$),W=jr((E==null?void 0:E.options)||{},(s==null?void 0:s.options)||{}),L=jr(W,(a==null?void 0:a.chartOptions)||{}),R={...L,plugins:{...L.plugins,datalabels:{...(S=L.plugins)==null?void 0:S.datalabels,formatter:(Y,q)=>{var U,G,Z,Q;return Js({number:Number(Y),decimalPlaces:((U=a==null?void 0:a.numberAxisFormat)==null?void 0:U.decimalPlaces)||0,useSuffix:!!((G=a==null?void 0:a.numberAxisFormat)!=null&&G.suffix),customSuffix:"",locale:((Z=a==null?void 0:a.numberAxisFormat)==null?void 0:Z.locale)||"",currency:((Q=a==null?void 0:a.numberAxisFormat)==null?void 0:Q.currency)||""})}},tooltip:{...(N=L.plugins)==null?void 0:N.tooltip,callbacks:{label:function(Y){var K,te,le,de;Y.dataset.label;const U=Y.dataset.data.reduce((ce,Ce)=>ce+Ce,0),G=Y.parsed,Z=Js({number:Number(G),decimalPlaces:((K=a==null?void 0:a.numberAxisFormat)==null?void 0:K.decimalPlaces)||0,useSuffix:!!((te=a==null?void 0:a.numberAxisFormat)!=null&&te.suffix),customSuffix:"",locale:((le=a==null?void 0:a.numberAxisFormat)==null?void 0:le.locale)||"",currency:((de=a==null?void 0:a.numberAxisFormat)==null?void 0:de.currency)||""}),Q=(G/U*100).toFixed(2);return Z+` (${Q}%)`},footer:function(Y){var U,G,Z,Q;return(((G=(U=e==null?void 0:e.interactionConfig)==null?void 0:U.drillHierarchies)==null?void 0:G.length)??0)>0||(((Q=(Z=e==null?void 0:e.interactionConfig)==null?void 0:Z.interactions)==null?void 0:Q.some(K=>K.mode==="drillDown"||K.mode==="drillToDetail"||K.mode==="drillThrough"||K.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},z=jr(L,R),{options:F}=ou({cfg:{options:z},preferences:a,customCfg:s,cardType:n,card:e}),A=jr(F,I);return{type:n,data:{labels:V,datasets:P},options:A,plugins:[n==="doughnut"?{id:"doughnutLabel",beforeDatasetsDraw:function(Y,q,U){var Ce,ge,he,me;const{ctx:G,data:Z}=Y;G.save();const Q=Y.getDatasetMeta(0).data[0].x,K=Y.getDatasetMeta(0).data[0].y,te=wo(Hi()),le=window.getComputedStyle(G.canvas).fontFamily;G.font=`1em ${le}`,G.fontWeight="bolder",G.fillStyle=te,G.textAlign="center",G.textBaseline="middle";const de=Z.datasets[0].data.reduce((oe,Ne)=>oe+Ne,0),ce=Js({number:Number(de),decimalPlaces:((Ce=a==null?void 0:a.numberAxisFormat)==null?void 0:Ce.decimalPlaces)||0,useSuffix:!!((ge=a==null?void 0:a.numberAxisFormat)!=null&&ge.suffix),customSuffix:"",locale:((he=a==null?void 0:a.numberAxisFormat)==null?void 0:he.locale)||"",currency:((me=a==null?void 0:a.numberAxisFormat)==null?void 0:me.currency)||""});G.fillText(ce,Q,K)}}:"",...O]}}if(n==="radar"){const E=Xve(r);return Kj({card:e,data:m,cfg:E,customCfg:s,cardType:n,preferences:a})}return n==="bubble"||n==="scatter"?ewe({data:m,cfg:r,customCfg:s,preferences:a,cardType:n,cardConfig:f,isDevMode:h,card:e}):Kj({card:e,data:m,cfg:r,customCfg:s,cardType:n,preferences:a})}function F1e({chart:e,elementIndex:t,datasetIndex:n,cardType:r,cfg:s,apply:o}){const i=J.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)&&L1e(e,t,s,o,a),["pie","doughnut","polarArea","funnel"].includes(r)&&z1e(e,t,s,o,a),["stackedBar","pyramid"].includes(r)&&$1e({chart:e,elementIndex:t,datasetIndex:n,cfg:s,apply:o,blurColor:a})}function $1e(e){var a,l,u,d;const{chart:t,elementIndex:n,datasetIndex:r,cfg:s,apply:o,blurColor:i}=e;o?(l=(a=t==null?void 0:t.data)==null?void 0:a.datasets)==null||l.forEach((f,h)=>{var m,p;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=(m=f==null?void 0:f.backgroundColor)==null?void 0:m.map((g,b)=>b===n&&h===r?g:i),f.borderColor=(p=f==null?void 0:f.borderColor)==null?void 0:p.map((g,b)=>b===n&&h===r?g:i)}):(d=(u=t==null?void 0:t.data)==null?void 0:u.datasets)==null||d.forEach((f,h)=>{var m,p,g,b,x,y;f.backgroundColor=new Array(f.data.length).fill((g=(p=(m=s==null?void 0:s.data)==null?void 0:m.datasets)==null?void 0:p[h])==null?void 0:g.backgroundColor),f.borderColor=new Array(f.data.length).fill((y=(x=(b=s==null?void 0:s.data)==null?void 0:b.datasets)==null?void 0:x[h])==null?void 0:y.borderColor)}),t==null||t.update()}function L1e(e,t,n,r,s){var o,i,a,l;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,m)=>m===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,m)=>m===t?h:s)}):(l=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||l.forEach((u,d)=>{var f,h,m,p,g,b;u.backgroundColor=new Array(u.data.length).fill((m=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:m.backgroundColor),u.borderColor=new Array(u.data.length).fill((b=(g=(p=n==null?void 0:n.data)==null?void 0:p.datasets)==null?void 0:g[d])==null?void 0:b.borderColor)}),e==null||e.update()}function z1e(e,t,n,r,s){var o,i,a,l;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,m)=>m===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,m)=>m===t?h:s)}):(l=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||l.forEach((u,d)=>{var f,h,m,p,g,b,x,y;typeof u.backgroundColor=="string"&&(u.backgroundColor=(m=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:m.backgroundColor,u.borderColor=(b=(g=(p=n==null?void 0:n.data)==null?void 0:p.datasets)==null?void 0:g[d])==null?void 0:b.borderColor),u.backgroundColor=(x=u==null?void 0:u.backgroundColor)==null?void 0:x.map((v,w)=>{var j;return(j=n.data.datasets[d].backgroundColor)==null?void 0:j[w]}),u.borderColor=(y=u==null?void 0:u.borderColor)==null?void 0:y.map((v,w)=>{var j;return(j=n.data.datasets[d].borderColor)==null?void 0:j[w]})}),e==null||e.update()}function B1e({card:e,data:t,datasetIndex:n,clickIndex:r,value:s}){var o,i,a,l,u,d,f;try{if(!t)return;const{keys:h}=zn(t);if(e.type==="map"){const m=h[0],p=((i=(o=s==null?void 0:s.feature)==null?void 0:o.properties)==null?void 0:i.name)||((l=(a=s==null?void 0:s.feature)==null?void 0:a.properties)==null?void 0:l.NAME);return[{columnName:m,columnValue:p}]}if(["bar","horizontalBar","line","pie","doughnut","radar","polarArea","funnel"].includes(e.type)){const m=h[0],p=h.slice(1),g=(u=t[r])==null?void 0:u[m];return[{columnName:m,columnValue:g,metric:p[n],value:s}]}if(["stackedBar","pyramid"].includes(e.type)){const m=Lx({dataArray:t,groupKey:h[0],pivotKey:h[1],valueKey:h[2]}),p=h[0],g=(d=m[r])==null?void 0:d[p],b=h[1],{keys:x}=zn(m),v=x.slice(1)[n];return[{columnName:p,columnValue:g,metric:h[2],value:s},{columnName:b,columnValue:v,metric:h[2],value:s}]}if(e.type==="bubble"||e.type==="scatter"){const m=h[0],p=(f=t[n])==null?void 0:f[m];return console.log(s,"bubble"),[{columnName:m,columnValue:p,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 NU(e){var a,l,u,d,f,h;const t=(((l=(a=e.preferences)==null?void 0:a.mapVisualOptions)==null?void 0:l.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}=En({queryKey:["topojson",t],queryFn:()=>fetch(t).then(m=>m.json()),enabled:n,staleTime:1/0});return{data:r,isLoading:s,isFetching:o,isError:i}}const cu="SEMAPHOR_CALCULATED_FIELD",V1e=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","YYYY-MM-DD HH:mm","YYYY-MM-DD HH:mm:ss","YYYY-MM-DD HH:mm Z","YYYY-MM-DD HH:mm:ss Z","Week of MMM DD, YYYY","Week of MMMM DD, YYYY","YYYY-WW","MMM YYYY","MMMM YYYY","YYYY-MM","MM/YYYY","YYYY MMM","Q1 YYYY","YYYY Q1","1st Quarter YYYY","YYYY-Q1","Quarter 1, YYYY","YYYY","YY","custom"];function sc(e){return e.role==="metric"&&"expression"in e&&!!e.expression}function Ux(e){return!!e.expression}function Pw(e){return!!e.expression}var kU=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(kU||{});function Ci(e){const{tokenProps:t}=Xe(),n=J(h=>h.authToken)||e,r=Ae(h=>h.selectedConnectionId),s=Ae(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r||s,{refetch:i,isPending:a,data:l,isLoading:u,isError:d}=En({queryKey:[t.project_id,"connections"],queryFn:()=>rr(`${t.apiServiceUrl}/v1/connections`,(n==null?void 0:n.accessToken)||""),enabled:!!(n!=null&&n.accessToken)}),f=l==null?void 0:l.connections.find(h=>h.id===o);return{isPending:a,error:d,connectionsData:l,connections:(l==null?void 0:l.connections)||[],isConnectionsLoading:u,isConnectionsError:d,refetchConnections:i,selectedConnection:f}}function EU(e){const{connections:t}=Ci(e),n=Ae(o=>o.selectedConnectionId),r=t.find(o=>o.id===n),s=r==null?void 0:r.capabilities.path.includes("schema");return{selectedConnection:r,capabilities:r==null?void 0:r.capabilities,connectionType:r==null?void 0:r.type,hasSchemaSupport:s}}const H1e=[],U1e=[],W1e=[];function q1e(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||pi(n.name),description:n.description,entityId:n.entityId||t.entityId,entityName:n.entityName||t.entityName,entityType:n.entityType||t.entityType})))}function gh(e){if(e.type==="model")return`${Uv}.${e.name}`;if(e.type==="dataset"){if(e.database&&e.schema)return`${e.database}.${e.schema}.${e.name}`;if(e.schema)return`${e.schema}.${e.name}`;if(e.database)return`${e.database}.${e.name}`}if(uk.includes(e.type)){if(e.database&&e.schema)return`${e.database}.${e.schema}.${e.name}`;if(e.schema)return`${e.schema}.${e.name}`;if(e.database)return`${e.database}.${e.name}`}return e.name}function kD(e){var v;const{tokenProps:t}=Xe(),n=J(w=>w.authToken)||e,{hasSchemaSupport:r}=EU(e),s=Ae(w=>{var j;return(j=w.card.dataSource)==null?void 0:j.connectionId}),o=Ae(w=>{var j;return(j=w.card.dataSource)==null?void 0:j.semanticDomainId}),i=Ae(w=>{var j;return(j=w.card.dataSource)==null?void 0:j.selectedEntities}),a=C.useMemo(()=>(i==null?void 0:i.filter(w=>w.type==="model"))||H1e,[i]),l=C.useMemo(()=>(i==null?void 0:i.filter(w=>uk.includes(w.type)))||U1e,[i]),u=C.useMemo(()=>(i==null?void 0:i.filter(w=>w.type==="dataset"))||W1e,[i]);function d(w){return w.type==="dataset"?!!s&&!!w.domainId&&!!w.name:w.type==="model"?!!s&&!!w.id:uk.includes(w.type)?r?!!s&&!!w.name&&!!w.database&&!!w.schema:["S3","API"].includes(w.connectionType)?!!s&&!!w.name:!!s&&!!w.name&&!!w.database:!1}const f=[...a,...l,...u],h=AT({queries:f.map(w=>{let j={};return w.type==="model"?j={connection_id:s,datamodel_id:w.id,database_name:"",schema_name:"",table_name:""}:w.type==="dataset"?j={connection_id:w.connectionId,domain_id:w.domainId,dataset_name:w.name}:j={connection_id:s,datamodel_id:"",database_name:w.database,schema_name:w.schema,table_name:w.name},{queryKey:["columns",s,w,o||null],queryFn:()=>rr(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",j),enabled:!!s&&d(w)}})}),m=h.some(w=>w.isPending),p=h.some(w=>w.isError),g=(v=h.find(w=>w.isError))==null?void 0:v.error,b=h.map((w,j)=>{var E;const S=f[j],N=gh(S);return{entityId:S.id||S.name,entityType:S.type,entityName:S.name,label:S.label,description:S.description,qualifiedEntityName:N,columns:(E=w.data)==null?void 0:E.columns.map(_=>({id:`${S.name}-${_.column_name}`,name:_.column_name,qualifiedFieldName:_.qualifiedFieldName||_.column_name,dataType:_.data_type,label:_.label||cb(_.column_name),description:_.description||"",qualifiedEntityName:N,entityId:S.id||S.id||S.name,entityName:S.name,entityType:S.type}))}}).filter(w=>{var j;return((j=w==null?void 0:w.columns)==null?void 0:j.length)>0})||[],x=h.flatMap(w=>{var j;return((j=w.data)==null?void 0:j.calculatedFields)||[]}).map(w=>({...w,fieldScope:"domain"}));if(x.length>0){const w=new Map;x.forEach(j=>{const S=`${j.name}-${j.role||"unknown"}`;w.has(S)||w.set(S,j)}),b.unshift({entityId:pz,entityType:"dataset",entityName:Qh,label:"Calculated Fields",description:"Domain-level calculated metrics and dimensions",qualifiedEntityName:Qh,columns:Array.from(w.values())})}const y=q1e(b);return{columnGroups:b,columns:y,isLoading:m,hasError:p,error:g,refetch:()=>{h.forEach(w=>w.refetch())}}}function Y1e(e,t,n){if(e===t)return!0;const r=new Map;for(const i of n){const a=i.source.name,l=i.target.name;r.has(a)||r.set(a,new Set),r.get(a).add(l),r.has(l)||r.set(l,new Set),r.get(l).add(a)}const s=new Set,o=[e];for(s.add(e);o.length>0;){const i=o.shift(),a=r.get(i);if(a)for(const l of a){if(l===t)return!0;s.has(l)||(s.add(l),o.push(l))}}return!1}function ED(e,t){var g,b,x,y,v,w,j;const{joinabilityMap:n,selectedFields:r,cardConfig:s,autoJoinMetadata:o,baseEntityName:i}=t;if(!n)return{state:"draggable"};if(e.entityName===cu||Pw(e))return{state:"draggable"};const a=r.filter(S=>S.entityName!==cu&&!Pw(S));if(a.length===0)return{state:"draggable",tooltip:"Select to establish base dataset"};let l;const u=(b=(g=s==null?void 0:s.joinPlan)==null?void 0:g.baseEntity)==null?void 0:b.name,d=(y=(x=o==null?void 0:o.resolvedJoinPlan)==null?void 0:x.baseEntity)==null?void 0:y.name;u?l=u:d?l=d:i?l=i:l=[...new Set(a.map(N=>N.entityName))].filter(Boolean)[0];const f=r.some(S=>S.entityName===e.entityName&&(S.name===e.name||S.id===e.id));if(e.entityName===l)return{state:"base",tooltip:f?"Field already in query (base dataset)":"From base dataset",isSelected:f};const h=n[l];if(!h)return{state:"unreachable",tooltip:"No relationships defined for base dataset"};if(h.canJoinTo.includes(e.entityName))return{state:"draggable",tooltip:`Direct join from ${l}`,joinPath:[l,e.entityName],isSelected:f};const m=(v=h.indirectJoins)==null?void 0:v[e.entityName];if(m&&m.length>0){const S=[l,...m,e.entityName];return{state:"indirect",joinPath:S,tooltip:`Multi-hop join: ${S.join(" → ")}`,isSelected:f}}const p=n[e.entityName];if(p){if(p.canJoinTo.includes(l))return{state:"draggable",tooltip:`Direct join to ${l}`,joinPath:[e.entityName,l],isSelected:f};const S=(w=p.indirectJoins)==null?void 0:w[l];if(S&&S.length>0){const N=[e.entityName,...S,l];return{state:"indirect",joinPath:N,tooltip:`Multi-hop join: ${N.join(" → ")}`,isSelected:f}}}return(j=s==null?void 0:s.joinPlan)!=null&&j.joins&&s.joinPlan.joins.length>0&&Y1e(l,e.entityName,s.joinPlan.joins)?{state:"draggable",tooltip:"Manual join configured",isSelected:f}:{state:"unreachable",tooltip:`Cannot join ${e.entityName} to ${l}`,isSelected:f}}function _U(e,t,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:e===t||e===gh(n.baseEntity)||t===gh(n.baseEntity)?!0:n.joins.some(s=>{const o=gh(s.source),i=gh(s.target);return o===e&&i===t||o===t&&i===e})}function G1e(e,t,n){var l;const{joinPlan:r,joinabilityMap:s,semanticDomainId:o}=n,i=t.filter(u=>u.entityName!==cu&&u.qualifiedEntityName!==Qh);if(i.length===0)return{isValid:!0};const a=i[0].qualifiedEntityName;if(!a)return{isValid:!0};if(a===e.qualifiedEntityName)return{isValid:!0};if(e.qualifiedEntityName){if(o&&s)return ED(e,{joinabilityMap:s,selectedFields:t,baseEntityName:(l=r==null?void 0:r.baseEntity)==null?void 0:l.name}).state==="unreachable"?{isValid:!1,showError:!0}:{isValid:!0};if(!r)return{isValid:!1,showError:!0};if(!_U(a,e.qualifiedEntityName,r))return{isValid:!1,showError:!0}}return{isValid:!0}}function TU(){ze.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 MU(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||{},l=JSON.stringify(i),u=JSON.stringify(a);if(l!==u)return!1}return!1}return!0})}function K1e(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 Z1e(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})`}function DU(e,t){return`${e}-${t.qualifiedEntityName}-${t.name}-${Date.now()}`}function IU(e,t){const n=pi(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 X1e(e,t,n){const r=yr(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 RU(e,t,n=[]){const r=DU(t,e),s=yr(e.dataType),o=s==="date",i=e.role==="metric"&&"expression"in e&&!!e.expression,a=e.role==="groupby"&&"expression"in e&&!!e.expression,l={id:r,name:e.name,dataType:e.dataType,label:cb(e.name),qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityId:e.entityId,entityName:e.entityName,entityType:e.entityType};if(t==="metrics"){if(i){const{fieldScope:h,...m}=e;return{...m,id:r,label:e.label||e.name,role:"metric"}}const u=s==="number"?"SUM":"COUNT",d=IU(e.label,u),f=Z1e({...l,label:d},n,t);return{...l,role:"metric",label:f,aggregate:u}}if(t==="groupBy"){if(a){const{fieldScope:u,...d}=e;return{...d,id:r,label:e.label||e.name,role:"groupby"}}return{...l,role:"groupby",...o&&{granularity:"month",dateFormat:"YYYY-MM"}}}if(t==="pivotBy")return{...l,role:"pivotby"};if(t==="detailColumns"){if(i){const{fieldScope:u,aggregate:d,parameters:f,aliasTemplate:h,valueAliases:m,...p}=e;return{...p,id:r,label:e.label||e.name,role:"detail"}}if(a){const{fieldScope:u,...d}=e;return{...d,id:r,label:e.label||e.name,role:"detail"}}return{...l,role:"detail"}}return t==="sortBy"?{...l,role:"sortby",label:e.label,direction:"asc"}:null}function Q1e(e){var o,i,a,l;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=(l=e.config)==null?void 0:l.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 J1e(e){var i,a;const[t]=C.useState({id:"",title:"",type:"bar"}),{getCard:n}=Wt(),r=n(e),s=Wx(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 Wx(e){var P;const{onChartElementClicked:t}=Xe(),[n,r]=C.useState(0),s=J(O=>O.themeStyle),o=J(O=>O.filteringCards),i=J(O=>O.selectedSheetId),a=J(O=>O.selectedLensId),l=J(O=>O.filterValues),u=C.useRef(l),d=(P=e==null?void 0:e.preferences)==null?void 0:P.onClickFilter,{addFilteringCard:f,addOrUpdateFilterValues:h,removeFilterValues:m,removeFilteringCard:p}=Wt(),{data:g,isLoading:b,isFetching:x,isError:y,isPending:v,queryKey:w,isFilteringCard:j,isSingleCardFrame:S,pagination:N,comparisonMetadata:E}=Ha(e),{data:_}=NU(e);let k;k=C.useMemo(()=>{if(!(!(g!=null&&g.records)||!(g!=null&&g.records.length)))return ND({card:e,data:g==null?void 0:g.records,cardType:e.type,queryConfig:e.queryConfig,customCfg:e.customCfg,preferences:e.preferences,topoJson:_})},[g==null?void 0:g.records,e.type,e.queryConfig,e.customCfg,e.config,e.preferences,_,s]);const M=C.useRef({filteringCards:o});C.useEffect(()=>{e.connectionId&&!j&&(u.current=l)},[l,a,e.connectionId,j]),C.useEffect(()=>{var I;j&&(M.current.filteringCards=[...o||[]]),!j&&((I=M.current.filteringCards)==null?void 0:I.find($=>$.id===e.id))&&S&&r($=>$+1)},[j,S,e.id,o]);function T(O,I,$,V){var R;if(Q1e(e))return;let W=!1;if(!(g!=null&&g.records))return;const L=B1e({card:e,data:g==null?void 0:g.records,datasetIndex:I,clickIndex:$,value:V});if(console.log("fieldValues",L),t==null||t(e,L),!!(((R=e==null?void 0:e.preferences)==null?void 0:R.onClickFilter)??[]).length){if(j){const z=e.id;m(z),p(e)}else{if(W=!0,!L)return;const z=[];L.forEach((F,A)=>{const H=d==null?void 0:d.find(Y=>Y.columnIndex===A);if(!H)return;const B={filterId:e.id+"-"+F.columnName+"-"+i,connectionId:e==null?void 0:e.connectionId,tableName:e.lastSelectedTable,name:F.columnName,expression:H.expression,valueType:jT(L[H.columnIndex].columnValue),operation:"=",values:[L[H.columnIndex].columnValue]};z.push(B)}),h(z),f(e)}F1e({chart:O,elementIndex:$,datasetIndex:I,cardType:e.type,cfg:k,apply:W})}}return{isPending:v,isError:y,isLoading:b,isFetching:x,data:g,visualKey:n,handleDatapointClick:T,cfg:k,queryKey:w,pagination:N,comparisonMetadata:E}}function AU(e){var x;const{tokenProps:t}=Xe(),n=J(y=>y.authToken)||e,r=Ae(y=>y.selectedConnectionId),s=Ae(y=>y.selectedDatabaseName),o=Ae(y=>y.selectedDatamodelId),i=Ae(y=>y.selectedSchemaName),a=Ae(y=>y.selectedTableName),{selectedConnection:l}=Ci(),u=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:m,refetch:p}=En({queryKey:["columns",r,s,o,i,a],queryFn:()=>rr(`${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:g(u)});function g(y){return n!=null&&n.accessToken?!!(r&&s&&s!=="NA"&&i&&a||r&&(y==="S3"||y==="API")||o&&o):!1}return{columns:(x=d==null?void 0:d.columns)==null?void 0:x.map(y=>({...y,data_type:y.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:m,refetchColumns:p}}function Ih(e,t){const[n,r]=C.useState(e);return C.useEffect(()=>{const s=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(s)}},[e,t]),n}var eCe=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,s,o;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(s=r;s--!==0;)if(!e(t[s],n[s]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(o=Object.keys(t),r=o.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[s]))return!1;for(s=r;s--!==0;){var i=o[s];if(!(i==="_owner"&&t.$$typeof)&&!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n};const PU=hf(eCe);function E0(e,t=PU){const[n,r]=C.useState(()=>({value:e,lastInput:e}));if(!t(n.lastInput,e)){const s=t(n.value,e)?n.value:e;return r({value:s,lastInput:e}),s}return n.value}function tCe(e=[],t=[]){var r,s,o,i;if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;const n=Math.min(5,e.length);for(let a=0;a<n;a++)if(((r=e[a])==null?void 0:r.id)!==((s=t[a])==null?void 0:s.id))return!1;for(let a=0;a<n;a++){const l=e.length-1-a;if(((o=e[l])==null?void 0:o.id)!==((i=t[l])==null?void 0:i.id))return!1}return PU(e,t)}gre();const IC=oa()(Im((e,t)=>({activeExports:new Map,actions:{addExport:n=>{e(r=>{r.activeExports.set(n.id,{...n,lastUpdatedAt:n.lastUpdatedAt??new Date})})},updateExport:(n,r)=>{e(s=>{const o=s.activeExports.get(n);if(o){const i={...o,...r};r.lastUpdatedAt||(i.lastUpdatedAt=new Date),s.activeExports.set(n,i)}})},removeExport:n=>{e(r=>{r.activeExports.delete(n)})},getInProgressExports:()=>Array.from(t().activeExports.values()).filter(r=>["pending","processing","chunking","compacting"].includes(r.status)),getAllExports:()=>Array.from(t().activeExports.values()).sort((n,r)=>r.startedAt.getTime()-n.startedAt.getTime()),clearCompleted:()=>{e(n=>{for(const[r,s]of n.activeExports)(s.status==="completed"||s.status==="failed")&&n.activeExports.delete(r)})},hasInProgressExports:()=>Array.from(t().activeExports.values()).some(r=>["pending","processing","chunking","compacting"].includes(r.status))}}))),OU=()=>IC(e=>e.actions),nCe=()=>IC(e=>e.activeExports),rCe=()=>IC(e=>Array.from(e.activeExports.values()).filter(n=>["pending","processing","chunking","compacting"].includes(n.status)).length);async function FU(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 tp(o.message||o.error||"Failed to create export",r.status,o)}return s}async function sCe(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 tp("Failed to fetch exports",s.status);return s.json()}async function oCe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}`,{headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new tp("Failed to fetch export status",r.status);return r.json()}async function iCe(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 tp("Failed to get download URL",r.status)}async function aCe(e,t,n){const r=await fetch(`${e}/v1/exports/${n}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw new tp("Failed to cancel export",r.status)}class tp extends Error{constructor(t,n,r){super(t),this.status=n,this.details=r,this.name="ExportError"}}function lCe(e){return["pending","processing","chunking","compacting"].includes(e)}function cCe(e){return["completed","failed","cancelled"].includes(e)}function uCe(e){return!e||e===0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}const O5={searchQuery:"",debouncedSearchQuery:"",selectedUsers:[],usersToRemove:[],usersToUpdate:[],selectedGroups:[],groupsToRemove:[],groupsToUpdate:[],selectedTab:"org",currentContext:"org-tab",currentMode:null,orgWideRole:"VIEWER",allTenantsRole:"VIEWER",tenantWideRole:"VIEWER",groupWideRole:"VIEWER",selectedTenant:"",message:""},Fs=oa()(Im(e=>({...O5,actions:{setSearchQuery:t=>{e(n=>{n.searchQuery=t})},setDebouncedSearchQuery:t=>{e(n=>{n.debouncedSearchQuery=t})},setSelectedUsers:t=>{e(n=>{n.selectedUsers=t})},addSelectedUser:t=>{e(n=>{n.selectedUsers.some(s=>s.id===t.id)||n.selectedUsers.push(t)})},removeSelectedUser:t=>{e(n=>{n.selectedUsers=n.selectedUsers.filter(r=>r.id!==t)})},updateSelectedUserRole:(t,n)=>{e(r=>{const s=r.selectedUsers.find(o=>o.id===t);s&&(s.role=n)})},setUsersToRemove:t=>{e(n=>{n.usersToRemove=t})},addUserToRemove:t=>{e(n=>{n.usersToRemove.includes(t)||n.usersToRemove.push(t)})},removeUserFromRemove:t=>{e(n=>{n.usersToRemove=n.usersToRemove.filter(r=>r!==t)})},setUsersToUpdate:t=>{e(n=>{n.usersToUpdate=t})},addUserToUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t.id),n.usersToUpdate.push(t)})},removeUserFromUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t)})},setSelectedTenant:t=>{e(n=>{n.selectedTenant=t})},setSelectedTab:t=>{e(n=>{n.selectedTab=t})},setCurrentContext:t=>{e(n=>{n.currentContext=t})},setCurrentMode:t=>{e(n=>{n.currentMode=t})},setOrgWideRole:t=>{e(n=>{n.orgWideRole=t})},setAllTenantsRole:t=>{e(n=>{n.allTenantsRole=t})},setTenantWideRole:t=>{e(n=>{n.tenantWideRole=t})},setGroupWideRole:t=>{e(n=>{n.groupWideRole=t})},setSelectedGroups:t=>{e(n=>{n.selectedGroups=t})},addSelectedGroup:t=>{e(n=>{n.selectedGroups.some(s=>s.id===t.id)||n.selectedGroups.push(t)})},removeSelectedGroup:t=>{e(n=>{n.selectedGroups=n.selectedGroups.filter(r=>r.id!==t)})},updateSelectedGroupRole:(t,n)=>{e(r=>{const s=r.selectedGroups.find(o=>o.id===t);s&&(s.role=n)})},setGroupsToRemove:t=>{e(n=>{n.groupsToRemove=t})},addGroupToRemove:t=>{e(n=>{n.groupsToRemove.includes(t)||n.groupsToRemove.push(t)})},removeGroupFromRemove:t=>{e(n=>{n.groupsToRemove=n.groupsToRemove.filter(r=>r!==t)})},setGroupsToUpdate:t=>{e(n=>{n.groupsToUpdate=t})},addGroupToUpdate:t=>{e(n=>{const r=n.groupsToUpdate.findIndex(s=>s.id===t.id);r!==-1?n.groupsToUpdate[r]=t:n.groupsToUpdate.push(t)})},removeGroupFromUpdate:t=>{e(n=>{n.groupsToUpdate=n.groupsToUpdate.filter(r=>r.id!==t)})},setMessage:t=>{e(n=>{n.message=t})},validateShareData:t=>fV(t),resetShareState:()=>{e(t=>{Object.assign(t,O5)})},resetUserSelections:()=>{e(t=>{t.selectedUsers=[],t.usersToRemove=[],t.usersToUpdate=[]})},resetGroupSelections:()=>{e(t=>{t.selectedGroups=[],t.groupsToRemove=[],t.groupsToUpdate=[]})}}}))),dCe=()=>Fs(e=>e.searchQuery),qx=()=>Fs(e=>e.selectedUsers),np=()=>Fs(e=>e.usersToRemove),Yx=()=>Fs(e=>e.usersToUpdate),Gx=()=>Fs(e=>e.selectedTenant),_D=()=>Fs(e=>e.selectedTab),$U=()=>Fs(e=>e.currentContext),ku=()=>Fs(e=>e.currentMode),TD=()=>Fs(e=>e.orgWideRole),MD=()=>Fs(e=>e.allTenantsRole),RC=()=>Fs(e=>e.tenantWideRole),LU=()=>Fs(e=>e.groupWideRole),Kx=()=>Fs(e=>e.selectedGroups),Zx=()=>Fs(e=>e.groupsToRemove),Xx=()=>Fs(e=>e.groupsToUpdate),rp=()=>Fs(e=>e.actions),zU=()=>{const e=dCe(),t=Ih(e,300),n=rp();return C.useEffect(()=>{n.setDebouncedSearchQuery(t)},[t,n]),{searchQuery:e,debouncedSearchQuery:t,setSearchQuery:n.setSearchQuery}};function fCe({currentUser:e,currentShare:t,isSharing:n,onUpdateAccess:r,allUsersToUpdate:s=null,allUsersToRemove:o=!1,isUpdating:i=!1,isRemoving:a=!1}){const l=ku(),u=$o().filter(y=>y.value==="VIEWER"||y.value==="EDITOR"||y.value==="CONTRIBUTOR"),d=t.role!=="NONE"?t.role:"NONE",f=s?s.newRole:d,h=t.role!=="NONE"&&!o&&(!s||s.newRole===d),m=s!==null&&s.newRole!==d,p=o,g=d==="NONE"||!d,b=y=>{switch(y){case"VIEWER":return c.jsx(tu,{className:"h-4 w-4"});case"EDITOR":return c.jsx(Y1,{className:"h-4 w-4"});case"CONTRIBUTOR":return c.jsx(nie,{className:"h-4 w-4"});default:return c.jsx(tu,{className:"h-4 w-4"})}},x=y=>{r(d,y)};return c.jsx("div",{className:"space-y-4",children:c.jsxs(Uo,{className:X("pb-6",m&&!p&&!g?"border-orange-300 bg-orange-50":h?"border-green-300 bg-green-50":p||g?"border-destructive bg-destructive/10":""),children:[c.jsxs(Zi,{children:[c.jsxs(Xi,{className:"flex items-center gap-2 text-base",children:[c.jsx(Pr,{className:"h-5 w-5"}),"Share with All"," ",l==="allOrgUsers"?"Organization":l==="allTenantUsers"?"Tenant":l==="specificOrgUsers"?"Org":"Tenant"," ","Users",h&&c.jsx(Ve,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),m&&c.jsx(Ve,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(p||g)&&c.jsx(Ve,{variant:"destructive",className:"ml-2",children:"No Access"})]}),c.jsx(Qz,{children:p||g?"No access for all users.":"This will share the dashboard with all users in your "+((e==null?void 0:e.type)==="organization"?"organization":"tenant")+". Select an access level below."})]}),c.jsx(Qi,{className:"space-y-4",children:c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("h4",{className:"text-sm font-medium",children:"Select Access Level:"}),c.jsxs(Wm,{children:[c.jsx(qm,{asChild:!0,children:c.jsx(se,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:c.jsx(nr,{className:"h-3 w-3"})})}),c.jsx(Mf,{className:"w-80",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"text-sm font-medium",children:"Share with All Users"}),c.jsxs("p",{className:"text-sm text-muted-foreground",children:["This action will share the dashboard with all users in your"," ",(e==null?void 0:e.type)==="organization"?"organization":"tenant",". Users will receive the selected access level."]}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.jsxs("p",{children:[c.jsx("strong",{children:"Viewer:"})," Can view the dashboard"]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Editor:"})," Can view and edit the dashboard"]}),c.jsxs("p",{children:[c.jsx("strong",{children:"Contributor:"})," Can view, edit, and share the dashboard"]}),c.jsxs("p",{children:[c.jsx("strong",{children:"None:"})," No access for all users"]})]})]})})]})]}),c.jsx("div",{className:"grid grid-cols-2 gap-3",children:u.map(y=>c.jsxs(se,{variant:f===y.value?"default":"outline",className:"h-auto flex-col items-start gap-2 p-3",onClick:()=>x(y.value),disabled:n||i||a,children:[c.jsxs("div",{className:"flex items-center gap-2",children:[b(y.value),c.jsx("span",{className:"font-medium",children:y.label})]}),c.jsx("p",{className:"text-left text-xs text-muted-foreground",children:y.description})]},y.value))})]})})]})})}function BU({currentUser:e,currentShare:t,isSharing:n,isUpdating:r,isRemoving:s,onUpdateAccess:o,onRemoveAccess:i,allUsersToUpdate:a,allUsersToRemove:l}){const u=g=>g==="OWNER"?"CONTRIBUTOR":g,f=t?{role:u(t.role)}:{role:"NONE"},h=a?{currentRole:u(a.currentRole),newRole:u(a.newRole)}:null,m=(g,b)=>{o(g,b)},p=()=>{i()};return c.jsx(fCe,{currentUser:e,currentShare:f,isSharing:n,isUpdating:r,isRemoving:s,onUpdateAccess:m,onRemoveAccess:p,allUsersToUpdate:h,allUsersToRemove:l})}function hCe(e){const t=mCe(e),n=D.forwardRef((r,s)=>{const{children:o,...i}=r,a=D.Children.toArray(o),l=a.find(gCe);if(l){const u=l.props.children,d=a.map(f=>f===l?D.Children.count(u)>1?D.Children.only(null):D.isValidElement(u)?u.props.children:null:f);return c.jsx(t,{...i,ref:s,children:D.isValidElement(u)?D.cloneElement(u,void 0,d):null})}return c.jsx(t,{...i,ref:s,children:o})});return n.displayName=`${e}.Slot`,n}function mCe(e){const t=D.forwardRef((n,r)=>{const{children:s,...o}=n;if(D.isValidElement(s)){const i=xCe(s),a=bCe(o,s.props);return s.type!==D.Fragment&&(a.ref=r?to(r,i):i),D.cloneElement(s,a)}return D.Children.count(s)>1?D.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var pCe=Symbol("radix.slottable");function gCe(e){return D.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===pCe}function bCe(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...a)=>{const l=o(...a);return s(...a),l}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function xCe(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var AC="Popover",[VU]=Lr(AC,[Ka]),Qx=Ka(),[yCe,Eu]=VU(AC),HU=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:s,onOpenChange:o,modal:i=!1}=e,a=Qx(t),l=D.useRef(null),[u,d]=D.useState(!1),[f,h]=ss({prop:r,defaultProp:s??!1,onChange:o,caller:AC});return c.jsx(zm,{...a,children:c.jsx(yCe,{scope:t,contentId:xr(),triggerRef:l,open:f,onOpenChange:h,onOpenToggle:D.useCallback(()=>h(m=>!m),[h]),hasCustomAnchor:u,onCustomAnchorAdd:D.useCallback(()=>d(!0),[]),onCustomAnchorRemove:D.useCallback(()=>d(!1),[]),modal:i,children:n})})};HU.displayName=AC;var UU="PopoverAnchor",vCe=D.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Eu(UU,n),o=Qx(n),{onCustomAnchorAdd:i,onCustomAnchorRemove:a}=s;return D.useEffect(()=>(i(),()=>a()),[i,a]),c.jsx(Bm,{...o,...r,ref:t})});vCe.displayName=UU;var WU="PopoverTrigger",qU=D.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Eu(WU,n),o=Qx(n),i=ut(t,s.triggerRef),a=c.jsx(Ze.button,{type:"button","aria-haspopup":"dialog","aria-expanded":s.open,"aria-controls":s.contentId,"data-state":QU(s.open),...r,ref:i,onClick:Ie(e.onClick,s.onOpenToggle)});return s.hasCustomAnchor?a:c.jsx(Bm,{asChild:!0,...o,children:a})});qU.displayName=WU;var DD="PopoverPortal",[wCe,CCe]=VU(DD,{forceMount:void 0}),YU=e=>{const{__scopePopover:t,forceMount:n,children:r,container:s}=e,o=Eu(DD,t);return c.jsx(wCe,{scope:t,forceMount:n,children:c.jsx(vr,{present:n||o.open,children:c.jsx(yf,{asChild:!0,container:s,children:r})})})};YU.displayName=DD;var bm="PopoverContent",GU=D.forwardRef((e,t)=>{const n=CCe(bm,e.__scopePopover),{forceMount:r=n.forceMount,...s}=e,o=Eu(bm,e.__scopePopover);return c.jsx(vr,{present:r||o.open,children:o.modal?c.jsx(jCe,{...s,ref:t}):c.jsx(NCe,{...s,ref:t})})});GU.displayName=bm;var SCe=hCe("PopoverContent.RemoveScroll"),jCe=D.forwardRef((e,t)=>{const n=Eu(bm,e.__scopePopover),r=D.useRef(null),s=ut(t,r),o=D.useRef(!1);return D.useEffect(()=>{const i=r.current;if(i)return J1(i)},[]),c.jsx(Rx,{as:SCe,allowPinchZoom:!0,children:c.jsx(KU,{...e,ref:s,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ie(e.onCloseAutoFocus,i=>{var a;i.preventDefault(),o.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:Ie(e.onPointerDownOutside,i=>{const a=i.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,u=a.button===2||l;o.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:Ie(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1})})})}),NCe=D.forwardRef((e,t)=>{const n=Eu(bm,e.__scopePopover),r=D.useRef(!1),s=D.useRef(!1);return c.jsx(KU,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var i,a;(i=e.onCloseAutoFocus)==null||i.call(e,o),o.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),o.preventDefault()),r.current=!1,s.current=!1},onInteractOutside:o=>{var l,u;(l=e.onInteractOutside)==null||l.call(e,o),o.defaultPrevented||(r.current=!0,o.detail.originalEvent.type==="pointerdown"&&(s.current=!0));const i=o.target;((u=n.triggerRef.current)==null?void 0:u.contains(i))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&s.current&&o.preventDefault()}})}),KU=D.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:i,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onInteractOutside:d,...f}=e,h=Eu(bm,n),m=Qx(n);return G1(),c.jsx(Fm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:s,onUnmountAutoFocus:o,children:c.jsx(xf,{asChild:!0,disableOutsidePointerEvents:i,onInteractOutside:d,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:u,onDismiss:()=>h.onOpenChange(!1),children:c.jsx(Mx,{"data-state":QU(h.open),role:"dialog",id:h.contentId,...m,...f,ref:t,style:{...f.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),ZU="PopoverClose",kCe=D.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Eu(ZU,n);return c.jsx(Ze.button,{type:"button",...r,ref:t,onClick:Ie(e.onClick,()=>s.onOpenChange(!1))})});kCe.displayName=ZU;var ECe="PopoverArrow",XU=D.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,s=Qx(n);return c.jsx(Dx,{...s,...r,ref:t})});XU.displayName=ECe;function QU(e){return e?"open":"closed"}var ID=HU,RD=qU,_Ce=YU,sp=GU,TCe=XU,F5=1,MCe=.9,DCe=.8,ICe=.17,uN=.1,dN=.999,RCe=.9999,ACe=.99,PCe=/[\\\/_+.#"@\[\(\{&]/,OCe=/[\\\/_+.#"@\[\(\{&]/g,FCe=/[\s-]/,JU=/[\s-]/g;function PE(e,t,n,r,s,o,i){if(o===t.length)return s===e.length?F5:ACe;var a=`${s},${o}`;if(i[a]!==void 0)return i[a];for(var l=r.charAt(o),u=n.indexOf(l,s),d=0,f,h,m,p;u>=0;)f=PE(e,t,n,r,u+1,o+1,i),f>d&&(u===s?f*=F5:PCe.test(e.charAt(u-1))?(f*=DCe,m=e.slice(s,u-1).match(OCe),m&&s>0&&(f*=Math.pow(dN,m.length))):FCe.test(e.charAt(u-1))?(f*=MCe,p=e.slice(s,u-1).match(JU),p&&s>0&&(f*=Math.pow(dN,p.length))):(f*=ICe,s>0&&(f*=Math.pow(dN,u-s))),e.charAt(u)!==t.charAt(o)&&(f*=RCe)),(f<uN&&n.charAt(u-1)===r.charAt(o+1)||r.charAt(o+1)===r.charAt(o)&&n.charAt(u-1)!==r.charAt(o))&&(h=PE(e,t,n,r,u+1,o+2,i),h*uN>f&&(f=h*uN)),f>d&&(d=f),u=n.indexOf(l,u+1);return i[a]=d,d}function $5(e){return e.toLowerCase().replace(JU," ")}function $Ce(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,PE(e,t,$5(e),$5(t),0,0,{})}var Up='[cmdk-group=""]',fN='[cmdk-group-items=""]',LCe='[cmdk-group-heading=""]',eW='[cmdk-item=""]',L5=`${eW}:not([aria-disabled="true"])`,OE="cmdk-item-select",sh="data-value",zCe=(e,t,n)=>$Ce(e,t,n),tW=D.createContext(void 0),Jx=()=>D.useContext(tW),nW=D.createContext(void 0),AD=()=>D.useContext(nW),rW=D.createContext(void 0),sW=D.forwardRef((e,t)=>{let n=oh(()=>{var F,A;return{search:"",value:(A=(F=e.value)!=null?F:e.defaultValue)!=null?A:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=oh(()=>new Set),s=oh(()=>new Map),o=oh(()=>new Map),i=oh(()=>new Set),a=oW(e),{label:l,children:u,value:d,onValueChange:f,filter:h,shouldFilter:m,loop:p,disablePointerSelection:g=!1,vimBindings:b=!0,...x}=e,y=xr(),v=xr(),w=xr(),j=D.useRef(null),S=XCe();sf(()=>{if(d!==void 0){let F=d.trim();n.current.value=F,N.emit()}},[d]),sf(()=>{S(6,P)},[]);let N=D.useMemo(()=>({subscribe:F=>(i.current.add(F),()=>i.current.delete(F)),snapshot:()=>n.current,setState:(F,A,H)=>{var B,Y,q,U;if(!Object.is(n.current[F],A)){if(n.current[F]=A,F==="search")T(),k(),S(1,M);else if(F==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let G=document.getElementById(w);G?G.focus():(B=document.getElementById(y))==null||B.focus()}if(S(7,()=>{var G;n.current.selectedItemId=(G=O())==null?void 0:G.id,N.emit()}),H||S(5,P),((Y=a.current)==null?void 0:Y.value)!==void 0){let G=A??"";(U=(q=a.current).onValueChange)==null||U.call(q,G);return}}N.emit()}},emit:()=>{i.current.forEach(F=>F())}}),[]),E=D.useMemo(()=>({value:(F,A,H)=>{var B;A!==((B=o.current.get(F))==null?void 0:B.value)&&(o.current.set(F,{value:A,keywords:H}),n.current.filtered.items.set(F,_(A,H)),S(2,()=>{k(),N.emit()}))},item:(F,A)=>(r.current.add(F),A&&(s.current.has(A)?s.current.get(A).add(F):s.current.set(A,new Set([F]))),S(3,()=>{T(),k(),n.current.value||M(),N.emit()}),()=>{o.current.delete(F),r.current.delete(F),n.current.filtered.items.delete(F);let H=O();S(4,()=>{T(),(H==null?void 0:H.getAttribute("id"))===F&&M(),N.emit()})}),group:F=>(s.current.has(F)||s.current.set(F,new Set),()=>{o.current.delete(F),s.current.delete(F)}),filter:()=>a.current.shouldFilter,label:l||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:y,inputId:w,labelId:v,listInnerRef:j}),[]);function _(F,A){var H,B;let Y=(B=(H=a.current)==null?void 0:H.filter)!=null?B:zCe;return F?Y(F,n.current.search,A):0}function k(){if(!n.current.search||a.current.shouldFilter===!1)return;let F=n.current.filtered.items,A=[];n.current.filtered.groups.forEach(B=>{let Y=s.current.get(B),q=0;Y.forEach(U=>{let G=F.get(U);q=Math.max(G,q)}),A.push([B,q])});let H=j.current;I().sort((B,Y)=>{var q,U;let G=B.getAttribute("id"),Z=Y.getAttribute("id");return((q=F.get(Z))!=null?q:0)-((U=F.get(G))!=null?U:0)}).forEach(B=>{let Y=B.closest(fN);Y?Y.appendChild(B.parentElement===Y?B:B.closest(`${fN} > *`)):H.appendChild(B.parentElement===H?B:B.closest(`${fN} > *`))}),A.sort((B,Y)=>Y[1]-B[1]).forEach(B=>{var Y;let q=(Y=j.current)==null?void 0:Y.querySelector(`${Up}[${sh}="${encodeURIComponent(B[0])}"]`);q==null||q.parentElement.appendChild(q)})}function M(){let F=I().find(H=>H.getAttribute("aria-disabled")!=="true"),A=F==null?void 0:F.getAttribute(sh);N.setState("value",A||void 0)}function T(){var F,A,H,B;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let Y=0;for(let q of r.current){let U=(A=(F=o.current.get(q))==null?void 0:F.value)!=null?A:"",G=(B=(H=o.current.get(q))==null?void 0:H.keywords)!=null?B:[],Z=_(U,G);n.current.filtered.items.set(q,Z),Z>0&&Y++}for(let[q,U]of s.current)for(let G of U)if(n.current.filtered.items.get(G)>0){n.current.filtered.groups.add(q);break}n.current.filtered.count=Y}function P(){var F,A,H;let B=O();B&&(((F=B.parentElement)==null?void 0:F.firstChild)===B&&((H=(A=B.closest(Up))==null?void 0:A.querySelector(LCe))==null||H.scrollIntoView({block:"nearest"})),B.scrollIntoView({block:"nearest"}))}function O(){var F;return(F=j.current)==null?void 0:F.querySelector(`${eW}[aria-selected="true"]`)}function I(){var F;return Array.from(((F=j.current)==null?void 0:F.querySelectorAll(L5))||[])}function $(F){let A=I()[F];A&&N.setState("value",A.getAttribute(sh))}function V(F){var A;let H=O(),B=I(),Y=B.findIndex(U=>U===H),q=B[Y+F];(A=a.current)!=null&&A.loop&&(q=Y+F<0?B[B.length-1]:Y+F===B.length?B[0]:B[Y+F]),q&&N.setState("value",q.getAttribute(sh))}function W(F){let A=O(),H=A==null?void 0:A.closest(Up),B;for(;H&&!B;)H=F>0?KCe(H,Up):ZCe(H,Up),B=H==null?void 0:H.querySelector(L5);B?N.setState("value",B.getAttribute(sh)):V(F)}let L=()=>$(I().length-1),R=F=>{F.preventDefault(),F.metaKey?L():F.altKey?W(1):V(1)},z=F=>{F.preventDefault(),F.metaKey?$(0):F.altKey?W(-1):V(-1)};return D.createElement(Ze.div,{ref:t,tabIndex:-1,...x,"cmdk-root":"",onKeyDown:F=>{var A;(A=x.onKeyDown)==null||A.call(x,F);let H=F.nativeEvent.isComposing||F.keyCode===229;if(!(F.defaultPrevented||H))switch(F.key){case"n":case"j":{b&&F.ctrlKey&&R(F);break}case"ArrowDown":{R(F);break}case"p":case"k":{b&&F.ctrlKey&&z(F);break}case"ArrowUp":{z(F);break}case"Home":{F.preventDefault(),$(0);break}case"End":{F.preventDefault(),L();break}case"Enter":{F.preventDefault();let B=O();if(B){let Y=new Event(OE);B.dispatchEvent(Y)}}}}},D.createElement("label",{"cmdk-label":"",htmlFor:E.inputId,id:E.labelId,style:JCe},l),PC(e,F=>D.createElement(nW.Provider,{value:N},D.createElement(tW.Provider,{value:E},F))))}),BCe=D.forwardRef((e,t)=>{var n,r;let s=xr(),o=D.useRef(null),i=D.useContext(rW),a=Jx(),l=oW(e),u=(r=(n=l.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;sf(()=>{if(!u)return a.item(s,i==null?void 0:i.id)},[u]);let d=iW(s,o,[e.value,e.children,o],e.keywords),f=AD(),h=uu(S=>S.value&&S.value===d.current),m=uu(S=>u||a.filter()===!1?!0:S.search?S.filtered.items.get(s)>0:!0);D.useEffect(()=>{let S=o.current;if(!(!S||e.disabled))return S.addEventListener(OE,p),()=>S.removeEventListener(OE,p)},[m,e.onSelect,e.disabled]);function p(){var S,N;g(),(N=(S=l.current).onSelect)==null||N.call(S,d.current)}function g(){f.setState("value",d.current,!0)}if(!m)return null;let{disabled:b,value:x,onSelect:y,forceMount:v,keywords:w,...j}=e;return D.createElement(Ze.div,{ref:to(o,t),...j,id:s,"cmdk-item":"",role:"option","aria-disabled":!!b,"aria-selected":!!h,"data-disabled":!!b,"data-selected":!!h,onPointerMove:b||a.getDisablePointerSelection()?void 0:g,onClick:b?void 0:p},e.children)}),VCe=D.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:s,...o}=e,i=xr(),a=D.useRef(null),l=D.useRef(null),u=xr(),d=Jx(),f=uu(m=>s||d.filter()===!1?!0:m.search?m.filtered.groups.has(i):!0);sf(()=>d.group(i),[]),iW(i,a,[e.value,e.heading,l]);let h=D.useMemo(()=>({id:i,forceMount:s}),[s]);return D.createElement(Ze.div,{ref:to(a,t),...o,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&D.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:u},n),PC(e,m=>D.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?u:void 0},D.createElement(rW.Provider,{value:h},m))))}),HCe=D.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,s=D.useRef(null),o=uu(i=>!i.search);return!n&&!o?null:D.createElement(Ze.div,{ref:to(s,t),...r,"cmdk-separator":"",role:"separator"})}),UCe=D.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,s=e.value!=null,o=AD(),i=uu(u=>u.search),a=uu(u=>u.selectedItemId),l=Jx();return D.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),D.createElement(Ze.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":a,id:l.inputId,type:"text",value:s?e.value:i,onChange:u=>{s||o.setState("search",u.target.value),n==null||n(u.target.value)}})}),WCe=D.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...s}=e,o=D.useRef(null),i=D.useRef(null),a=uu(u=>u.selectedItemId),l=Jx();return D.useEffect(()=>{if(i.current&&o.current){let u=i.current,d=o.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=u.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return h.observe(u),()=>{cancelAnimationFrame(f),h.unobserve(u)}}},[]),D.createElement(Ze.div,{ref:to(o,t),...s,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:l.listId},PC(e,u=>D.createElement("div",{ref:to(i,l.listInnerRef),"cmdk-list-sizer":""},u)))}),qCe=D.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:s,contentClassName:o,container:i,...a}=e;return D.createElement(RM,{open:n,onOpenChange:r},D.createElement(AM,{container:i},D.createElement(lC,{"cmdk-overlay":"",className:s}),D.createElement(cC,{"aria-label":e.label,"cmdk-dialog":"",className:o},D.createElement(sW,{ref:t,...a}))))}),YCe=D.forwardRef((e,t)=>uu(n=>n.filtered.count===0)?D.createElement(Ze.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),GCe=D.forwardRef((e,t)=>{let{progress:n,children:r,label:s="Loading...",...o}=e;return D.createElement(Ze.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":s},PC(e,i=>D.createElement("div",{"aria-hidden":!0},i)))}),$s=Object.assign(sW,{List:WCe,Item:BCe,Input:UCe,Group:VCe,Separator:HCe,Dialog:qCe,Empty:YCe,Loading:GCe});function KCe(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function ZCe(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function oW(e){let t=D.useRef(e);return sf(()=>{t.current=e}),t}var sf=typeof window>"u"?D.useEffect:D.useLayoutEffect;function oh(e){let t=D.useRef();return t.current===void 0&&(t.current=e()),t}function uu(e){let t=AD(),n=()=>e(t.snapshot());return D.useSyncExternalStore(t.subscribe,n,n)}function iW(e,t,n,r=[]){let s=D.useRef(),o=Jx();return sf(()=>{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}})(),l=r.map(u=>u.trim());o.value(e,a,l),(i=t.current)==null||i.setAttribute(sh,a),s.current=a}),s}var XCe=()=>{let[e,t]=D.useState(),n=oh(()=>new Map);return sf(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,s)=>{n.current.set(r,s),t({})}};function QCe(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function PC({asChild:e,children:t},n){return e&&D.isValidElement(t)?D.cloneElement(QCe(t),{ref:t.ref},n(t.props.children)):n(t)}var JCe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const op=D.forwardRef(({className:e,...t},n)=>c.jsx($s,{ref:n,className:X("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));op.displayName=$s.displayName;const ey=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[c.jsx(Ko,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx($s.Input,{ref:n,className:X("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})]}));ey.displayName=$s.Input.displayName;const ip=D.forwardRef(({className:e,...t},n)=>c.jsx($s.List,{ref:n,className:X("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));ip.displayName=$s.List.displayName;const ap=D.forwardRef((e,t)=>c.jsx($s.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));ap.displayName=$s.Empty.displayName;const lp=D.forwardRef(({className:e,...t},n)=>c.jsx($s.Group,{ref:n,className:X("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}));lp.displayName=$s.Group.displayName;const aW=D.forwardRef(({className:e,...t},n)=>c.jsx($s.Separator,{ref:n,className:X("-mx-1 h-px bg-border",e),...t}));aW.displayName=$s.Separator.displayName;const cp=D.forwardRef(({className:e,...t},n)=>c.jsx($s.Item,{ref:n,className:X("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}));cp.displayName=$s.Item.displayName;var OC="Checkbox",[eSe]=Lr(OC),[tSe,PD]=eSe(OC);function nSe(e){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:s,disabled:o,form:i,name:a,onCheckedChange:l,required:u,value:d="on",internal_do_not_use_render:f}=e,[h,m]=ss({prop:n,defaultProp:s??!1,onChange:l,caller:OC}),[p,g]=D.useState(null),[b,x]=D.useState(null),y=D.useRef(!1),v=p?!!i||!!p.closest("form"):!0,w={checked:h,disabled:o,setChecked:m,control:p,setControl:g,name:a,form:i,value:d,hasConsumerStoppedPropagationRef:y,required:u,defaultChecked:Xc(s)?!1:s,isFormControl:v,bubbleInput:b,setBubbleInput:x};return c.jsx(tSe,{scope:t,...w,children:rSe(f)?f(w):r})}var lW="CheckboxTrigger",cW=D.forwardRef(({__scopeCheckbox:e,onKeyDown:t,onClick:n,...r},s)=>{const{control:o,value:i,disabled:a,checked:l,required:u,setControl:d,setChecked:f,hasConsumerStoppedPropagationRef:h,isFormControl:m,bubbleInput:p}=PD(lW,e),g=ut(s,d),b=D.useRef(l);return D.useEffect(()=>{const x=o==null?void 0:o.form;if(x){const y=()=>f(b.current);return x.addEventListener("reset",y),()=>x.removeEventListener("reset",y)}},[o,f]),c.jsx(Ze.button,{type:"button",role:"checkbox","aria-checked":Xc(l)?"mixed":l,"aria-required":u,"data-state":mW(l),"data-disabled":a?"":void 0,disabled:a,value:i,...r,ref:g,onKeyDown:Ie(t,x=>{x.key==="Enter"&&x.preventDefault()}),onClick:Ie(n,x=>{f(y=>Xc(y)?!0:!y),p&&m&&(h.current=x.isPropagationStopped(),h.current||x.stopPropagation())})})});cW.displayName=lW;var OD=D.forwardRef((e,t)=>{const{__scopeCheckbox:n,name:r,checked:s,defaultChecked:o,required:i,disabled:a,value:l,onCheckedChange:u,form:d,...f}=e;return c.jsx(nSe,{__scopeCheckbox:n,checked:s,defaultChecked:o,disabled:a,required:i,onCheckedChange:u,name:r,form:d,value:l,internal_do_not_use_render:({isFormControl:h})=>c.jsxs(c.Fragment,{children:[c.jsx(cW,{...f,ref:t,__scopeCheckbox:n}),h&&c.jsx(hW,{__scopeCheckbox:n})]})})});OD.displayName=OC;var uW="CheckboxIndicator",dW=D.forwardRef((e,t)=>{const{__scopeCheckbox:n,forceMount:r,...s}=e,o=PD(uW,n);return c.jsx(vr,{present:r||Xc(o.checked)||o.checked===!0,children:c.jsx(Ze.span,{"data-state":mW(o.checked),"data-disabled":o.disabled?"":void 0,...s,ref:t,style:{pointerEvents:"none",...e.style}})})});dW.displayName=uW;var fW="CheckboxBubbleInput",hW=D.forwardRef(({__scopeCheckbox:e,...t},n)=>{const{control:r,hasConsumerStoppedPropagationRef:s,checked:o,defaultChecked:i,required:a,disabled:l,name:u,value:d,form:f,bubbleInput:h,setBubbleInput:m}=PD(fW,e),p=ut(n,m),g=$x(o),b=Tx(r);D.useEffect(()=>{const y=h;if(!y)return;const v=window.HTMLInputElement.prototype,j=Object.getOwnPropertyDescriptor(v,"checked").set,S=!s.current;if(g!==o&&j){const N=new Event("click",{bubbles:S});y.indeterminate=Xc(o),j.call(y,Xc(o)?!1:o),y.dispatchEvent(N)}},[h,g,o,s]);const x=D.useRef(Xc(o)?!1:o);return c.jsx(Ze.input,{type:"checkbox","aria-hidden":!0,defaultChecked:i??x.current,required:a,disabled:l,name:u,value:d,form:f,...t,tabIndex:-1,ref:p,style:{...t.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});hW.displayName=fW;function rSe(e){return typeof e=="function"}function Xc(e){return e==="indeterminate"}function mW(e){return Xc(e)?"indeterminate":e?"checked":"unchecked"}const cn=D.forwardRef(({className:e,...t},n)=>c.jsx(OD,{ref:n,className:X("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",e),...t,children:c.jsx(dW,{className:X("flex items-center justify-center text-current"),children:c.jsx(Ar,{className:"h-4 w-4"})})}));cn.displayName=OD.displayName;function pW({users:e,selectedUsers:t,existingUserIds:n,isLoading:r,onUserToggle:s,onSearchChange:o,currentUserId:i,placeholder:a="Search and select users..."}){const[l,u]=C.useState(!1),[d,f]=C.useState(""),h=b=>{f(b),o==null||o(b)},m=C.useMemo(()=>e.filter(b=>!(i&&b.id===i||n.includes(b.id))),[e,i,n]),p=b=>t.some(x=>x.id===b),g=()=>{const b=t.length;return b===0?a:`${b} user${b>1?"s":""} selected`};return c.jsxs(ID,{open:l,onOpenChange:u,children:[c.jsx(RD,{asChild:!0,children:c.jsxs(se,{variant:"outline",role:"combobox","aria-expanded":l,className:"w-full justify-between font-normal",children:[c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Ko,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:X(t.length===0&&"text-muted-foreground"),children:g()})]}),c.jsx(VT,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),c.jsxs(sp,{className:"z-[52] mt-1 rounded-md border bg-popover p-0 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",align:"start",sideOffset:4,style:{width:"var(--radix-popover-trigger-width)"},onOpenAutoFocus:b=>b.preventDefault(),children:[c.jsxs(op,{shouldFilter:!1,children:[c.jsx(ey,{placeholder:"Search by name, email, or department...",value:d,onValueChange:h}),c.jsx(ip,{className:"max-h-[250px] overflow-auto overscroll-contain",children:r?c.jsxs("div",{className:"flex items-center justify-center py-6",children:[c.jsx(xn,{className:"h-4 w-4 animate-spin"}),c.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading users..."})]}):m.length===0?c.jsx(ap,{children:d?"No users found matching your search.":"No users available to share with."}):c.jsx(lp,{children:m.map(b=>{const x=p(b.id);return c.jsx(cp,{value:b.id,onSelect:()=>s(b.id),className:"cursor-pointer",children:c.jsxs("div",{className:"flex w-full items-center gap-3",children:[c.jsx(cn,{checked:x,className:"pointer-events-none"}),c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"truncate font-medium",children:b.name}),c.jsx(Ve,{variant:"outline",className:"text-xs",children:b.role==="POWER_USER"?"Power User":b.role==="ADMIN"?"Admin":"Viewer"})]}),c.jsx("span",{className:"truncate text-xs text-muted-foreground",children:b.email})]}),x&&c.jsx(Ar,{className:"h-4 w-4 shrink-0 text-primary"})]})},b.id)})})})]}),t.length>0&&c.jsx("div",{className:"border-t p-2",children:c.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.length," user",t.length>1?"s":""," ","selected"]})})]})]})}var FC="Collapsible",[sSe,gW]=Lr(FC),[oSe,FD]=sSe(FC),bW=D.forwardRef((e,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:s,disabled:o,onOpenChange:i,...a}=e,[l,u]=ss({prop:r,defaultProp:s??!1,onChange:i,caller:FC});return c.jsx(oSe,{scope:n,disabled:o,contentId:xr(),open:l,onOpenToggle:D.useCallback(()=>u(d=>!d),[u]),children:c.jsx(Ze.div,{"data-state":BD(l),"data-disabled":o?"":void 0,...a,ref:t})})});bW.displayName=FC;var xW="CollapsibleTrigger",$D=D.forwardRef((e,t)=>{const{__scopeCollapsible:n,...r}=e,s=FD(xW,n);return c.jsx(Ze.button,{type:"button","aria-controls":s.contentId,"aria-expanded":s.open||!1,"data-state":BD(s.open),"data-disabled":s.disabled?"":void 0,disabled:s.disabled,...r,ref:t,onClick:Ie(e.onClick,s.onOpenToggle)})});$D.displayName=xW;var LD="CollapsibleContent",zD=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=FD(LD,e.__scopeCollapsible);return c.jsx(vr,{present:n||s.open,children:({present:o})=>c.jsx(iSe,{...r,ref:t,present:o})})});zD.displayName=LD;var iSe=D.forwardRef((e,t)=>{const{__scopeCollapsible:n,present:r,children:s,...o}=e,i=FD(LD,n),[a,l]=D.useState(r),u=D.useRef(null),d=ut(t,u),f=D.useRef(0),h=f.current,m=D.useRef(0),p=m.current,g=i.open||a,b=D.useRef(g),x=D.useRef(void 0);return D.useEffect(()=>{const y=requestAnimationFrame(()=>b.current=!1);return()=>cancelAnimationFrame(y)},[]),Yr(()=>{const y=u.current;if(y){x.current=x.current||{transitionDuration:y.style.transitionDuration,animationName:y.style.animationName},y.style.transitionDuration="0s",y.style.animationName="none";const v=y.getBoundingClientRect();f.current=v.height,m.current=v.width,b.current||(y.style.transitionDuration=x.current.transitionDuration,y.style.animationName=x.current.animationName),l(r)}},[i.open,r]),c.jsx(Ze.div,{"data-state":BD(i.open),"data-disabled":i.disabled?"":void 0,id:i.contentId,hidden:!g,...o,ref:d,style:{"--radix-collapsible-content-height":h?`${h}px`:void 0,"--radix-collapsible-content-width":p?`${p}px`:void 0,...e.style},children:g&&s})});function BD(e){return e?"open":"closed"}var yW=bW,aSe=$D,lSe=zD;const bo=yW,xo=$D,yo=zD;function vW({existingShares:e,usersToRemove:t,usersToUpdate:n,allUsers:r,onUpdateRole:s,onRemoveAccess:o,onUndoRemove:i,onUndoUpdate:a,getRoleOptions:l,isLoading:u=!1,defaultExpanded:d=!0,userType:f="organization",selectedTenantId:h}){const[m,p]=C.useState(d),g=C.useMemo(()=>{if(!(e!=null&&e.shares))return[];if(f==="organization")return e.shares.specificOrgUsers||[];{const j=e.shares.specificTenantUsers||[];return h?j.filter(S=>S.tenantId===h):j}},[e,f,h]),b=C.useMemo(()=>g.map(j=>{const S=f==="organization"?j.orgUserId:j.tenantUserId,N=j.user,E=r.find(M=>M.id===S),_=t.includes(S),k=n.find(M=>M.id===S);return{share:j,user:N?{id:S,name:N.name||"Unknown User",email:N.email||"",role:(E==null?void 0:E.role)||"VIEWER",type:f}:null,userId:S,isMarkedForRemoval:_,updateInfo:k,displayRole:k?k.newRole:j.role}}).filter(j=>j.user),[g,r,t,n,f]),x=b.filter(j=>!j.isMarkedForRemoval).length,y=b.filter(j=>j.isMarkedForRemoval).length,v=b.filter(j=>j.updateInfo&&!j.isMarkedForRemoval).length;if(u||e===void 0)return c.jsx("div",{className:"rounded-lg border border-dashed p-4",children:c.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c.jsx(xn,{className:"h-4 w-4 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading current access..."})]})});if(g.length===0)return c.jsx("div",{className:"rounded-lg border border-dashed p-4 text-center",children:c.jsxs("p",{className:"text-sm text-muted-foreground",children:["This resource hasn't been shared with any"," ",f==="organization"?"organization":"tenant"," users yet."]})});return c.jsxs(bo,{open:m,onOpenChange:p,className:"space-y-2",children:[c.jsx(xo,{asChild:!0,children:c.jsx(se,{variant:"ghost",className:"flex w-full items-center justify-between p-2 hover:bg-muted/50",children:c.jsxs("div",{className:"flex items-center gap-2",children:[m?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx("span",{className:"text-sm font-medium",children:"Current Access"}),c.jsx(Ve,{variant:"secondary",className:"text-xs",children:x}),y>0&&c.jsxs(Ve,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:["-",y]}),v>0&&c.jsxs(Ve,{variant:"outline",className:"border-orange-200 bg-orange-50 text-xs text-orange-700",children:[v," updating"]})]})})}),c.jsx(yo,{className:"space-y-1",children:c.jsx("div",{className:"max-h-48 space-y-1 overflow-y-auto rounded-md border p-2",children:b.map(j=>w(j,l))})})]});function w({share:j,user:S,userId:N,isMarkedForRemoval:E,updateInfo:_,displayRole:k},M){if(!S)return null;const T=M(S.type);return c.jsxs("div",{className:X("flex items-center justify-between rounded-md p-2 transition-colors",E?"bg-red-50 opacity-60":_?"bg-orange-50":"hover:bg-muted/50"),children:[c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:X("truncate text-sm font-medium",E&&"line-through"),children:S.name}),c.jsx(Ve,{variant:"outline",className:"shrink-0 text-xs",children:S.role==="POWER_USER"?"Power User":S.role==="ADMIN"?"Admin":"Viewer"})]}),c.jsx("span",{className:"truncate text-xs text-muted-foreground",children:S.email})]}),c.jsx("div",{className:"flex shrink-0 items-center gap-2",children:E?c.jsxs(se,{variant:"ghost",size:"sm",onClick:()=>i(N),className:"h-7 gap-1 text-xs",children:[c.jsx(ew,{className:"h-3 w-3"}),"Undo"]}):c.jsxs(c.Fragment,{children:[c.jsx(dC,{currentRole:k,onRoleChange:P=>s(N,j.role,P),roleOptions:T,className:X(_&&"border-orange-300 bg-orange-100")}),_?c.jsx(se,{variant:"ghost",size:"sm",onClick:()=>a(N),className:"h-7 gap-1 px-2 text-xs",children:c.jsx(ew,{className:"h-3 w-3"})}):c.jsx(se,{variant:"ghost",size:"sm",onClick:()=>o(N),className:"h-7 px-2 text-destructive hover:bg-destructive/10 hover:text-destructive",children:c.jsx(ec,{className:"h-3 w-3"})})]})})]},N)}}const cSe=async(e,t,n={})=>{const r={};n.search&&(r.search=n.search),n.type&&(r.type=n.type),n.active!==void 0&&(r.active=n.active.toString()),n.tenantId&&(r.tenantId=n.tenantId),n.limit&&(r.limit=n.limit.toString()),n.offset&&(r.offset=n.offset.toString()),n.page&&(r.page=n.page.toString()),n.pageSize&&(r.pageSize=n.pageSize.toString());const s=`${e}/management/v1/unified-users`;return await rr(s,t,r)};function VD(e={}){var o,i,a;const{authToken:t,tokenProps:n}=Xe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=En({queryKey:["unified-users",e],queryFn:()=>cSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(l,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:l<2,retryDelay:l=>Math.min(1e3*2**l,3e4)});return{users:((o=s.data)==null?void 0:o.users)||[],userContext:(i=s.data)==null?void 0:i.userContext,total:((a=s.data)==null?void 0:a.total)||0,isLoading:s.isLoading,isError:s.isError,isFetching:s.isFetching,error:s.error,refetch:s.refetch}}function xm(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=Ut.DASHBOARD,userType:s,tenantId:o}=e,i=C.useMemo(()=>({search:t,active:!0,...s?{type:s}:{},...s==="tenant"&&o?{tenantId:o}:{}}),[t,s,o]),{users:a,isLoading:l,isError:u}=VD(i),d=Fde(r,n);return{allUsers:a,isLoadingUsers:l,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function uSe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var z,F;const a=_D(),l=Gx(),{setSearchQuery:u,debouncedSearchQuery:d}=zU(),f=qx(),h=np(),m=Yx(),p=ku(),g=TD(),b=rp(),[x,y]=C.useState("specific_users"),v=()=>{if(a==="org")return"organization";if(a==="tenant")return"tenant"},w=()=>{if(a==="tenant"&&l)return l},{allUsers:j,existingShares:S,isLoadingUsers:N,isLoadingShares:E}=xm({debouncedSearchQuery:d,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:v(),tenantId:w()});C.useEffect(()=>{b.setCurrentContext("org-tab"),b.setCurrentMode(x==="all_users"?"allOrgUsers":"specificOrgUsers")},[b,x]);const _=A=>{var B,Y;const H=A;if(y(H),r==null||r(H),b.setCurrentContext("org-tab"),H==="specific_users")b.setCurrentMode("specificOrgUsers");else if(H==="all_users"){b.setCurrentMode("allOrgUsers");const q=(Y=(B=S==null?void 0:S.shares)==null?void 0:B.orgUsersOnly)==null?void 0:Y[0];q&&q.role!==void 0&&b.setOrgWideRole(q.role)}},k=C.useMemo(()=>{var A;return(((A=S==null?void 0:S.shares)==null?void 0:A.specificOrgUsers)||[]).map(H=>H.orgUserId)},[S]),M=j.filter(A=>f.some(H=>H.id===A.id)),T=A=>{f.some(B=>B.id===A)?b.removeSelectedUser(A):b.addSelectedUser({id:A,role:"VIEWER"})},P=(A,H)=>{b.updateSelectedUserRole(A,H)},O=(A,H,B)=>{b.addUserToUpdate({id:A,currentRole:H,newRole:B})},I=A=>{b.addUserToRemove(A)},$=A=>{b.removeUserFromRemove(A)},V=A=>{b.removeUserFromUpdate(A)},W=(A,H)=>{b.setOrgWideRole(H)},L=()=>{b.setOrgWideRole((R==null?void 0:R.role)||"NONE")},R=(F=(z=S==null?void 0:S.shares)==null?void 0:z.orgUsersOnly)==null?void 0:F[0];return C.useEffect(()=>{x==="all_users"&&R&&R.role!==void 0&&b.setOrgWideRole(R.role)},[x,R,b]),n?c.jsxs(c.Fragment,{children:[c.jsx(zM,{shareType:x,onShareTypeChange:_,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:c.jsx(Kl,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"all_users",label:"All Org Users",description:`Share with all ${(n==null?void 0:n.type)==="organization"?"organization":"tenant"} users`,icon:c.jsx(Pr,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),x==="specific_users"?c.jsxs("div",{className:"mt-3 space-y-4",children:[c.jsx(pW,{users:j,selectedUsers:f,existingUserIds:k,isLoading:N||E,onUserToggle:T,onSearchChange:u,getRoleOptions:$o,currentUserId:n==null?void 0:n.id,placeholder:"Search and select users to share with..."}),c.jsx(UB,{selectedUsers:f,selectedUserObjects:M,onRemove:T,onRoleChange:P,getRoleOptions:$o}),c.jsx(vW,{existingShares:S,usersToRemove:h,usersToUpdate:m,allUsers:j,onUpdateRole:O,onRemoveAccess:I,onUndoRemove:$,onUndoUpdate:V,getRoleOptions:$o,isLoading:N,userType:"organization"})]}):c.jsx("div",{className:"mt-3",children:c.jsx(BU,{currentUser:n,currentShare:R,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:W,onRemoveAccess:L,allUsersToUpdate:p==="allOrgUsers"&&g!==((R==null?void 0:R.role)||"NONE")?{currentRole:(R==null?void 0:R.role)||"NONE",newRole:g}:null,allUsersToRemove:p==="allOrgUsers"&&(R==null?void 0:R.role)===void 0})})]}):null}function wW({selectedGroups:e,groupObjects:t,onRemove:n,onRoleChange:r,getRoleOptions:s}){if(e.length===0)return null;const o=s();return c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["Selected Groups (",e.length,")"]}),c.jsx("div",{className:"space-y-1",children:e.map(i=>{const a=t.find(l=>l.id===i.id);return a?c.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/50 p-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[a.type==="ORG_GROUP"?c.jsx(ql,{className:"h-4 w-4 text-blue-600"}):c.jsx(Pr,{className:"h-4 w-4 text-green-600"}),c.jsx("span",{className:"text-sm font-medium",children:a.name}),c.jsxs(Ve,{variant:"secondary",className:"text-xs",children:[a.memberCount," members"]}),a.type==="TENANT_GROUP"&&a.tenantName&&c.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",a.tenantName]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(dC,{currentRole:i.role,onRoleChange:l=>r(i.id,l),roleOptions:o}),c.jsx(se,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>n(i.id),children:c.jsx(St,{className:"h-3 w-3"})})]})]},i.id):null})})]})}const ms=ID,ps=RD,gs=D.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>c.jsx(_Ce,{children:c.jsx(Za,{children:c.jsx(sp,{ref:s,align:t,sideOffset:n,className:X("z-49 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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),...r})})}));gs.displayName=sp.displayName;function CW(e){switch(e){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function SW(e){switch(e){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function jW({groups:e,selectedGroups:t,existingGroupIds:n,isLoading:r,onGroupToggle:s,placeholder:o="Search and select groups..."}){const[i,a]=C.useState(!1),[l,u]=C.useState(""),d=C.useMemo(()=>e.filter(p=>!n.includes(p.id)),[e,n]),f=C.useMemo(()=>{if(!l)return d;const p=l.toLowerCase();return d.filter(g=>g.name.toLowerCase().includes(p)||g.description&&g.description.toLowerCase().includes(p)||g.tenantName&&g.tenantName.toLowerCase().includes(p))},[d,l]),h=p=>t.some(g=>g.id===p),m=()=>{const p=t.length;return p===0?o:`${p} group${p>1?"s":""} selected`};return c.jsxs(ms,{open:i,onOpenChange:a,children:[c.jsx(ps,{asChild:!0,children:c.jsxs(se,{variant:"outline",role:"combobox","aria-expanded":i,className:"w-full justify-between font-normal",children:[c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Ko,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:X(t.length===0&&"text-muted-foreground"),children:m()})]}),c.jsx(VT,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),c.jsxs(gs,{className:"w-[400px] p-0",align:"start",children:[c.jsxs(op,{shouldFilter:!1,children:[c.jsx(ey,{placeholder:"Search by name or description...",value:l,onValueChange:u}),c.jsx(ip,{children:r?c.jsxs("div",{className:"flex items-center justify-center py-6",children:[c.jsx(xn,{className:"h-4 w-4 animate-spin"}),c.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading groups..."})]}):f.length===0?c.jsx(ap,{children:l?"No groups found matching your search.":"No groups available to share with."}):c.jsx(lp,{children:f.map(p=>{const g=h(p.id);return c.jsx(cp,{value:p.id,onSelect:()=>s(p.id),className:"cursor-pointer",children:c.jsxs("div",{className:"flex w-full items-center gap-3",children:[c.jsx(cn,{checked:g,className:"pointer-events-none"}),c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"truncate font-medium",children:p.name}),p.type==="ORG_GROUP"?c.jsx(ql,{className:"h-3 w-3 shrink-0 text-blue-600"}):c.jsx(Pr,{className:"h-3 w-3 shrink-0 text-green-600"}),c.jsxs(Ve,{variant:"secondary",className:"shrink-0 text-xs",children:[p.memberCount," members"]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:X("text-xs",SW(p.type)),children:CW(p.type)}),p.type==="TENANT_GROUP"&&p.tenantName&&c.jsx("span",{className:"text-xs text-muted-foreground",children:p.tenantName})]}),p.description&&c.jsx("span",{className:"truncate text-xs text-muted-foreground",children:p.description})]}),g&&c.jsx(Ar,{className:"h-4 w-4 shrink-0 text-primary"})]})},p.id)})})})]}),t.length>0&&c.jsx("div",{className:"border-t p-2",children:c.jsxs("div",{className:"text-xs text-muted-foreground",children:[t.length," group",t.length>1?"s":""," ","selected"]})})]})]})}function NW({existingGroupShares:e,groupsToRemove:t,groupsToUpdate:n,allGroups:r,onUpdateRole:s,onRemoveAccess:o,onUndoRemove:i,onUndoUpdate:a,getRoleOptions:l,isLoading:u=!1,defaultExpanded:d=!0}){const[f,h]=C.useState(d),m=C.useMemo(()=>e.map(y=>{const v=r.find(S=>S.id===y.groupId),w=t.includes(y.groupId),j=n.find(S=>S.id===y.groupId);return{share:y,group:v,groupId:y.groupId,isMarkedForRemoval:w,updateInfo:j,displayRole:j?j.newRole:y.role}}).filter(y=>y.group),[e,r,t,n]),p=m.filter(y=>!y.isMarkedForRemoval).length,g=m.filter(y=>y.isMarkedForRemoval).length,b=m.filter(y=>y.updateInfo&&!y.isMarkedForRemoval).length,x=l();return u?c.jsx("div",{className:"rounded-lg border border-dashed p-4",children:c.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c.jsx(xn,{className:"h-4 w-4 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading current access..."})]})}):e.length===0?c.jsx("div",{className:"rounded-lg border border-dashed p-4 text-center",children:c.jsx("p",{className:"text-sm text-muted-foreground",children:"This resource hasn't been shared with any groups yet."})}):c.jsxs(bo,{open:f,onOpenChange:h,className:"space-y-2",children:[c.jsx(xo,{asChild:!0,children:c.jsx(se,{variant:"ghost",className:"flex w-full items-center justify-between p-2 hover:bg-muted/50",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx("span",{className:"text-sm font-medium",children:"Current Access"}),c.jsx(Ve,{variant:"secondary",className:"text-xs",children:p}),g>0&&c.jsxs(Ve,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:["-",g]}),b>0&&c.jsxs(Ve,{variant:"outline",className:"border-orange-200 bg-orange-50 text-xs text-orange-700",children:[b," updating"]})]})})}),c.jsx(yo,{className:"space-y-1",children:c.jsx("div",{className:"max-h-48 space-y-1 overflow-y-auto rounded-md border p-2",children:m.map(({share:y,group:v,groupId:w,isMarkedForRemoval:j,updateInfo:S,displayRole:N})=>v?c.jsxs("div",{className:X("flex items-center justify-between rounded-md p-2 transition-colors",j?"bg-red-50 opacity-60":S?"bg-orange-50":"hover:bg-muted/50"),children:[c.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:X("truncate text-sm font-medium",j&&"line-through"),children:v.name}),v.type==="ORG_GROUP"?c.jsx(ql,{className:"h-3 w-3 shrink-0 text-blue-600"}):c.jsx(Pr,{className:"h-3 w-3 shrink-0 text-green-600"}),c.jsxs(Ve,{variant:"secondary",className:"shrink-0 text-xs",children:[v.memberCount," members"]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:X("text-xs",SW(v.type)),children:CW(v.type)}),v.type==="TENANT_GROUP"&&v.tenantName&&c.jsx("span",{className:"text-xs text-muted-foreground",children:v.tenantName})]})]}),c.jsx("div",{className:"flex shrink-0 items-center gap-2",children:j?c.jsxs(se,{variant:"ghost",size:"sm",onClick:()=>i(w),className:"h-7 gap-1 text-xs",children:[c.jsx(ew,{className:"h-3 w-3"}),"Undo"]}):c.jsxs(c.Fragment,{children:[c.jsx(dC,{currentRole:N,onRoleChange:E=>s(w,y.role,E),roleOptions:x,className:X(S&&"border-orange-300 bg-orange-100")}),S?c.jsx(se,{variant:"ghost",size:"sm",onClick:()=>a(w),className:"h-7 gap-1 px-2 text-xs",children:c.jsx(ew,{className:"h-3 w-3"})}):c.jsx(se,{variant:"ghost",size:"sm",onClick:()=>o(w),className:"h-7 px-2 text-destructive hover:bg-destructive/10 hover:text-destructive",children:c.jsx(ec,{className:"h-3 w-3"})})]})})]},w):null)})})]})}const dSe=async(e,t,n={})=>{const r={};n.search&&(r.search=n.search),n.type&&n.type!=="all"&&(r.type=n.type),n.tenantId&&(r.tenantId=n.tenantId),n.organizationId&&(r.organizationId=n.organizationId),n.includeMembers!==void 0&&(r.includeMembers=n.includeMembers.toString()),n.page&&(r.page=n.page.toString()),n.limit&&(r.limit=n.limit.toString());const s=`${e}/management/v1/groups`;return await rr(s,t,r)},fSe=async(e,t,n)=>{const r=`${e}/management/v1/groups/${n}/members`;return await rr(r,t)};function HD(e={}){var o,i,a;const{authToken:t,tokenProps:n}=Xe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=En({queryKey:["groups",e],queryFn:()=>dSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(l,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:l<2,retryDelay:l=>Math.min(1e3*2**l,3e4),staleTime:6e4});return{groups:((o=s.data)==null?void 0:o.groups)||[],total:((i=s.data)==null?void 0:i.total)||0,hasMore:((a=s.data)==null?void 0:a.hasMore)||!1,isLoading:s.isLoading,isError:s.isError,error:s.error,isFetching:s.isFetching,refetch:s.refetch}}function hSe(e){const{authToken:t,tokenProps:n}=Xe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId);return En({queryKey:["group-members",e],queryFn:()=>fSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r&&!!e,retry:1,staleTime:6e4})}function kW(e,t){const{tokenProps:n}=Xe(),r={limit:100};return e==="organization"||n!=null&&n.orgUserId?(r.type="all",t&&(r.tenantId=t)):(e==="tenant"||n!=null&&n.endUserId)&&(r.type="TENANT_GROUP",(t||n!=null&&n.tenantId)&&(r.tenantId=t||n.tenantId)),HD(r)}function Ib(e,[t,n]){return Math.min(n,Math.max(t,e))}function mSe(e){const t=pSe(e),n=D.forwardRef((r,s)=>{const{children:o,...i}=r,a=D.Children.toArray(o),l=a.find(bSe);if(l){const u=l.props.children,d=a.map(f=>f===l?D.Children.count(u)>1?D.Children.only(null):D.isValidElement(u)?u.props.children:null:f);return c.jsx(t,{...i,ref:s,children:D.isValidElement(u)?D.cloneElement(u,void 0,d):null})}return c.jsx(t,{...i,ref:s,children:o})});return n.displayName=`${e}.Slot`,n}function pSe(e){const t=D.forwardRef((n,r)=>{const{children:s,...o}=n;if(D.isValidElement(s)){const i=ySe(s),a=xSe(o,s.props);return s.type!==D.Fragment&&(a.ref=r?to(r,i):i),D.cloneElement(s,a)}return D.Children.count(s)>1?D.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var gSe=Symbol("radix.slottable");function bSe(e){return D.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===gSe}function xSe(e,t){const n={...t};for(const r in t){const s=e[r],o=t[r];/^on[A-Z]/.test(r)?s&&o?n[r]=(...a)=>{const l=o(...a);return s(...a),l}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function ySe(e){var r,s;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(s=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:s.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var vSe=[" ","Enter","ArrowUp","ArrowDown"],wSe=[" ","Enter"],of="Select",[$C,LC,CSe]=Ex(of),[up]=Lr(of,[CSe,Ka]),zC=Ka(),[SSe,_u]=up(of),[jSe,NSe]=up(of),EW=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:s,onOpenChange:o,value:i,defaultValue:a,onValueChange:l,dir:u,name:d,autoComplete:f,disabled:h,required:m,form:p}=e,g=zC(t),[b,x]=D.useState(null),[y,v]=D.useState(null),[w,j]=D.useState(!1),S=bu(u),[N,E]=ss({prop:r,defaultProp:s??!1,onChange:o,caller:of}),[_,k]=ss({prop:i,defaultProp:a,onChange:l,caller:of}),M=D.useRef(null),T=b?p||!!b.closest("form"):!0,[P,O]=D.useState(new Set),I=Array.from(P).map($=>$.props.value).join(";");return c.jsx(zm,{...g,children:c.jsxs(SSe,{required:m,scope:t,trigger:b,onTriggerChange:x,valueNode:y,onValueNodeChange:v,valueNodeHasChildren:w,onValueNodeHasChildrenChange:j,contentId:xr(),value:_,onValueChange:k,open:N,onOpenChange:E,dir:S,triggerPointerDownPosRef:M,disabled:h,children:[c.jsx($C.Provider,{scope:t,children:c.jsx(jSe,{scope:e.__scopeSelect,onNativeOptionAdd:D.useCallback($=>{O(V=>new Set(V).add($))},[]),onNativeOptionRemove:D.useCallback($=>{O(V=>{const W=new Set(V);return W.delete($),W})},[]),children:n})}),T?c.jsxs(QW,{"aria-hidden":!0,required:m,tabIndex:-1,name:d,autoComplete:f,value:_,onChange:$=>k($.target.value),disabled:h,form:p,children:[_===void 0?c.jsx("option",{value:""}):null,Array.from(P)]},I):null]})})};EW.displayName=of;var _W="SelectTrigger",TW=D.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=zC(n),i=_u(_W,n),a=i.disabled||r,l=ut(t,i.onTriggerChange),u=LC(n),d=D.useRef("touch"),[f,h,m]=eq(g=>{const b=u().filter(v=>!v.disabled),x=b.find(v=>v.value===i.value),y=tq(b,g,x);y!==void 0&&i.onValueChange(y.value)}),p=g=>{a||(i.onOpenChange(!0),m()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return c.jsx(Bm,{asChild:!0,...o,children:c.jsx(Ze.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":JW(i.value)?"":void 0,...s,ref:l,onClick:Ie(s.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&p(g)}),onPointerDown:Ie(s.onPointerDown,g=>{d.current=g.pointerType;const b=g.target;b.hasPointerCapture(g.pointerId)&&b.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(p(g),g.preventDefault())}),onKeyDown:Ie(s.onKeyDown,g=>{const b=f.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(b&&g.key===" ")&&vSe.includes(g.key)&&(p(),g.preventDefault())})})})});TW.displayName=_W;var MW="SelectValue",DW=D.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:i="",...a}=e,l=_u(MW,n),{onValueNodeHasChildrenChange:u}=l,d=o!==void 0,f=ut(t,l.onValueNodeChange);return Yr(()=>{u(d)},[u,d]),c.jsx(Ze.span,{...a,ref:f,style:{pointerEvents:"none"},children:JW(l.value)?c.jsx(c.Fragment,{children:i}):o})});DW.displayName=MW;var kSe="SelectIcon",IW=D.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return c.jsx(Ze.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});IW.displayName=kSe;var ESe="SelectPortal",RW=e=>c.jsx(yf,{asChild:!0,...e});RW.displayName=ESe;var af="SelectContent",AW=D.forwardRef((e,t)=>{const n=_u(af,e.__scopeSelect),[r,s]=D.useState();if(Yr(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?Bd.createPortal(c.jsx(PW,{scope:e.__scopeSelect,children:c.jsx($C.Slot,{scope:e.__scopeSelect,children:c.jsx("div",{children:e.children})})}),o):null}return c.jsx(OW,{...e,ref:t})});AW.displayName=af;var Ri=10,[PW,Tu]=up(af),_Se="SelectContentImpl",TSe=mSe("SelectContent.RemoveScroll"),OW=D.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:s,onEscapeKeyDown:o,onPointerDownOutside:i,side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:m,sticky:p,hideWhenDetached:g,avoidCollisions:b,...x}=e,y=_u(af,n),[v,w]=D.useState(null),[j,S]=D.useState(null),N=ut(t,q=>w(q)),[E,_]=D.useState(null),[k,M]=D.useState(null),T=LC(n),[P,O]=D.useState(!1),I=D.useRef(!1);D.useEffect(()=>{if(v)return J1(v)},[v]),G1();const $=D.useCallback(q=>{const[U,...G]=T().map(K=>K.ref.current),[Z]=G.slice(-1),Q=document.activeElement;for(const K of q)if(K===Q||(K==null||K.scrollIntoView({block:"nearest"}),K===U&&j&&(j.scrollTop=0),K===Z&&j&&(j.scrollTop=j.scrollHeight),K==null||K.focus(),document.activeElement!==Q))return},[T,j]),V=D.useCallback(()=>$([E,v]),[$,E,v]);D.useEffect(()=>{P&&V()},[P,V]);const{onOpenChange:W,triggerPointerDownPosRef:L}=y;D.useEffect(()=>{if(v){let q={x:0,y:0};const U=Z=>{var Q,K;q={x:Math.abs(Math.round(Z.pageX)-(((Q=L.current)==null?void 0:Q.x)??0)),y:Math.abs(Math.round(Z.pageY)-(((K=L.current)==null?void 0:K.y)??0))}},G=Z=>{q.x<=10&&q.y<=10?Z.preventDefault():v.contains(Z.target)||W(!1),document.removeEventListener("pointermove",U),L.current=null};return L.current!==null&&(document.addEventListener("pointermove",U),document.addEventListener("pointerup",G,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",U),document.removeEventListener("pointerup",G,{capture:!0})}}},[v,W,L]),D.useEffect(()=>{const q=()=>W(!1);return window.addEventListener("blur",q),window.addEventListener("resize",q),()=>{window.removeEventListener("blur",q),window.removeEventListener("resize",q)}},[W]);const[R,z]=eq(q=>{const U=T().filter(Q=>!Q.disabled),G=U.find(Q=>Q.ref.current===document.activeElement),Z=tq(U,q,G);Z&&setTimeout(()=>Z.ref.current.focus())}),F=D.useCallback((q,U,G)=>{const Z=!I.current&&!G;(y.value!==void 0&&y.value===U||Z)&&(_(q),Z&&(I.current=!0))},[y.value]),A=D.useCallback(()=>v==null?void 0:v.focus(),[v]),H=D.useCallback((q,U,G)=>{const Z=!I.current&&!G;(y.value!==void 0&&y.value===U||Z)&&M(q)},[y.value]),B=r==="popper"?FE:FW,Y=B===FE?{side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:m,sticky:p,hideWhenDetached:g,avoidCollisions:b}:{};return c.jsx(PW,{scope:n,content:v,viewport:j,onViewportChange:S,itemRefCallback:F,selectedItem:E,onItemLeave:A,itemTextRefCallback:H,focusSelectedItem:V,selectedItemText:k,position:r,isPositioned:P,searchRef:R,children:c.jsx(Rx,{as:TSe,allowPinchZoom:!0,children:c.jsx(Fm,{asChild:!0,trapped:y.open,onMountAutoFocus:q=>{q.preventDefault()},onUnmountAutoFocus:Ie(s,q=>{var U;(U=y.trigger)==null||U.focus({preventScroll:!0}),q.preventDefault()}),children:c.jsx(xf,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:q=>q.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:c.jsx(B,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:q=>q.preventDefault(),...x,...Y,onPlaced:()=>O(!0),ref:N,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:Ie(x.onKeyDown,q=>{const U=q.ctrlKey||q.altKey||q.metaKey;if(q.key==="Tab"&&q.preventDefault(),!U&&q.key.length===1&&z(q.key),["ArrowUp","ArrowDown","Home","End"].includes(q.key)){let Z=T().filter(Q=>!Q.disabled).map(Q=>Q.ref.current);if(["ArrowUp","End"].includes(q.key)&&(Z=Z.slice().reverse()),["ArrowUp","ArrowDown"].includes(q.key)){const Q=q.target,K=Z.indexOf(Q);Z=Z.slice(K+1)}setTimeout(()=>$(Z)),q.preventDefault()}})})})})})})});OW.displayName=_Se;var MSe="SelectItemAlignedPosition",FW=D.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=_u(af,n),i=Tu(af,n),[a,l]=D.useState(null),[u,d]=D.useState(null),f=ut(t,N=>d(N)),h=LC(n),m=D.useRef(!1),p=D.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:x,focusSelectedItem:y}=i,v=D.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&u&&g&&b&&x){const N=o.trigger.getBoundingClientRect(),E=u.getBoundingClientRect(),_=o.valueNode.getBoundingClientRect(),k=x.getBoundingClientRect();if(o.dir!=="rtl"){const Q=k.left-E.left,K=_.left-Q,te=N.left-K,le=N.width+te,de=Math.max(le,E.width),ce=window.innerWidth-Ri,Ce=Ib(K,[Ri,Math.max(Ri,ce-de)]);a.style.minWidth=le+"px",a.style.left=Ce+"px"}else{const Q=E.right-k.right,K=window.innerWidth-_.right-Q,te=window.innerWidth-N.right-K,le=N.width+te,de=Math.max(le,E.width),ce=window.innerWidth-Ri,Ce=Ib(K,[Ri,Math.max(Ri,ce-de)]);a.style.minWidth=le+"px",a.style.right=Ce+"px"}const M=h(),T=window.innerHeight-Ri*2,P=g.scrollHeight,O=window.getComputedStyle(u),I=parseInt(O.borderTopWidth,10),$=parseInt(O.paddingTop,10),V=parseInt(O.borderBottomWidth,10),W=parseInt(O.paddingBottom,10),L=I+$+P+W+V,R=Math.min(b.offsetHeight*5,L),z=window.getComputedStyle(g),F=parseInt(z.paddingTop,10),A=parseInt(z.paddingBottom,10),H=N.top+N.height/2-Ri,B=T-H,Y=b.offsetHeight/2,q=b.offsetTop+Y,U=I+$+q,G=L-U;if(U<=H){const Q=M.length>0&&b===M[M.length-1].ref.current;a.style.bottom="0px";const K=u.clientHeight-g.offsetTop-g.offsetHeight,te=Math.max(B,Y+(Q?A:0)+K+V),le=U+te;a.style.height=le+"px"}else{const Q=M.length>0&&b===M[0].ref.current;a.style.top="0px";const te=Math.max(H,I+g.offsetTop+(Q?F:0)+Y)+G;a.style.height=te+"px",g.scrollTop=U-H+g.offsetTop}a.style.margin=`${Ri}px 0`,a.style.minHeight=R+"px",a.style.maxHeight=T+"px",r==null||r(),requestAnimationFrame(()=>m.current=!0)}},[h,o.trigger,o.valueNode,a,u,g,b,x,o.dir,r]);Yr(()=>v(),[v]);const[w,j]=D.useState();Yr(()=>{u&&j(window.getComputedStyle(u).zIndex)},[u]);const S=D.useCallback(N=>{N&&p.current===!0&&(v(),y==null||y(),p.current=!1)},[v,y]);return c.jsx(ISe,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:m,onScrollButtonChange:S,children:c.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:w},children:c.jsx(Ze.div,{...s,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});FW.displayName=MSe;var DSe="SelectPopperPosition",FE=D.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=Ri,...o}=e,i=zC(n);return c.jsx(Mx,{...i,...o,ref:t,align:r,collisionPadding:s,style:{boxSizing:"border-box",...o.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});FE.displayName=DSe;var[ISe,UD]=up(af,{}),$E="SelectViewport",$W=D.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Tu($E,n),i=UD($E,n),a=ut(t,o.onViewportChange),l=D.useRef(0);return c.jsxs(c.Fragment,{children:[c.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),c.jsx($C.Slot,{scope:n,children:c.jsx(Ze.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...s.style},onScroll:Ie(s.onScroll,u=>{const d=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const m=Math.abs(l.current-d.scrollTop);if(m>0){const p=window.innerHeight-Ri*2,g=parseFloat(f.style.minHeight),b=parseFloat(f.style.height),x=Math.max(g,b);if(x<p){const y=x+m,v=Math.min(p,y),w=y-v;f.style.height=v+"px",f.style.bottom==="0px"&&(d.scrollTop=w>0?w:0,f.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});$W.displayName=$E;var LW="SelectGroup",[RSe,ASe]=up(LW),zW=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=xr();return c.jsx(RSe,{scope:n,id:s,children:c.jsx(Ze.div,{role:"group","aria-labelledby":s,...r,ref:t})})});zW.displayName=LW;var BW="SelectLabel",VW=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=ASe(BW,n);return c.jsx(Ze.div,{id:s.id,...r,ref:t})});VW.displayName=BW;var Ow="SelectItem",[PSe,HW]=up(Ow),UW=D.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...i}=e,a=_u(Ow,n),l=Tu(Ow,n),u=a.value===r,[d,f]=D.useState(o??""),[h,m]=D.useState(!1),p=ut(t,y=>{var v;return(v=l.itemRefCallback)==null?void 0:v.call(l,y,r,s)}),g=xr(),b=D.useRef("touch"),x=()=>{s||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return c.jsx(PSe,{scope:n,value:r,disabled:s,textId:g,isSelected:u,onItemTextChange:D.useCallback(y=>{f(v=>v||((y==null?void 0:y.textContent)??"").trim())},[]),children:c.jsx($C.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:c.jsx(Ze.div,{role:"option","aria-labelledby":g,"data-highlighted":h?"":void 0,"aria-selected":u&&h,"data-state":u?"checked":"unchecked","aria-disabled":s||void 0,"data-disabled":s?"":void 0,tabIndex:s?void 0:-1,...i,ref:p,onFocus:Ie(i.onFocus,()=>m(!0)),onBlur:Ie(i.onBlur,()=>m(!1)),onClick:Ie(i.onClick,()=>{b.current!=="mouse"&&x()}),onPointerUp:Ie(i.onPointerUp,()=>{b.current==="mouse"&&x()}),onPointerDown:Ie(i.onPointerDown,y=>{b.current=y.pointerType}),onPointerMove:Ie(i.onPointerMove,y=>{var v;b.current=y.pointerType,s?(v=l.onItemLeave)==null||v.call(l):b.current==="mouse"&&y.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ie(i.onPointerLeave,y=>{var v;y.currentTarget===document.activeElement&&((v=l.onItemLeave)==null||v.call(l))}),onKeyDown:Ie(i.onKeyDown,y=>{var w;((w=l.searchRef)==null?void 0:w.current)!==""&&y.key===" "||(wSe.includes(y.key)&&x(),y.key===" "&&y.preventDefault())})})})})});UW.displayName=Ow;var pg="SelectItemText",WW=D.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,i=_u(pg,n),a=Tu(pg,n),l=HW(pg,n),u=NSe(pg,n),[d,f]=D.useState(null),h=ut(t,x=>f(x),l.onItemTextChange,x=>{var y;return(y=a.itemTextRefCallback)==null?void 0:y.call(a,x,l.value,l.disabled)}),m=d==null?void 0:d.textContent,p=D.useMemo(()=>c.jsx("option",{value:l.value,disabled:l.disabled,children:m},l.value),[l.disabled,l.value,m]),{onNativeOptionAdd:g,onNativeOptionRemove:b}=u;return Yr(()=>(g(p),()=>b(p)),[g,b,p]),c.jsxs(c.Fragment,{children:[c.jsx(Ze.span,{id:l.textId,...o,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Bd.createPortal(o.children,i.valueNode):null]})});WW.displayName=pg;var qW="SelectItemIndicator",YW=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return HW(qW,n).isSelected?c.jsx(Ze.span,{"aria-hidden":!0,...r,ref:t}):null});YW.displayName=qW;var LE="SelectScrollUpButton",GW=D.forwardRef((e,t)=>{const n=Tu(LE,e.__scopeSelect),r=UD(LE,e.__scopeSelect),[s,o]=D.useState(!1),i=ut(t,r.onScrollButtonChange);return Yr(()=>{if(n.viewport&&n.isPositioned){let a=function(){const u=l.scrollTop>0;o(u)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),s?c.jsx(ZW,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});GW.displayName=LE;var zE="SelectScrollDownButton",KW=D.forwardRef((e,t)=>{const n=Tu(zE,e.__scopeSelect),r=UD(zE,e.__scopeSelect),[s,o]=D.useState(!1),i=ut(t,r.onScrollButtonChange);return Yr(()=>{if(n.viewport&&n.isPositioned){let a=function(){const u=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<u;o(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),s?c.jsx(ZW,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});KW.displayName=zE;var ZW=D.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Tu("SelectScrollButton",n),i=D.useRef(null),a=LC(n),l=D.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return D.useEffect(()=>()=>l(),[l]),Yr(()=>{var d;const u=a().find(f=>f.ref.current===document.activeElement);(d=u==null?void 0:u.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),c.jsx(Ze.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:Ie(s.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:Ie(s.onPointerMove,()=>{var u;(u=o.onItemLeave)==null||u.call(o),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:Ie(s.onPointerLeave,()=>{l()})})}),OSe="SelectSeparator",XW=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c.jsx(Ze.div,{"aria-hidden":!0,...r,ref:t})});XW.displayName=OSe;var BE="SelectArrow",FSe=D.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=zC(n),o=_u(BE,n),i=Tu(BE,n);return o.open&&i.position==="popper"?c.jsx(Dx,{...s,...r,ref:t}):null});FSe.displayName=BE;var $Se="SelectBubbleInput",QW=D.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const s=D.useRef(null),o=ut(r,s),i=$x(t);return D.useEffect(()=>{const a=s.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),c.jsx(Ze.select,{...n,style:{...b7,...n.style},ref:o,defaultValue:t})});QW.displayName=$Se;function JW(e){return e===""||e===void 0}function eq(e){const t=qr(e),n=D.useRef(""),r=D.useRef(0),s=D.useCallback(i=>{const a=n.current+i;t(a),function l(u){n.current=u,window.clearTimeout(r.current),u!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),o=D.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return D.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function tq(e,t,n){const s=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let i=LSe(e,Math.max(o,0));s.length===1&&(i=i.filter(u=>u!==n));const l=i.find(u=>u.textValue.toLowerCase().startsWith(s.toLowerCase()));return l!==n?l:void 0}function LSe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var zSe=EW,nq=TW,BSe=DW,VSe=IW,HSe=RW,rq=AW,USe=$W,WSe=zW,sq=VW,oq=UW,qSe=WW,YSe=YW,iq=GW,aq=KW,lq=XW;const ot=zSe,WD=WSe,at=BSe,nt=D.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(nq,{ref:r,className:X("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-0 focus:ring-ring focus:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,c.jsx(VSe,{asChild:!0,children:c.jsx(kr,{className:"h-4 w-4 opacity-50"})})]}));nt.displayName=nq.displayName;const cq=D.forwardRef(({className:e,...t},n)=>c.jsx(iq,{ref:n,className:X("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Ch,{className:"h-4 w-4"})}));cq.displayName=iq.displayName;const uq=D.forwardRef(({className:e,...t},n)=>c.jsx(aq,{ref:n,className:X("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(kr,{className:"h-4 w-4"})}));uq.displayName=aq.displayName;const rt=D.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>c.jsx(HSe,{children:c.jsx(Za,{children:c.jsxs(rq,{ref:s,className:X("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-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",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[c.jsx(cq,{}),c.jsx(USe,{className:X("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),c.jsx(uq,{})]})})}));rt.displayName=rq.displayName;const BC=D.forwardRef(({className:e,...t},n)=>c.jsx(sq,{ref:n,className:X("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));BC.displayName=sq.displayName;const ve=D.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(oq,{ref:r,className:X("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx(YSe,{children:c.jsx(Ar,{className:"h-4 w-4"})})}),c.jsx(qSe,{children:t})]}));ve.displayName=oq.displayName;const GSe=D.forwardRef(({className:e,...t},n)=>c.jsx(lq,{ref:n,className:X("-mx-1 my-1 h-px bg-muted",e),...t}));GSe.displayName=lq.displayName;function z5({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var Ne;const a=qx(),l=np(),u=Yx(),d=Kx(),f=Zx(),h=Xx(),{setSearchQuery:m,debouncedSearchQuery:p}=zU(),g=ku(),b=RC(),x=MD(),y=Gx(),v=rp(),{data:w,isLoading:j}=I7({enabled:(n==null?void 0:n.type)==="organization"}),{groups:S,isLoading:N}=kW("tenant",(n==null?void 0:n.tenantId)||y),[E,_]=C.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");C.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(v.setCurrentContext("tenant-dialog"),v.setCurrentMode("specificTenantUsers")):(v.setCurrentContext("tenant-tab"),v.setCurrentMode("allTenants"))},[v,n==null?void 0:n.type]);const k=fe=>{var ke,ie,xe,Oe;_(fe);let Me;if(fe==="specific_tenant_users"?Me="specific_users":fe==="all_tenant_users"||fe==="all_tenants"?Me="all_users":fe==="groups"?Me="groups":Me="specific_users",r==null||r(Me),fe==="groups"?(v.setCurrentContext("group-share"),v.setCurrentMode("specificGroups")):(n==null?void 0:n.type)==="tenant"?(v.setCurrentContext("tenant-dialog"),fe==="specific_tenant_users"?v.setCurrentMode("specificTenantUsers"):fe==="all_tenant_users"&&(v.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&v.setSelectedTenant(n.tenantId))):(v.setCurrentContext("tenant-tab"),fe==="specific_tenant_users"?v.setCurrentMode("specificTenantUsers"):fe==="all_tenant_users"?v.setCurrentMode("allTenantUsers"):fe==="all_tenants"&&v.setCurrentMode("allTenants")),fe==="all_tenant_users"){const be=(ie=(ke=P==null?void 0:P.shares)==null?void 0:ke.tenantWide)==null?void 0:ie[0];be&&be.role!==void 0&&v.setTenantWideRole(be.role)}else if(fe==="all_tenants"){const be=(Oe=(xe=P==null?void 0:P.shares)==null?void 0:xe.allTenantsOnly)==null?void 0:Oe[0];be&&be.role!==void 0&&v.setAllTenantsRole(be.role)}},M=fe=>{v.setSelectedTenant(fe)},{allUsers:T,existingShares:P,isLoadingUsers:O,isErrorLoadingUsers:I,isLoadingShares:$,isErrorLoadingShares:V}=xm({debouncedSearchQuery:p,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:y}),W=C.useMemo(()=>{var fe;return(((fe=P==null?void 0:P.shares)==null?void 0:fe.specificTenantUsers)||[]).map(Me=>Me.tenantUserId)},[P]),L=fe=>{a.some(ke=>ke.id===fe)?v.removeSelectedUser(fe):v.addSelectedUser({id:fe,role:"VIEWER"})},R=(fe,Me)=>{v.updateSelectedUserRole(fe,Me)},z=(fe,Me,ke)=>{v.addUserToUpdate({id:fe,currentRole:Me,newRole:ke})},F=fe=>{v.addUserToRemove(fe)},A=fe=>{v.removeUserFromRemove(fe)},H=fe=>{v.removeUserFromUpdate(fe)},B=(fe,Me)=>{E==="all_tenant_users"?v.setTenantWideRole(Me):E==="all_tenants"&&v.setAllTenantsRole(Me)},Y=()=>{E==="all_tenant_users"?v.setTenantWideRole("VIEWER"):E==="all_tenants"&&v.setAllTenantsRole("VIEWER")},U=(()=>{var fe,Me,ke,ie;return g==="allTenants"?(Me=(fe=P==null?void 0:P.shares)==null?void 0:fe.allTenantsOnly)==null?void 0:Me[0]:g==="allTenantUsers"?(ie=(ke=P==null?void 0:P.shares)==null?void 0:ke.tenantWide)==null?void 0:ie[0]:null})();C.useEffect(()=>{var fe,Me,ke,ie;if(E==="all_tenant_users"){const xe=(Me=(fe=P==null?void 0:P.shares)==null?void 0:fe.tenantWide)==null?void 0:Me[0];xe&&xe.role!==void 0&&v.setTenantWideRole(xe.role)}else if(E==="all_tenants"){const xe=(ie=(ke=P==null?void 0:P.shares)==null?void 0:ke.allTenantsOnly)==null?void 0:ie[0];xe&&xe.role!==void 0&&v.setAllTenantsRole(xe.role)}},[E,P,v]);const G=T.filter(fe=>a.some(Me=>Me.id===fe.id)),Z=fe=>{const Me=d.some(xe=>xe.id===fe),ke=f.includes(fe),ie=ge==null?void 0:ge.some(xe=>xe.groupId===fe);Me?v.removeSelectedGroup(fe):ke?v.removeGroupFromRemove(fe):ie||v.addSelectedGroup({id:fe,role:"VIEWER"})},Q=(fe,Me)=>{v.updateSelectedGroupRole(fe,Me)},K=fe=>{v.addGroupToRemove(fe),v.removeSelectedGroup(fe)},te=(fe,Me,ke)=>{v.addGroupToUpdate({id:fe,currentRole:Me,newRole:ke})},le=fe=>{v.removeGroupFromRemove(fe)},de=fe=>{v.removeGroupFromUpdate(fe)},ce=S.filter(fe=>d.some(Me=>Me.id===fe.id)),Ce=C.useMemo(()=>E!=="groups"?[]:S.filter(fe=>fe.type==="TENANT_GROUP"),[S,E]),ge=C.useMemo(()=>{var Me,ke;const fe=((Me=P==null?void 0:P.shares)==null?void 0:Me.specificGroups)||((ke=P==null?void 0:P.shares)==null?void 0:ke.groups)||[];return!fe||fe.length===0?[]:fe.filter(ie=>{const xe=S.find(Oe=>Oe.id===ie.groupId);return(xe==null?void 0:xe.type)==="TENANT_GROUP"})},[P,S]),he=C.useMemo(()=>ge.map(fe=>fe.groupId),[ge]),me=I||V,oe=()=>(n==null?void 0:n.type)==="tenant"||E==="all_tenants"||E==="groups"?!0:y&&(E==="specific_tenant_users"||E==="all_tenant_users");return c.jsxs(c.Fragment,{children:[me&&c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsxs("div",{className:"text-center",children:[c.jsx(Yl,{className:"mx-auto mb-2 h-8 w-8 text-destructive"}),c.jsx("p",{className:"mb-4 text-sm text-destructive",children:"Failed to load users or shares"}),c.jsx(se,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!me&&n&&c.jsxs("div",{className:"space-y-4",children:[c.jsx(zM,{shareType:E,onShareTypeChange:k,currentUser:n,options:(n==null?void 0:n.type)==="tenant"?[{value:"all_tenant_users",label:"All Users",description:"Share with all users of this tenant",icon:c.jsx(Pr,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"specific_tenant_users",label:"Specific Users",description:"Share with specific tenant users",icon:c.jsx(Kl,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:c.jsx(Pr,{className:"mb-3 h-6 w-6 text-green-500"})}]:[{value:"all_tenants",label:"All Tenants",description:"Share with all tenants and their users",icon:c.jsx(RP,{className:"mb-3 h-6 w-6 text-purple-500"})},{value:"all_tenant_users",label:"Specific Tenant",description:"Share with all users of a specific tenant",icon:c.jsx(hb,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"specific_tenant_users",label:"Specific Tenant User",description:"Share with users of a specific tenant",icon:c.jsx(Kl,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(E==="specific_tenant_users"||E==="all_tenant_users")&&c.jsxs("div",{className:"mt-4",children:[c.jsx(ae,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),c.jsxs(ot,{value:y||"",onValueChange:M,disabled:j,children:[c.jsx(nt,{className:"w-full",children:c.jsx(at,{placeholder:j?"Loading tenants...":"Select a tenant..."})}),c.jsx(rt,{className:"z-[51]",children:(Ne=w==null?void 0:w.tenants)==null?void 0:Ne.map(fe=>c.jsx(ve,{value:fe.id,children:fe.name},fe.id))})]})]}),oe()?c.jsx(c.Fragment,{children:E==="specific_tenant_users"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(pW,{users:T,selectedUsers:a,existingUserIds:W,isLoading:O||$,onUserToggle:L,onSearchChange:m,getRoleOptions:$o,currentUserId:n==null?void 0:n.id,placeholder:"Search and select users to share with..."}),c.jsx(UB,{selectedUsers:a,selectedUserObjects:G,onRemove:fe=>L(fe),onRoleChange:R,getRoleOptions:$o}),c.jsx(vW,{existingShares:P,usersToRemove:l,usersToUpdate:u,allUsers:T,onUpdateRole:z,onRemoveAccess:F,onUndoRemove:A,onUndoUpdate:H,getRoleOptions:$o,userType:"tenant",selectedTenantId:y})]}):E==="groups"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(jW,{groups:Ce,selectedGroups:d,existingGroupIds:he,isLoading:N,onGroupToggle:Z,getRoleOptions:$o,placeholder:"Search and select groups to share with..."}),c.jsx(wW,{selectedGroups:d,groupObjects:ce,onRemove:Z,onRoleChange:Q,getRoleOptions:$o}),c.jsx(NW,{existingGroupShares:ge,groupsToRemove:f,groupsToUpdate:h,allGroups:Ce,onUpdateRole:te,onRemoveAccess:K,onUndoRemove:le,onUndoUpdate:de,getRoleOptions:$o,isLoading:$})]}):E==="all_tenant_users"||E==="all_tenants"?c.jsx("div",{className:"mt-6",children:c.jsx(BU,{currentUser:n,currentShare:U,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:B,onRemoveAccess:Y,allUsersToUpdate:g==="allTenantUsers"&&((U==null?void 0:U.role)===void 0||b!==U.role)||g==="allTenants"&&((U==null?void 0:U.role)===void 0||x!==U.role)?{currentRole:(U==null?void 0:U.role)||"VIEWER",newRole:g==="allTenantUsers"?b:x}:null,allUsersToRemove:g==="allTenantUsers"&&(U==null?void 0:U.role)===void 0||g==="allTenants"&&(U==null?void 0:U.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(E==="specific_tenant_users"||E==="all_tenant_users")&&c.jsx("div",{className:"mt-6 flex items-center justify-center py-8",children:c.jsxs("div",{className:"text-center",children:[c.jsx(RP,{className:"mx-auto mb-2 h-8 w-8 text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant to continue"})]})})]})]})}function KSe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var W,L;const a=Kx(),l=Zx(),u=Xx(),d=rp(),[f,h]=C.useState("org_groups"),[m,p]=C.useState(""),{data:g,isLoading:b}=I7({enabled:(n==null?void 0:n.type)==="organization"&&f==="tenant_groups"}),x=Array.isArray(g)?g:(g==null?void 0:g.tenants)||[],y=()=>{if((n==null?void 0:n.type)==="organization")return"organization";if((n==null?void 0:n.type)==="tenant")return"tenant"},{groups:v,isLoading:w}=kW(y(),f==="tenant_groups"&&(n==null?void 0:n.type)==="organization"?m:n==null?void 0:n.tenantId),{existingShares:j,isLoadingShares:S}=xm({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t}),N=C.useMemo(()=>v.filter(R=>!(f==="org_groups"&&R.type!=="ORG_GROUP"||f==="tenant_groups"&&R.type!=="TENANT_GROUP"||f==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&(!m||R.tenantId&&R.tenantId!==m))),[v,f,m,n==null?void 0:n.type]),E=((W=j==null?void 0:j.shares)==null?void 0:W.specificGroups)||((L=j==null?void 0:j.shares)==null?void 0:L.groups)||[],_=C.useMemo(()=>E.map(R=>R.groupId),[E]);C.useEffect(()=>{d.setCurrentContext("group-share"),d.setCurrentMode("specificGroups")},[d]);const k=R=>{const z=R;h(z),z==="org_groups"&&p(""),r==null||r(z==="org_groups"?"specific_groups":"all_groups"),d.setCurrentContext("group-share"),d.setCurrentMode("specificGroups")},M=v.filter(R=>a.some(z=>z.id===R.id)),T=R=>{a.some(F=>F.id===R)?d.removeSelectedGroup(R):d.addSelectedGroup({id:R,role:"VIEWER"})},P=(R,z)=>{d.updateSelectedGroupRole(R,z)},O=(R,z,F)=>{d.addGroupToUpdate({id:R,currentRole:z,newRole:F})},I=R=>{d.addGroupToRemove(R)},$=R=>{d.removeGroupFromRemove(R)},V=R=>{d.removeGroupFromUpdate(R)};return n?c.jsxs(c.Fragment,{children:[c.jsx(zM,{shareType:f,onShareTypeChange:k,currentUser:n,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:c.jsx(ql,{className:"mb-3 h-6 w-6 text-blue-500"})},{value:"tenant_groups",label:"Tenant Groups",description:"Share with tenant-level groups",icon:c.jsx(Pr,{className:"mb-3 h-6 w-6 text-green-500"})}]}),f==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsx(ae,{children:"Select Tenant"}),c.jsxs(ot,{value:m,onValueChange:p,disabled:b,children:[c.jsx(nt,{className:"w-full",children:c.jsx(at,{placeholder:b?"Loading tenants...":"Select a tenant to view its groups"})}),c.jsx(rt,{className:"z-[51]",children:x.map(R=>c.jsx(ve,{className:"hover:bg-muted",value:R.id,children:R.name},R.id))})]})]}),c.jsx("div",{className:"mt-3 space-y-2",children:f==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&!m?c.jsx("div",{className:"rounded-md border border-dashed p-6 text-center",children:c.jsx("p",{className:"text-sm text-muted-foreground",children:"Please select a tenant above to view and share with its groups"})}):c.jsxs(c.Fragment,{children:[c.jsx(jW,{groups:N,selectedGroups:a,existingGroupIds:_,isLoading:w,onGroupToggle:T,getRoleOptions:$o,placeholder:"Search and select groups to share with..."}),c.jsx(wW,{selectedGroups:a,groupObjects:M,onRemove:T,onRoleChange:P,getRoleOptions:$o}),c.jsx(NW,{existingGroupShares:E,groupsToRemove:l,groupsToUpdate:u,allGroups:v,onUpdateRole:O,onRemoveAccess:I,onUndoRemove:$,onUndoUpdate:V,getRoleOptions:$o,isLoading:S})]})})]}):null}const dq=()=>{const e=$U(),t=ku(),n=qx(),r=np(),s=Yx(),o=Kx(),i=Zx(),a=Xx(),l=Gx(),u=TD(),d=MD(),f=RC(),h=LU(),m=C.useMemo(()=>()=>Qfe({currentContext:e,currentMode:t,selectedUsers:n,usersToRemove:r,usersToUpdate:s,selectedGroups:o,groupsToRemove:i,groupsToUpdate:a,selectedTenant:l,orgWideRole:u,allTenantsRole:d,tenantWideRole:f}),[e,t,n,r,s,o,i,a,l,u,d,f,h]),p=C.useMemo(()=>b=>fV(b),[]),g=C.useMemo(()=>{if(!e||!t)return!1;switch(e){case"org-tab":return t==="specificOrgUsers"?n.length>0||r.length>0||s.length>0:!0;case"tenant-tab":if(t==="allTenantUsers"){if(!l)return!1}else if(t==="specificTenantUsers")return l?n.length>0||r.length>0||s.length>0:!1;return!0;case"tenant-dialog":return t==="specificTenantUsers"?n.length>0||r.length>0||s.length>0:!0;case"group-share":return t==="specificGroups"?o.length>0||i.length>0||a.length>0:!0}return!1},[e,t,n,r,s,o,i,a,l]);return{buildShareData:m,validateShareData:p,isCurrentStateValid:g,currentContext:e,currentMode:t,selectedUsers:n,usersToRemove:r,usersToUpdate:s,selectedTenant:l,orgWideRole:u,allTenantsRole:d,tenantWideRole:f}};function B5({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllUsersShare:l,onRemoveAccess:u}){const d=qx(),f=np(),h=Yx(),m=Gx(),p=TD(),g=MD(),b=RC(),{buildShareData:x,validateShareData:y,isCurrentStateValid:v}=dq(),w=n||r||s,j=()=>{var k,M,T,P;if(w)return"Updating...";if(a==="specific_users"){if(d.length===0&&f.length===0&&h.length===0)return"Select users to share with";const O=d.length+f.length+h.length;return O===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${O} user${O!==1?"s":""}`:f.length>0&&d.length===0&&h.length===0?`Remove access for ${f.length} user${f.length!==1?"s":""}`:d.length>0&&f.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&f.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${O} user${O!==1?"s":""}`}else if(a==="all_users"){if(!l||l.role===void 0)return"Share with All Users";const O=l.role;return p===O?"Remove Access":"Update Access"}else if(a==="all_tenants"){const O=(M=(k=t==null?void 0:t.shares)==null?void 0:k.allTenantsOnly)==null?void 0:M[0];if(!O||O.role===void 0)return"Share with All Tenants";const I=O.role;return g===I?"Remove Access":"Update Access"}else if(a==="all_tenant_users"){const O=(P=(T=t==null?void 0:t.shares)==null?void 0:T.tenantWide)==null?void 0:P[0];if(!O||O.role===void 0)return"Share with All Tenant Users";const I=O.role;return b===I?"Remove Access":"Update Access"}else if(a==="specific_tenant_users"){if(d.length===0&&f.length===0&&h.length===0)return"Select users to share with";const O=d.length+f.length+h.length;return O===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${O} user${O!==1?"s":""}`:f.length>0&&d.length===0&&h.length===0?`Remove access for ${f.length} user${f.length!==1?"s":""}`:d.length>0&&f.length===0&&h.length===0?`Share with ${d.length} user${d.length!==1?"s":""}`:h.length>0&&d.length===0&&f.length===0?`Update access for ${h.length} user${h.length!==1?"s":""}`:`Update access for ${O} user${O!==1?"s":""}`}return"Share"},S=()=>w||!e||a==="all_tenant_users"&&!m||a==="specific_tenant_users"&&!m?!0:!v,N=()=>{const k=x();k&&y(k)&&o(k)},E=()=>{var k,M,T,P;if(a==="all_users")if(!l||l.role===void 0){const O=x();O&&y(O)&&o(O)}else{const O=l.role;if(p===O)u==null||u();else{const $=x();if($&&y($)){const V={...$,updateAccess:!0};o(V)}}}else if(a==="all_tenants"){const O=(M=(k=t==null?void 0:t.shares)==null?void 0:k.allTenantsOnly)==null?void 0:M[0];if(!O||O.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=O.role;if(g===I)u==null||u();else{const V=x();if(V&&y(V)){const W={...V,updateAccess:!0};o(W)}}}}else if(a==="all_tenant_users"){const O=(P=(T=t==null?void 0:t.shares)==null?void 0:T.tenantWide)==null?void 0:P[0];if(!O||O.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=O.role;if(b===I)u==null||u();else{const V=x();if(V&&y(V)){const W={...V,updateAccess:!0};o(W)}}}}},_=()=>{var k,M,T,P;if(a==="all_users"){if(!l||l.role===void 0)return"default";const O=l.role;return p===O?"destructive":"default"}else if(a==="all_tenants"){const O=(M=(k=t==null?void 0:t.shares)==null?void 0:k.allTenantsOnly)==null?void 0:M[0];if(!O||O.role===void 0)return"default";const I=O.role;return g===I?"destructive":"default"}else if(a==="all_tenant_users"){const O=(P=(T=t==null?void 0:t.shares)==null?void 0:T.tenantWide)==null?void 0:P[0];if(!O||O.role===void 0)return"default";const I=O.role;return b===I?"destructive":"default"}return"default"};return c.jsxs(os,{children:[c.jsxs(se,{variant:"outline",onClick:i,disabled:w,children:[c.jsx(St,{className:"mr-2 h-4 w-4"}),"Close"]}),(a==="specific_users"||a==="specific_tenant_users")&&c.jsx(c.Fragment,{children:(d.length>0||f.length>0||h.length>0)&&c.jsxs(se,{onClick:N,disabled:!e||w,variant:"default",children:[w?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Sh,{className:"mr-2 h-4 w-4"}),!w&&j()]})}),(a==="all_users"||a==="all_tenants"||a==="all_tenant_users")&&c.jsxs(se,{onClick:E,disabled:S(),variant:_(),children:[w?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Pr,{className:"mr-2 h-4 w-4"}),!w&&j()]})]})}function ZSe({resource:e,isSharing:t,isRemoving:n,isUpdating:r,onShare:s,onClose:o,shareTabType:i,currentAllUsersShare:a}){const l=qx(),u=np(),d=Yx(),f=Kx(),h=Zx(),m=Xx();ku(),$U();const p=RC();Gx();const{buildShareData:g,validateShareData:b,isCurrentStateValid:x}=dq(),y=t||n||r,v=()=>{if(y)return"Updating...";if(i==="specific_users"){if(l.length===0&&u.length===0&&d.length===0)return"Select users to share with";const _=l.length+u.length+d.length;return _===0?"Select users to share with":l.length>0&&u.length>0?`Update access for ${_} user${_!==1?"s":""}`:u.length>0&&l.length===0&&d.length===0?`Remove access for ${u.length} user${u.length!==1?"s":""}`:l.length>0&&u.length===0&&d.length===0?`Share with ${l.length} user${l.length!==1?"s":""}`:d.length>0&&l.length===0&&u.length===0?`Update access for ${d.length} user${d.length!==1?"s":""}`:`Update access for ${_} user${_!==1?"s":""}`}else if(i==="groups"){if(f.length===0&&h.length===0&&m.length===0)return"Select groups to share with";const _=f.length+h.length+m.length;return _===0?"Select groups to share with":f.length>0&&h.length>0?`Update access for ${_} group${_!==1?"s":""}`:h.length>0&&f.length===0&&m.length===0?`Remove access for ${h.length} group${h.length!==1?"s":""}`:f.length>0&&h.length===0&&m.length===0?`Share with ${f.length} group${f.length!==1?"s":""}`:m.length>0&&f.length===0&&h.length===0?`Update access for ${m.length} group${m.length!==1?"s":""}`:`Update access for ${_} group${_!==1?"s":""}`}else if(i==="all_users"){if(!a||a.role==="NONE")return"Share with All Users";const _=a.role;return p===_?"Remove Access":"Update Access"}return"Share"},w=()=>y||!e?!0:!x,j=()=>{const _=g();_&&b(_)&&s(_)},S=()=>{const _=g();_&&b(_)&&s(_)},N=()=>{if(!a||a.role==="NONE"){const _=g();_&&b(_)&&s(_)}else{const _=a.role;if(p===_){const M=g();if(M&&b(M)){const T={...M,removeAccess:!0};s(T)}}else{const M=g();if(M&&b(M)){const T={...M,updateAccess:!0};s(T)}}}},E=()=>!a||a.role==="NONE"?"default":"destructive";return c.jsxs(os,{children:[c.jsxs(se,{variant:"outline",onClick:o,disabled:y,children:[c.jsx(St,{className:"mr-2 h-4 w-4"}),"Close"]}),i==="specific_users"&&c.jsx(c.Fragment,{children:(l.length>0||u.length>0||d.length>0)&&c.jsxs(se,{onClick:j,disabled:!e||y,variant:"default",children:[y?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Sh,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="groups"&&c.jsx(c.Fragment,{children:(f.length>0||h.length>0||m.length>0)&&c.jsxs(se,{onClick:S,disabled:!e||y,variant:"default",children:[y?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Sh,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="all_users"&&c.jsxs(se,{onClick:N,disabled:w(),variant:E(),children:[y?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Sh,{className:"mr-2 h-4 w-4"}),!y&&v()]})]})}function XSe({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllGroupsShare:l,onRemoveAccess:u}){const d=Kx(),f=Zx(),h=Xx();LU(),ku();const m=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:d,groupsToRemove:f,groupsToUpdate:h})},p=()=>d.length>0||f.length>0||h.length>0,g=()=>f.length>0&&d.length===0&&h.length===0?"Remove Access":h.length>0&&d.length===0&&f.length===0?"Update Access":"Share with Groups",b=n||r||s;return c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"text-sm text-muted-foreground",children:[d.length>0&&c.jsxs("span",{children:[d.length," groups selected"]}),f.length>0&&c.jsxs("span",{className:"ml-2 text-destructive",children:["• ",f.length," to remove"]}),h.length>0&&c.jsxs("span",{className:"ml-2 text-orange-600",children:["• ",h.length," to update"]})]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx(se,{variant:"outline",onClick:i,disabled:b,children:"Cancel"}),c.jsxs(se,{onClick:m,disabled:!p()||b,children:[b&&c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),g()]})]})]})}function Eo(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function Sl(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function QSe(e,t,n){const{resourceType:r,resourceId:s,shareMutation:o,removeMutation:i,existingShares:a,resetUserSelections:l}=t;if(s)switch(e.context){case"org-tab":if(e.mode==="allOrgUsers"){const u=Eo(r,s,[{scope:"org_users_only",role:e.orgWideRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="specificOrgUsers"){const{selectedUsers:u,usersToRemove:d,usersToUpdate:f}=e;if(u&&u.length>0){const h=Eo(r,s,u.map(m=>({scope:"specific_org_user",orgUserId:m.id,role:m.role})));o(h,{onSuccess:()=>{l()}})}if(d&&d.length>0){const h=Sl(r,s,d.map(m=>{var g,b;const p=(b=(g=a==null?void 0:a.shares)==null?void 0:g.specificOrgUsers)==null?void 0:b.find(x=>x.orgUserId===m);return{scope:"specific_org_user",orgUserId:m,role:(p==null?void 0:p.role)||"VIEWER"}}));i(h,{onSuccess:()=>{l()}})}f&&f.length>0&&f.forEach(h=>{const m=Eo(r,s,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);o(m,{onSuccess:()=>{l()}})})}break;case"tenant-tab":if(e.mode==="allTenants"){const u=Eo(r,s,[{scope:"all_tenants_only",role:e.allTenantsRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="allTenantUsers"){const u=Eo(r,s,[{scope:"all_tenant_users",tenantId:e.tenantId,role:e.tenantWideRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:d,usersToUpdate:f,tenantId:h}=e;if(d&&d.length>0){const m=Sl(r,s,d.map(p=>{var b,x;const g=(x=(b=a==null?void 0:a.shares)==null?void 0:b.specificTenantUsers)==null?void 0:x.find(y=>y.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,tenantId:h,role:(g==null?void 0:g.role)||"VIEWER"}}));i(m,{onSuccess:()=>{l()}})}if(f&&f.length>0&&f.forEach(m=>{const p=Eo(r,s,[{scope:"specific_tenant_user",tenantUserId:m.id,tenantId:h,role:m.newRole}]);o(p,{onSuccess:()=>{l()}})}),u&&u.length>0){const m=Eo(r,s,u.map(p=>({scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.role})));o(m,{onSuccess:()=>{l()}})}}break;case"tenant-dialog":if(e.mode==="allTenantUsers")if(e.removeAccess){const u=Sl(r,s,[{scope:"all_tenant_users",role:"VIEWER"}]);i(u,{onSuccess:()=>{l()}})}else if(e.updateAccess){const u=Eo(r,s,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:e.tenantWideRole}]);o(u,{onSuccess:()=>{l()}})}else{const u=Eo(r,s,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:e.tenantWideRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="specificTenantUsers"){const{selectedUsers:u,usersToRemove:d,usersToUpdate:f}=e;if(u&&u.length>0){const h=Eo(r,s,u.map(m=>({scope:"specific_tenant_user",tenantUserId:m.id,role:m.role})));o(h,{onSuccess:()=>{l()}})}if(d&&d.length>0){const h=Sl(r,s,d.map(m=>{var g,b;const p=(b=(g=a==null?void 0:a.shares)==null?void 0:g.specificTenantUsers)==null?void 0:b.find(x=>x.tenantUserId===m);return{scope:"specific_tenant_user",tenantUserId:m,role:(p==null?void 0:p.role)||"VIEWER"}}));i(h,{onSuccess:()=>{l()}})}f&&f.length>0&&f.forEach(h=>{const m=Eo(r,s,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);o(m,{onSuccess:()=>{l()}})})}break;case"group-share":if(e.mode==="specificGroups"){const{selectedGroups:u,groupsToRemove:d,groupsToUpdate:f}=e;if(u&&u.length>0){const h=Eo(r,s,u.map(m=>({scope:"group",groupId:m.id,role:m.role})));o(h,{onSuccess:()=>{var m;l(),(m=t.resetGroupSelections)==null||m.call(t),ze.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(d&&d.length>0){const h=Sl(r,s,d.map(m=>({scope:"group",groupId:m,role:"VIEWER"})));i(h,{onSuccess:()=>{var m;l(),(m=t.resetGroupSelections)==null||m.call(t),ze.success(`Removed access from ${d.length} group${d.length!==1?"s":""}`)}})}f&&f.length>0&&f.forEach(h=>{const m=Eo(r,s,[{scope:"group",groupId:h.id,role:h.newRole}]);o(m,{onSuccess:()=>{var p;l(),(p=t.resetGroupSelections)==null||p.call(t),ze.success("Updated access for group")}})})}break}}function JSe(e,t,n,r){var u,d,f,h,m,p;const{resourceType:s,resourceId:o,removeMutation:i,existingShares:a,resetUserSelections:l}=r;if(o)if(e.length>0){const g=Sl(s,o,e.map(b=>{var y,v;const x=(v=(y=a==null?void 0:a.shares)==null?void 0:y.specificTenantUsers)==null?void 0:v.find(w=>w.tenantUserId===b);return{scope:"specific_tenant_user",tenantUserId:b,role:(x==null?void 0:x.role)||"VIEWER"}}));i(g,{onSuccess:()=>{l()},onError:b=>{console.error("Remove access failed:",b)}})}else{const g=t==="tenant"&&n==="allTenants",b=t==="tenant"&&n==="allTenantUsers";if(g){const x=(d=(u=a==null?void 0:a.shares)==null?void 0:u.allTenantsOnly)==null?void 0:d[0];if(x){const y=Sl(s,o,[{scope:"all_tenants_only",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove all-tenants access failed:",v)}})}}else if(b){const x=(h=(f=a==null?void 0:a.shares)==null?void 0:f.tenantWide)==null?void 0:h[0];if(x){const y=Sl(s,o,[{scope:"all_tenant_users",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove all-tenant-users access failed:",v)}})}}else{const x=(p=(m=a==null?void 0:a.shares)==null?void 0:m.orgUsersOnly)==null?void 0:p[0];if(x){const y=Sl(s,o,[{scope:"org_users_only",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove org-wide access failed:",v)}})}}}}function eje(e,t,n){const r=rp(),s=np(),o=_D(),i=ku(),{currentUser:a}=Ps(),{existingShares:l}=xm({debouncedSearchQuery:"",resourceId:e||"",resourceType:Ut.DASHBOARD,userType:"tenant"}),u=C.useCallback(()=>{r.resetUserSelections()},[r]),d=C.useCallback(()=>{r.resetGroupSelections()},[r]),f=C.useCallback(m=>{if(!e)return;const p={resourceType:Ut.DASHBOARD,resourceId:e,shareMutation:t,removeMutation:n,existingShares:l,resetUserSelections:u,resetGroupSelections:d};QSe(m,p,a)},[e,t,n,l,u,d,a]),h=C.useCallback(()=>{if(!e)return;const m={resourceType:Ut.DASHBOARD,resourceId:e,removeMutation:n,existingShares:l,resetUserSelections:u};JSe(s,o||"",i||"",m)},[e,t,n,l,u,d,s,o,i]);return{handleShareSubmit:f,handleRemoveAccess:h}}function tje(e,t){return D.useReducer((n,r)=>t[n][r]??n,e)}var qD="ScrollArea",[fq]=Lr(qD),[nje,Si]=fq(qD),hq=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:s,scrollHideDelay:o=600,...i}=e,[a,l]=D.useState(null),[u,d]=D.useState(null),[f,h]=D.useState(null),[m,p]=D.useState(null),[g,b]=D.useState(null),[x,y]=D.useState(0),[v,w]=D.useState(0),[j,S]=D.useState(!1),[N,E]=D.useState(!1),_=ut(t,M=>l(M)),k=bu(s);return c.jsx(nje,{scope:n,type:r,dir:k,scrollHideDelay:o,scrollArea:a,viewport:u,onViewportChange:d,content:f,onContentChange:h,scrollbarX:m,onScrollbarXChange:p,scrollbarXEnabled:j,onScrollbarXEnabledChange:S,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:N,onScrollbarYEnabledChange:E,onCornerWidthChange:y,onCornerHeightChange:w,children:c.jsx(Ze.div,{dir:k,...i,ref:_,style:{position:"relative","--radix-scroll-area-corner-width":x+"px","--radix-scroll-area-corner-height":v+"px",...e.style}})})});hq.displayName=qD;var mq="ScrollAreaViewport",pq=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:s,...o}=e,i=Si(mq,n),a=D.useRef(null),l=ut(t,a,i.onViewportChange);return c.jsxs(c.Fragment,{children:[c.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:s}),c.jsx(Ze.div,{"data-radix-scroll-area-viewport":"",...o,ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c.jsx("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});pq.displayName=mq;var Xa="ScrollAreaScrollbar",YD=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Si(Xa,e.__scopeScrollArea),{onScrollbarXEnabledChange:o,onScrollbarYEnabledChange:i}=s,a=e.orientation==="horizontal";return D.useEffect(()=>(a?o(!0):i(!0),()=>{a?o(!1):i(!1)}),[a,o,i]),s.type==="hover"?c.jsx(rje,{...r,ref:t,forceMount:n}):s.type==="scroll"?c.jsx(sje,{...r,ref:t,forceMount:n}):s.type==="auto"?c.jsx(gq,{...r,ref:t,forceMount:n}):s.type==="always"?c.jsx(GD,{...r,ref:t}):null});YD.displayName=Xa;var rje=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Si(Xa,e.__scopeScrollArea),[o,i]=D.useState(!1);return D.useEffect(()=>{const a=s.scrollArea;let l=0;if(a){const u=()=>{window.clearTimeout(l),i(!0)},d=()=>{l=window.setTimeout(()=>i(!1),s.scrollHideDelay)};return a.addEventListener("pointerenter",u),a.addEventListener("pointerleave",d),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",u),a.removeEventListener("pointerleave",d)}}},[s.scrollArea,s.scrollHideDelay]),c.jsx(vr,{present:n||o,children:c.jsx(gq,{"data-state":o?"visible":"hidden",...r,ref:t})})}),sje=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=Si(Xa,e.__scopeScrollArea),o=e.orientation==="horizontal",i=HC(()=>l("SCROLL_END"),100),[a,l]=tje("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return D.useEffect(()=>{if(a==="idle"){const u=window.setTimeout(()=>l("HIDE"),s.scrollHideDelay);return()=>window.clearTimeout(u)}},[a,s.scrollHideDelay,l]),D.useEffect(()=>{const u=s.viewport,d=o?"scrollLeft":"scrollTop";if(u){let f=u[d];const h=()=>{const m=u[d];f!==m&&(l("SCROLL"),i()),f=m};return u.addEventListener("scroll",h),()=>u.removeEventListener("scroll",h)}},[s.viewport,o,l,i]),c.jsx(vr,{present:n||a!=="hidden",children:c.jsx(GD,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Ie(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:Ie(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),gq=D.forwardRef((e,t)=>{const n=Si(Xa,e.__scopeScrollArea),{forceMount:r,...s}=e,[o,i]=D.useState(!1),a=e.orientation==="horizontal",l=HC(()=>{if(n.viewport){const u=n.viewport.offsetWidth<n.viewport.scrollWidth,d=n.viewport.offsetHeight<n.viewport.scrollHeight;i(a?u:d)}},10);return ym(n.viewport,l),ym(n.content,l),c.jsx(vr,{present:r||o,children:c.jsx(GD,{"data-state":o?"visible":"hidden",...s,ref:t})})}),GD=D.forwardRef((e,t)=>{const{orientation:n="vertical",...r}=e,s=Si(Xa,e.__scopeScrollArea),o=D.useRef(null),i=D.useRef(0),[a,l]=D.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),u=wq(a.viewport,a.content),d={...r,sizes:a,onSizesChange:l,hasThumb:u>0&&u<1,onThumbChange:h=>o.current=h,onThumbPointerUp:()=>i.current=0,onThumbPointerDown:h=>i.current=h};function f(h,m){return uje(h,i.current,a,m)}return n==="horizontal"?c.jsx(oje,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const h=s.viewport.scrollLeft,m=V5(h,a,s.dir);o.current.style.transform=`translate3d(${m}px, 0, 0)`}},onWheelScroll:h=>{s.viewport&&(s.viewport.scrollLeft=h)},onDragScroll:h=>{s.viewport&&(s.viewport.scrollLeft=f(h,s.dir))}}):n==="vertical"?c.jsx(ije,{...d,ref:t,onThumbPositionChange:()=>{if(s.viewport&&o.current){const h=s.viewport.scrollTop,m=V5(h,a);o.current.style.transform=`translate3d(0, ${m}px, 0)`}},onWheelScroll:h=>{s.viewport&&(s.viewport.scrollTop=h)},onDragScroll:h=>{s.viewport&&(s.viewport.scrollTop=f(h))}}):null}),oje=D.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Si(Xa,e.__scopeScrollArea),[i,a]=D.useState(),l=D.useRef(null),u=ut(t,l,o.onScrollbarXChange);return D.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c.jsx(xq,{"data-orientation":"horizontal",...s,ref:u,sizes:n,style:{bottom:0,left:o.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:o.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":VC(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.x),onDragScroll:d=>e.onDragScroll(d.x),onWheelScroll:(d,f)=>{if(o.viewport){const h=o.viewport.scrollLeft+d.deltaX;e.onWheelScroll(h),Sq(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&o.viewport&&i&&r({content:o.viewport.scrollWidth,viewport:o.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:$w(i.paddingLeft),paddingEnd:$w(i.paddingRight)}})}})}),ije=D.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...s}=e,o=Si(Xa,e.__scopeScrollArea),[i,a]=D.useState(),l=D.useRef(null),u=ut(t,l,o.onScrollbarYChange);return D.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c.jsx(xq,{"data-orientation":"vertical",...s,ref:u,sizes:n,style:{top:0,right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":VC(n)+"px",...e.style},onThumbPointerDown:d=>e.onThumbPointerDown(d.y),onDragScroll:d=>e.onDragScroll(d.y),onWheelScroll:(d,f)=>{if(o.viewport){const h=o.viewport.scrollTop+d.deltaY;e.onWheelScroll(h),Sq(h,f)&&d.preventDefault()}},onResize:()=>{l.current&&o.viewport&&i&&r({content:o.viewport.scrollHeight,viewport:o.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:$w(i.paddingTop),paddingEnd:$w(i.paddingBottom)}})}})}),[aje,bq]=fq(Xa),xq=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:s,onThumbChange:o,onThumbPointerUp:i,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:u,onWheelScroll:d,onResize:f,...h}=e,m=Si(Xa,n),[p,g]=D.useState(null),b=ut(t,_=>g(_)),x=D.useRef(null),y=D.useRef(""),v=m.viewport,w=r.content-r.viewport,j=qr(d),S=qr(l),N=HC(f,10);function E(_){if(x.current){const k=_.clientX-x.current.left,M=_.clientY-x.current.top;u({x:k,y:M})}}return D.useEffect(()=>{const _=k=>{const M=k.target;(p==null?void 0:p.contains(M))&&j(k,w)};return document.addEventListener("wheel",_,{passive:!1}),()=>document.removeEventListener("wheel",_,{passive:!1})},[v,p,w,j]),D.useEffect(S,[r,S]),ym(p,N),ym(m.content,N),c.jsx(aje,{scope:n,scrollbar:p,hasThumb:s,onThumbChange:qr(o),onThumbPointerUp:qr(i),onThumbPositionChange:S,onThumbPointerDown:qr(a),children:c.jsx(Ze.div,{...h,ref:b,style:{position:"absolute",...h.style},onPointerDown:Ie(e.onPointerDown,_=>{_.button===0&&(_.target.setPointerCapture(_.pointerId),x.current=p.getBoundingClientRect(),y.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",m.viewport&&(m.viewport.style.scrollBehavior="auto"),E(_))}),onPointerMove:Ie(e.onPointerMove,E),onPointerUp:Ie(e.onPointerUp,_=>{const k=_.target;k.hasPointerCapture(_.pointerId)&&k.releasePointerCapture(_.pointerId),document.body.style.webkitUserSelect=y.current,m.viewport&&(m.viewport.style.scrollBehavior=""),x.current=null})})})}),Fw="ScrollAreaThumb",yq=D.forwardRef((e,t)=>{const{forceMount:n,...r}=e,s=bq(Fw,e.__scopeScrollArea);return c.jsx(vr,{present:n||s.hasThumb,children:c.jsx(lje,{ref:t,...r})})}),lje=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...s}=e,o=Si(Fw,n),i=bq(Fw,n),{onThumbPositionChange:a}=i,l=ut(t,f=>i.onThumbChange(f)),u=D.useRef(void 0),d=HC(()=>{u.current&&(u.current(),u.current=void 0)},100);return D.useEffect(()=>{const f=o.viewport;if(f){const h=()=>{if(d(),!u.current){const m=dje(f,a);u.current=m,a()}};return a(),f.addEventListener("scroll",h),()=>f.removeEventListener("scroll",h)}},[o.viewport,d,a]),c.jsx(Ze.div,{"data-state":i.hasThumb?"visible":"hidden",...s,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Ie(e.onPointerDownCapture,f=>{const m=f.target.getBoundingClientRect(),p=f.clientX-m.left,g=f.clientY-m.top;i.onThumbPointerDown({x:p,y:g})}),onPointerUp:Ie(e.onPointerUp,i.onThumbPointerUp)})});yq.displayName=Fw;var KD="ScrollAreaCorner",vq=D.forwardRef((e,t)=>{const n=Si(KD,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?c.jsx(cje,{...e,ref:t}):null});vq.displayName=KD;var cje=D.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,s=Si(KD,n),[o,i]=D.useState(0),[a,l]=D.useState(0),u=!!(o&&a);return ym(s.scrollbarX,()=>{var f;const d=((f=s.scrollbarX)==null?void 0:f.offsetHeight)||0;s.onCornerHeightChange(d),l(d)}),ym(s.scrollbarY,()=>{var f;const d=((f=s.scrollbarY)==null?void 0:f.offsetWidth)||0;s.onCornerWidthChange(d),i(d)}),u?c.jsx(Ze.div,{...r,ref:t,style:{width:o,height:a,position:"absolute",right:s.dir==="ltr"?0:void 0,left:s.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function $w(e){return e?parseInt(e,10):0}function wq(e,t){const n=e/t;return isNaN(n)?0:n}function VC(e){const t=wq(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function uje(e,t,n,r="ltr"){const s=VC(n),o=s/2,i=t||o,a=s-i,l=n.scrollbar.paddingStart+i,u=n.scrollbar.size-n.scrollbar.paddingEnd-a,d=n.content-n.viewport,f=r==="ltr"?[0,d]:[d*-1,0];return Cq([l,u],f)(e)}function V5(e,t,n="ltr"){const r=VC(t),s=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,o=t.scrollbar.size-s,i=t.content-t.viewport,a=o-r,l=n==="ltr"?[0,i]:[i*-1,0],u=Ib(e,l);return Cq([0,i],[0,a])(u)}function Cq(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 Sq(e,t){return e>0&&e<t}var dje=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function s(){const o={left:e.scrollLeft,top:e.scrollTop},i=n.left!==o.left,a=n.top!==o.top;(i||a)&&t(),n=o,r=window.requestAnimationFrame(s)}(),()=>window.cancelAnimationFrame(r)};function HC(e,t){const n=qr(e),r=D.useRef(0);return D.useEffect(()=>()=>window.clearTimeout(r.current),[]),D.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function ym(e,t){const n=qr(t);Yr(()=>{let r=0;if(e){const s=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return s.observe(e),()=>{window.cancelAnimationFrame(r),s.unobserve(e)}}},[e,n])}var UC=hq,jq=pq,Nq=vq;const ro=D.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(UC,{ref:r,className:X("relative overflow-hidden",e),...n,children:[c.jsx(jq,{className:"h-full w-full rounded-[inherit]",children:t}),c.jsx(bi,{}),c.jsx(Nq,{})]}));ro.displayName=UC.displayName;const bi=D.forwardRef(({className:e,orientation:t="vertical",...n},r)=>c.jsx(YD,{ref:r,orientation:t,className:X("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:c.jsx(yq,{className:"relative flex-1 rounded-full bg-border"})}));bi.displayName=YD.displayName;function fje({existingShares:e,isLoading:t}){var p,g,b,x,y,v,w,j,S,N,E,_,k,M,T,P,O,I,$,V,W,L;const[n,r]=C.useState(new Set(["org-users","tenant-users","groups"])),[s,o]=C.useState(new Set),i=R=>{r(z=>{const F=new Set(z);return F.has(R)?F.delete(R):F.add(R),F})},a=R=>{o(z=>{const F=new Set(z);return F.has(R)?F.delete(R):F.add(R),F})},l=C.useMemo(()=>{var F;const R=((F=e==null?void 0:e.shares)==null?void 0:F.specificTenantUsers)||[],z={};return R.forEach(A=>{var Y;const H=A.tenantId||"unknown",B=((Y=A.tenant)==null?void 0:Y.name)||"Unknown Tenant";z[H]||(z[H]={tenantName:B,users:[]}),z[H].users.push(A)}),z},[e]),u=(((g=(p=e==null?void 0:e.shares)==null?void 0:p.specificOrgUsers)==null?void 0:g.length)||0)+(((x=(b=e==null?void 0:e.shares)==null?void 0:b.orgUsersOnly)==null?void 0:x.length)||0),d=(((v=(y=e==null?void 0:e.shares)==null?void 0:y.specificTenantUsers)==null?void 0:v.length)||0)+(((j=(w=e==null?void 0:e.shares)==null?void 0:w.tenantWide)==null?void 0:j.length)||0)+(((N=(S=e==null?void 0:e.shares)==null?void 0:S.allTenantsOnly)==null?void 0:N.length)||0),f=((_=(E=e==null?void 0:e.shares)==null?void 0:E.specificGroups)==null?void 0:_.length)||0,h=u+d+f,m=R=>{switch(R){case"EDITOR":return"bg-blue-100 text-blue-800 border-blue-200";case"CONTRIBUTOR":return"bg-purple-100 text-purple-800 border-purple-200";default:return"bg-gray-100 text-gray-800 border-gray-200"}};return c.jsxs(ID,{children:[c.jsx(RD,{asChild:!0,children:c.jsxs(se,{variant:"ghost",size:"sm",className:"gap-2",children:[c.jsx(tu,{className:"h-4 w-4"}),"Access Overview",c.jsx(Ve,{variant:"secondary",className:"ml-1",children:h})]})}),c.jsxs(sp,{align:"end",sideOffset:8,className:"z-[100] w-[400px] rounded-md border bg-popover p-0 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",children:[c.jsxs("div",{className:"border-b p-3",children:[c.jsx("h4",{className:"text-sm font-semibold",children:"Current Access"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Users and groups with access to this resource"})]}),t?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(xn,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):c.jsx(ro,{className:"h-[400px]",children:c.jsxs("div",{className:"space-y-2 p-3 pr-4",children:[c.jsxs(bo,{open:n.has("org-users"),onOpenChange:()=>i("org-users"),children:[c.jsxs(xo,{className:"flex w-full items-center gap-2 rounded-md p-2 hover:bg-muted/50",children:[n.has("org-users")?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx(ql,{className:"h-4 w-4 text-blue-500"}),c.jsx("span",{className:"text-sm font-medium",children:"Organization Users"}),c.jsx(Ve,{variant:"secondary",className:"ml-auto text-xs",children:u})]}),c.jsx(yo,{className:"pl-6",children:c.jsxs("div",{className:"space-y-1 pt-1",children:[(M=(k=e==null?void 0:e.shares)==null?void 0:k.orgUsersOnly)==null?void 0:M.map(R=>c.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted/30 p-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Pr,{className:"h-3 w-3 text-muted-foreground"}),c.jsx("span",{className:"text-xs",children:"All Org Users"})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)),(P=(T=e==null?void 0:e.shares)==null?void 0:T.specificOrgUsers)==null?void 0:P.map(R=>{var z,F;return c.jsxs("div",{className:"flex items-center justify-between rounded-md p-2 hover:bg-muted/30",children:[c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-xs font-medium",children:((z=R.user)==null?void 0:z.name)||"Unknown User"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:(F=R.user)==null?void 0:F.email})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)}),u===0&&c.jsx("p",{className:"py-2 text-xs text-muted-foreground",children:"No organization users have access"})]})})]}),c.jsxs(bo,{open:n.has("tenant-users"),onOpenChange:()=>i("tenant-users"),children:[c.jsxs(xo,{className:"flex w-full items-center gap-2 rounded-md p-2 hover:bg-muted/50",children:[n.has("tenant-users")?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx(hb,{className:"h-4 w-4 text-green-500"}),c.jsx("span",{className:"text-sm font-medium",children:"Tenant Users"}),c.jsx(Ve,{variant:"secondary",className:"ml-auto text-xs",children:d})]}),c.jsx(yo,{className:"pl-6",children:c.jsxs("div",{className:"space-y-2 pt-1",children:[(I=(O=e==null?void 0:e.shares)==null?void 0:O.allTenantsOnly)==null?void 0:I.map(R=>c.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted/30 p-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Pr,{className:"h-3 w-3 text-muted-foreground"}),c.jsx("span",{className:"text-xs",children:"All Tenants"})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)),(V=($=e==null?void 0:e.shares)==null?void 0:$.tenantWide)==null?void 0:V.map(R=>c.jsxs("div",{className:"flex items-center justify-between rounded-md bg-muted/30 p-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Pr,{className:"h-3 w-3 text-muted-foreground"}),c.jsx("span",{className:"text-xs",children:"All Tenant Users"})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)),Object.entries(l).map(([R,{tenantName:z,users:F}])=>c.jsxs(bo,{open:s.has(R),onOpenChange:()=>a(R),children:[c.jsxs(xo,{className:"flex w-full items-center gap-2 rounded-md border bg-muted/20 p-2 hover:bg-muted/40",children:[s.has(R)?c.jsx(kr,{className:"h-3 w-3"}):c.jsx(ns,{className:"h-3 w-3"}),c.jsx(hb,{className:"h-3 w-3 text-muted-foreground"}),c.jsx("span",{className:"text-xs font-medium",children:z}),c.jsx(Ve,{variant:"outline",className:"ml-auto text-xs",children:F.length})]}),c.jsx(yo,{className:"pl-4",children:c.jsx("div",{className:"space-y-1 pt-1",children:F.map(A=>{var H,B;return c.jsxs("div",{className:"flex items-center justify-between rounded-md p-2 hover:bg-muted/30",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Kl,{className:"h-3 w-3 text-muted-foreground"}),c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-xs",children:((H=A.user)==null?void 0:H.name)||"Unknown User"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:(B=A.user)==null?void 0:B.email})]})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(A.role)}`,children:A.role})]},A.id)})})})]},R)),d===0&&c.jsx("p",{className:"py-2 text-xs text-muted-foreground",children:"No tenant users have access"})]})})]}),c.jsxs(bo,{open:n.has("groups"),onOpenChange:()=>i("groups"),children:[c.jsxs(xo,{className:"flex w-full items-center gap-2 rounded-md p-2 hover:bg-muted/50",children:[n.has("groups")?c.jsx(kr,{className:"h-4 w-4"}):c.jsx(ns,{className:"h-4 w-4"}),c.jsx(Pr,{className:"h-4 w-4 text-purple-500"}),c.jsx("span",{className:"text-sm font-medium",children:"Groups"}),c.jsx(Ve,{variant:"secondary",className:"ml-auto text-xs",children:f})]}),c.jsx(yo,{className:"pl-6",children:c.jsxs("div",{className:"space-y-1 pt-1",children:[(L=(W=e==null?void 0:e.shares)==null?void 0:W.specificGroups)==null?void 0:L.map(R=>{var z,F;return c.jsxs("div",{className:"flex items-center justify-between rounded-md p-2 hover:bg-muted/30",children:[c.jsxs("div",{className:"flex flex-col",children:[c.jsx("span",{className:"text-xs font-medium",children:((z=R.group)==null?void 0:z.name)||"Unknown Group"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:((F=R.group)==null?void 0:F.type)==="ORG_GROUP"?"Organization Group":"Tenant Group"})]}),c.jsx(Ve,{variant:"outline",className:`text-xs ${m(R.role)}`,children:R.role})]},R.id)}),f===0&&c.jsx("p",{className:"py-2 text-xs text-muted-foreground",children:"No groups have access"})]})})]})]})})]})]})}function kq({resource:e,resourceType:t,onClose:n,onShareSuccess:r,onRemoveSuccess:s}){var O,I,$,V,W,L,R,z;const{currentUser:o}=Ps(),[i,a]=C.useState("specific_users"),[l,u]=C.useState("specific_users"),[d,f]=C.useState("specific_groups"),h=rp(),m=_D(),p=ku(),g=A7(),b=P7(),{handleShareSubmit:x,handleRemoveAccess:y}=eje(e.id,(F,A)=>{g.mutate(F,{...A,onSuccess:()=>{var H;(H=A==null?void 0:A.onSuccess)==null||H.call(A),r==null||r()}})},(F,A)=>{b.mutate(F,{...A,onSuccess:()=>{var H;(H=A==null?void 0:A.onSuccess)==null||H.call(A),s==null||s()}})}),v=g.isPending,w=b.isPending,j=g.isPending,{existingShares:S}=xm({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant"}),{existingShares:N,isLoadingShares:E}=xm({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"organization"}),_=(I=(O=S==null?void 0:S.shares)==null?void 0:O.tenantWide)==null?void 0:I[0],k=(V=($=N==null?void 0:N.shares)==null?void 0:$.orgUsersOnly)==null?void 0:V[0],M=()=>{if(m==="org")return l;switch(p){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},T=C.useCallback(()=>{h.resetShareState(),n()},[h,n]),P=(o==null?void 0:o.type)==="organization";return c.jsx(Gr,{open:!0,onOpenChange:T,children:c.jsxs(zr,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[c.jsxs(Br,{children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(Vr,{children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Sh,{className:"h-5 w-5"}),' Share "',e==null?void 0:e.title,'"']})}),P&&c.jsx(fje,{existingShares:N,isLoading:E})]}),c.jsx(is,{children:P?"Share this resource with org users or tenant users.":"Share this resource with other users in your tenant."})]}),P?c.jsxs(Os,{value:m,onValueChange:F=>{const A=F;h.setSelectedTab(A),h.resetUserSelections(),h.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[c.jsxs(ys,{className:"mb-2 grid w-full grid-cols-3",children:[c.jsx(nn,{value:"org",children:"Org Users"}),c.jsx(nn,{value:"tenant",children:"Tenant Users"}),c.jsx(nn,{value:"groups",children:"Groups"})]}),c.jsx(pr,{value:"org",className:"mt-0 min-h-0 flex-1",children:c.jsx("div",{className:"max-h-[calc(80vh-280px)] overflow-y-auto",children:c.jsx(uSe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:u,isSharing:v,isUpdating:j,isRemoving:w})})}),c.jsx(pr,{value:"tenant",className:"mt-0 min-h-0 flex-1",children:c.jsx("div",{className:"max-h-[calc(80vh-280px)] overflow-y-auto",children:c.jsx(z5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:F=>a(F),isSharing:v,isUpdating:j,isRemoving:w})})}),c.jsx(pr,{value:"groups",className:"mt-0 min-h-0 flex-1",children:c.jsx("div",{className:"max-h-[calc(80vh-280px)] overflow-y-auto",children:c.jsx(KSe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:f,isSharing:v,isUpdating:j,isRemoving:w})})})]}):c.jsx("div",{className:"mb-4 min-h-0 flex-1",children:c.jsx("div",{className:"max-h-[calc(80vh-220px)] overflow-y-auto",children:c.jsx(z5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:F=>a(F),isSharing:v,isUpdating:j,isRemoving:w})})}),c.jsx("div",{className:"mt-auto flex-shrink-0",children:P?m==="org"?c.jsx(B5,{resource:e,existingShares:N,isSharing:v,isRemoving:w,isUpdating:j,onShare:x,onClose:n,shareTabType:l,currentAllUsersShare:k,onRemoveAccess:y}):m==="tenant"?c.jsx(B5,{resource:e,existingShares:S,isSharing:v,isRemoving:w,isUpdating:j,onShare:x,onClose:n,shareTabType:M(),currentAllUsersShare:_,onRemoveAccess:y}):c.jsx(XSe,{resource:e,existingShares:N,isSharing:v,isRemoving:w,isUpdating:j,onShare:x,onClose:n,shareTabType:d,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(L=(W=N==null?void 0:N.shares)==null?void 0:W.allOrgGroups)==null?void 0:L[0]:(z=(R=S==null?void 0:S.shares)==null?void 0:R.allTenantGroups)==null?void 0:z[0],onRemoveAccess:y}):c.jsx(ZSe,{resource:e,isSharing:v,isRemoving:w,isUpdating:j,onShare:x,onClose:n,shareTabType:i,currentAllUsersShare:_,onRemoveAccess:y})})]})})}const mn=D.forwardRef(({className:e,type:t,...n},r)=>c.jsx("input",{type:t,className:X("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-inset ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,...n}));mn.displayName="Input";function Eq({open:e,resourceLabel:t,initialTitle:n,initialDescription:r="",onClose:s,onSave:o,isSaving:i=!1}){const[a,l]=C.useState(n),[u,d]=C.useState(r??"");C.useEffect(()=>{e&&(l(n),d(r??""))},[e,n,r]);const f=h=>{h.preventDefault();const m=a.trim();m&&o({title:m,description:u.trim()})};return c.jsx(Gr,{open:e,onOpenChange:h=>h?null:s(),children:c.jsx(zr,{className:"sm:max-w-md",children:c.jsxs("form",{onSubmit:f,className:"space-y-4",children:[c.jsxs(Br,{children:[c.jsxs(Vr,{children:["Edit ",t]}),c.jsxs(is,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"resource-title",children:"Title"}),c.jsx(mn,{id:"resource-title",value:a,onChange:h=>l(h.target.value),placeholder:`Enter ${t.toLowerCase()} title`,autoFocus:!0})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"resource-description",children:"Description"}),c.jsx(vu,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),c.jsxs(os,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[c.jsx(se,{type:"button",variant:"outline",onClick:s,disabled:i,children:"Cancel"}),c.jsx(se,{type:"submit",disabled:i||!a.trim(),children:i?"Saving...":"Save changes"})]})]})})})}function hje({onDashboardSelect:e}){var G,Z;const{authToken:t}=Xe(),[n,r]=C.useState(!1),[s,o]=C.useState(!1),[i,a]=C.useState(null),[l,u]=C.useState(!1),[d,f]=C.useState(null),[h,m]=C.useState(null),[p,g]=C.useState(null),{data:b}=cB(),x=((G=b==null?void 0:b.preference)==null?void 0:G.defaultDashboardId)||null,y=hs(Q=>Q.actions.selectDashboard),{userContext:v}=Ps(),w=((Z=v==null?void 0:v.permissions)==null?void 0:Z.canCreateDashboard)??!1,{onCreateSuccess:j}=z7({onDashboardSelect:e}),{resources:S,isLoading:N,isError:E,createResource:_,updateResource:k,deleteResource:M,duplicateResource:T,isCreating:P,isUpdating:O,isDeleting:I,isDuplicating:$,refetch:V}=L7(()=>{u(!1),f(null)},Q=>{r(!1),j(Q,V)}),{startUpdating:W,stopUpdating:L,isUpdating:R}=$7(),z=Q=>{const K=S.find(te=>te.id===Q);K&&(y(K),e==null||e(Q))},F=Q=>{_({title:Q.title,description:Q.description,isPrivate:!1})},A=Q=>{f(Q),u(!0)},H=()=>{d&&M(d.id)},B=Q=>{m(Q),T(Q,{onSettled:()=>m(null)})},Y=(Q,K,te)=>{var Ce;const le=Object.fromEntries(Object.entries(K).filter(([,ge])=>ge!==void 0));if(Object.keys(le).length===0){(Ce=te==null?void 0:te.onSuccess)==null||Ce.call(te);return}const de=Object.keys(le),ce=de.length===1?de[0]:void 0;W(Q,ce),k({resourceId:Q,data:le},{onSuccess:()=>{var ge;L(Q,ce),(ge=te==null?void 0:te.onSuccess)==null||ge.call(te)},onError:()=>{var ge;L(Q,ce),(ge=te==null?void 0:te.onError)==null||ge.call(te)}})},q=Q=>{a(Q),o(!0)},U=Q=>new Date(Q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return t?N?c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"flex flex-col items-center gap-3",children:[c.jsx(xn,{className:"h-8 w-8 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading dashboards..."})]})}):E?c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"text-center",children:[c.jsx(Yl,{className:"mx-auto mb-4 h-12 w-12 text-destructive"}),c.jsx("h2",{className:"mb-2 text-lg font-semibold",children:"Error Loading Dashboards"}),c.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Unable to fetch your dashboards. Please try again."}),c.jsx(se,{onClick:()=>window.location.reload(),children:"Retry"})]})}):c.jsxs("div",{"data-content-type":"dashboard-hub",className:"flex h-full grow flex-col",children:[c.jsx("div",{className:"border-b bg-background px-6 py-8 lg:px-8",children:c.jsx("div",{className:"mx-auto max-w-7xl",children:c.jsxs("div",{className:"flex items-start justify-between",children:[c.jsxs("div",{children:[c.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Welcome to your analytics workspace"}),c.jsx("p",{className:"mt-2 text-muted-foreground",children:"Get started with existing dashboards or create a new one tailored to your needs"}),S.length>0&&w&&c.jsx("div",{className:"mt-6 flex gap-3",children:c.jsxs(se,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(Tr,{className:"h-4 w-4"}),"Create New Dashboard"]})})]}),S.length>0&&c.jsxs("div",{className:"rounded-md bg-orange-500 px-3 py-1 text-sm font-medium text-white",children:[S.length," dashboard",S.length!==1?"s":""]})]})})}),c.jsx("div",{className:"flex-1 overflow-y-auto bg-muted/30 px-6 py-6 lg:px-8",children:c.jsx("div",{className:"mx-auto max-w-7xl",children:S.length===0?c.jsx("div",{className:"flex h-[400px] items-center justify-center rounded-lg border-2 border-dashed",children:c.jsxs("div",{className:"text-center",children:[c.jsx(qT,{className:"mx-auto mb-4 h-12 w-12 text-muted-foreground"}),c.jsx("h3",{className:"mb-2 text-lg font-semibold",children:"No dashboards yet"}),c.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:w?"Create your first dashboard to get started with analytics":"No dashboards have been shared with you yet"}),w&&c.jsxs(se,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(Tr,{className:"h-4 w-4"}),"Create Dashboard"]})]})}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"mb-4 flex items-center justify-between",children:c.jsx("h2",{className:"text-lg font-semibold",children:"Your Dashboards"})}),c.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:S.map(Q=>c.jsx(jde,{dashboard:Q,isDefault:Q.id===x,onView:z,isDeleting:I&&(d==null?void 0:d.id)===Q.id,isDuplicating:h===Q.id,onEditDetails:g,onDeleteClick:A,onDuplicateDashboard:B,onShareDashboard:q,formatDate:U},Q.id))})]})})}),c.jsx(lB,{open:n,onOpenChange:r,onSubmit:F,isCreating:P}),p&&c.jsx(Eq,{open:!!p,resourceLabel:"Dashboard",initialTitle:p.title||"",initialDescription:p.description||"",onClose:()=>g(null),onSave:Q=>{Y(p.id,Q,{onSuccess:()=>{g(null)}})},isSaving:R(p.id)}),c.jsx(Um,{open:l,onOpenChange:u,children:c.jsxs(Sf,{children:[c.jsxs(jf,{children:[c.jsx(kf,{children:"Delete Dashboard?"}),c.jsxs(Ef,{children:['Are you sure you want to delete "',d==null?void 0:d.title,'"? This action cannot be undone.']})]}),c.jsxs(Nf,{children:[c.jsx(Tf,{disabled:I,children:"Cancel"}),c.jsx(_f,{onClick:H,disabled:I,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:I?c.jsxs(c.Fragment,{children:[c.jsx(xn,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete"})]})]})}),i&&s&&c.jsx(kq,{resource:i,resourceType:Ut.DASHBOARD,onClose:()=>{o(!1),a(null)}})]}):c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"text-center",children:[c.jsx(Yl,{className:"mx-auto mb-4 h-12 w-12 text-muted-foreground"}),c.jsx("h2",{className:"mb-2 text-lg font-semibold",children:"Authentication Required"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Please provide authentication to view dashboards"})]})})}const Od=oa()(nz(e=>({panels:{dashboard:{isOpen:!1,container:null},editor:{isOpen:!1,container:null}},fullscreen:null,setPanelOpen:(t,n)=>e(r=>r.panels[t].isOpen===n?r:{panels:{...r.panels,[t]:{...r.panels[t],isOpen:n}},fullscreen:!n&&r.fullscreen===t?null:r.fullscreen}),setFullscreen:t=>e(n=>n.fullscreen===t?n:{fullscreen:t}),setContainer:(t,n)=>e(r=>r.panels[t].container===n?r:{panels:{...r.panels,[t]:{...r.panels[t],container:n}}})}),{name:"assistant-layout-store",partialize:e=>({panels:{dashboard:{isOpen:e.panels.dashboard.isOpen,container:null},editor:{isOpen:e.panels.editor.isOpen,container:null}},fullscreen:e.fullscreen})})),_q=e=>Od(t=>t.panels[e]),Tq=()=>Od(e=>e.fullscreen),Mq=e=>Od(t=>t.panels[e].container??null);function Dq(e){return Array.isArray(e)?e.reduce((t,n)=>n.role!=="assistant"?(t.push(n),t):n.parts.some(s=>{var o;return!!(s.type==="reasoning"&&s.state==="streaming"||s.type==="text"&&s.state==="streaming"||(o=s.type)!=null&&o.startsWith("tool-")&&s.state==="input-streaming")})?(console.log("Removing aborted assistant message:",n.id),t):(t.push(n),t),[]):e}function mje(e){const{selectedEntities:t}=e,n=t.map(r=>({...r,qualifiedEntityName:gh(r)}));return{...e,selectedEntities:n}}const H5={selectedEntities:[]},la=oa()(Im((e,t)=>({currentAIContext:H5,activeAssistantType:null,reasoningEffort:"low",showReasoning:!1,messageQueues:{dashboard:[],editor:[]},fileAttachments:{dashboard:[],editor:[]},uploadProgress:new Map,actions:{setCurrentAIContext:n=>{e(r=>{r.currentAIContext=mje(n)})},setActiveAssistantType:n=>{e(r=>{r.activeAssistantType=n})},updateSelectedEntities:n=>{e(r=>{r.currentAIContext.selectedEntities=n})},clearAIContext:()=>{e(n=>{n.currentAIContext=H5})},mergeAIContext:n=>{e(r=>{r.currentAIContext={...r.currentAIContext,...n}})},setReasoningEffort:n=>{e(r=>{r.reasoningEffort=n})},setShowReasoning:n=>{e(r=>{r.showReasoning=n})},queueMessage:(n,r,s)=>{e(o=>{o.messageQueues[n].push({id:crypto.randomUUID(),text:r,timestamp:Date.now(),fileAttachments:s})})},dequeueMessage:n=>{if(t().messageQueues[n].length===0)return;let s;return e(o=>{const i=o.messageQueues[n].shift();i&&(s={id:i.id,text:i.text,timestamp:i.timestamp})}),s},removeFromQueue:(n,r)=>{e(s=>{s.messageQueues[n]=s.messageQueues[n].filter(o=>o.id!==r)})},clearQueue:n=>{e(r=>{r.messageQueues[n]=[]})},addFileAttachment:(n,r)=>{e(s=>{s.fileAttachments[n].push(r)})},removeFileAttachment:(n,r)=>{e(s=>{s.fileAttachments[n]=s.fileAttachments[n].filter(o=>o.id!==r)})},clearFileAttachments:n=>{e(r=>{r.fileAttachments[n]=[]})},updateUploadProgress:(n,r)=>{e(s=>{s.uploadProgress.set(n,r)})},getFileAttachments:n=>t().fileAttachments[n]}}))),dp=()=>la(e=>e.currentAIContext),ZD=()=>la(e=>e.activeAssistantType),pje=()=>la(e=>e.reasoningEffort),gje=()=>la(e=>e.showReasoning),WC=()=>la(e=>e.actions),Iq=e=>la(t=>t.messageQueues[e]),fp=()=>la(bx(e=>({queueMessage:e.actions.queueMessage,dequeueMessage:e.actions.dequeueMessage,removeFromQueue:e.actions.removeFromQueue,clearQueue:e.actions.clearQueue}))),XD=e=>la(t=>t.fileAttachments[e]),QD=()=>la(bx(e=>({addFileAttachment:e.actions.addFileAttachment,removeFileAttachment:e.actions.removeFileAttachment,clearFileAttachments:e.actions.clearFileAttachments,updateUploadProgress:e.actions.updateUploadProgress,getFileAttachments:e.actions.getFileAttachments})));function Rq(){const{tokenProps:e,id:t}=Xe(),n=hs(s=>s.selectedDashboard);return hs(s=>s.showHub)?!1:!!(n!=null&&n.id||t||e!=null&&e.dashboard_id)}function JD({className:e,customStyle:t,onSave:n,onEvent:r,LoadingComponent:s,ErrorComponent:o,onChartElementClicked:i,id:a,authToken:l,currentTheme:u,version:d,customCards:f,showAssistant:h,defaultFilterValues:m,onFilterValuesChange:p,selectedSheetId:g,eventHandlers:b,type:x="dashboard",cardId:y,dashboardId:v,...w}){const{placeholders:j,tokenProps:S,id:N}=Xe();hs(P=>P.selectedDashboard);const E=J(P=>P.themeStyle),_=J(P=>P.isSessionExpired),{isLoading:k,isError:M}=Ooe({customStyle:t,currentTheme:u,onSave:n,onEvent:r,defaultFilterValues:m,onFilterValuesChange:p,selectedSheetId:g}),T=Rq();return l&&!T&&!k?c.jsx(hje,{}):k||!l?(r==null||r({type:"info",message:"Loading dashboard"}),s?c.jsx(s,{message:"loading"}):c.jsx("div",{className:"flex items-center gap-3",children:c.jsx(Xs,{className:"h-1 w-full dark:h-[2px]"})})):M?(r==null||r({type:"error",message:"Error fetching dashboard"}),o?(console.log("Error fetching dashboard"),c.jsx(o,{})):c.jsx("div",{children:"Error"})):_?(r==null||r({type:"error",message:"Session Expired"}),j!=null&&j.SessionExpired?c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsx("div",{children:j.SessionExpired})}):c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsxs("div",{className:"space-y-4 rounded-md border border-muted p-10",children:[c.jsx(Xi,{children:"Session Expired"}),c.jsx("p",{className:"text-muted-foreground",children:"Please refresh your page to continue"})]})})):c.jsx("div",{className:X("isolate flex grow flex-col",{"h-full":x==="visual"},E==null?void 0:E.dashboardPanel,e),style:{},"data-role":"semaphor-container",...w})}var Aq={exports:{}},ty={},VE={exports:{}};(function(e,t){(function(n,r){r(t)})(kl,function(n){function r(U){return function(Z,Q,K,te,le,de,ce){return U(Z,Q,ce)}}function s(U){return function(Z,Q,K,te){if(!Z||!Q||typeof Z!="object"||typeof Q!="object")return U(Z,Q,K,te);var le=te.get(Z),de=te.get(Q);if(le&&de)return le===Q&&de===Z;te.set(Z,Q),te.set(Q,Z);var ce=U(Z,Q,K,te);return te.delete(Z),te.delete(Q),ce}}function o(U,G){var Z={};for(var Q in U)Z[Q]=U[Q];for(var Q in G)Z[Q]=G[Q];return Z}function i(U){return U.constructor===Object||U.constructor==null}function a(U){return typeof U.then=="function"}function l(U,G){return U===G||U!==U&&G!==G}var u="[object Arguments]",d="[object Boolean]",f="[object Date]",h="[object RegExp]",m="[object Map]",p="[object Number]",g="[object Object]",b="[object Set]",x="[object String]",y=Object.prototype.toString;function v(U){var G=U.areArraysEqual,Z=U.areDatesEqual,Q=U.areMapsEqual,K=U.areObjectsEqual,te=U.areRegExpsEqual,le=U.areSetsEqual,de=U.createIsNestedEqual,ce=de(Ce);function Ce(ge,he,me){if(ge===he)return!0;if(!ge||!he||typeof ge!="object"||typeof he!="object")return ge!==ge&&he!==he;if(i(ge)&&i(he))return K(ge,he,ce,me);var oe=Array.isArray(ge),Ne=Array.isArray(he);if(oe||Ne)return oe===Ne&&G(ge,he,ce,me);var fe=y.call(ge);return fe!==y.call(he)?!1:fe===f?Z(ge,he,ce,me):fe===h?te(ge,he,ce,me):fe===m?Q(ge,he,ce,me):fe===b?le(ge,he,ce,me):fe===g||fe===u?a(ge)||a(he)?!1:K(ge,he,ce,me):fe===d||fe===p||fe===x?l(ge.valueOf(),he.valueOf()):!1}return Ce}function w(U,G,Z,Q){var K=U.length;if(G.length!==K)return!1;for(;K-- >0;)if(!Z(U[K],G[K],K,K,U,G,Q))return!1;return!0}var j=s(w);function S(U,G){return l(U.valueOf(),G.valueOf())}function N(U,G,Z,Q){var K=U.size===G.size;if(!K)return!1;if(!U.size)return!0;var te={},le=0;return U.forEach(function(de,ce){if(K){var Ce=!1,ge=0;G.forEach(function(he,me){!Ce&&!te[ge]&&(Ce=Z(ce,me,le,ge,U,G,Q)&&Z(de,he,ce,me,U,G,Q))&&(te[ge]=!0),ge++}),le++,K=Ce}}),K}var E=s(N),_="_owner",k=Object.prototype.hasOwnProperty;function M(U,G,Z,Q){var K=Object.keys(U),te=K.length;if(Object.keys(G).length!==te)return!1;for(var le;te-- >0;){if(le=K[te],le===_){var de=!!U.$$typeof,ce=!!G.$$typeof;if((de||ce)&&de!==ce)return!1}if(!k.call(G,le)||!Z(U[le],G[le],le,le,U,G,Q))return!1}return!0}var T=s(M);function P(U,G){return U.source===G.source&&U.flags===G.flags}function O(U,G,Z,Q){var K=U.size===G.size;if(!K)return!1;if(!U.size)return!0;var te={};return U.forEach(function(le,de){if(K){var ce=!1,Ce=0;G.forEach(function(ge,he){!ce&&!te[Ce]&&(ce=Z(le,ge,de,he,U,G,Q))&&(te[Ce]=!0),Ce++}),K=ce}}),K}var I=s(O),$=Object.freeze({areArraysEqual:w,areDatesEqual:S,areMapsEqual:N,areObjectsEqual:M,areRegExpsEqual:P,areSetsEqual:O,createIsNestedEqual:r}),V=Object.freeze({areArraysEqual:j,areDatesEqual:S,areMapsEqual:E,areObjectsEqual:T,areRegExpsEqual:P,areSetsEqual:I,createIsNestedEqual:r}),W=v($);function L(U,G){return W(U,G,void 0)}var R=v(o($,{createIsNestedEqual:function(){return l}}));function z(U,G){return R(U,G,void 0)}var F=v(V);function A(U,G){return F(U,G,new WeakMap)}var H=v(o(V,{createIsNestedEqual:function(){return l}}));function B(U,G){return H(U,G,new WeakMap)}function Y(U){return v(o($,U($)))}function q(U){var G=v(o(V,U(V)));return function(Z,Q,K){return K===void 0&&(K=new WeakMap),G(Z,Q,K)}}n.circularDeepEqual=A,n.circularShallowEqual=B,n.createCustomCircularEqual=q,n.createCustomEqual=Y,n.deepEqual=L,n.sameValueZeroEqual=l,n.shallowEqual=z,Object.defineProperty(n,"__esModule",{value:!0})})})(VE,VE.exports);var eI=VE.exports;const qC=dz(wne);var qt={},bje=function(t,n,r){return t===n?!0:t.className===n.className&&r(t.style,n.style)&&t.width===n.width&&t.autoSize===n.autoSize&&t.cols===n.cols&&t.draggableCancel===n.draggableCancel&&t.draggableHandle===n.draggableHandle&&r(t.verticalCompact,n.verticalCompact)&&r(t.compactType,n.compactType)&&r(t.layout,n.layout)&&r(t.margin,n.margin)&&r(t.containerPadding,n.containerPadding)&&t.rowHeight===n.rowHeight&&t.maxRows===n.maxRows&&t.isBounded===n.isBounded&&t.isDraggable===n.isDraggable&&t.isResizable===n.isResizable&&t.allowOverlap===n.allowOverlap&&t.preventCollision===n.preventCollision&&t.useCSSTransforms===n.useCSSTransforms&&t.transformScale===n.transformScale&&t.isDroppable===n.isDroppable&&r(t.resizeHandles,n.resizeHandles)&&r(t.resizeHandle,n.resizeHandle)&&t.onLayoutChange===n.onLayoutChange&&t.onDragStart===n.onDragStart&&t.onDrag===n.onDrag&&t.onDragStop===n.onDragStop&&t.onResizeStart===n.onResizeStart&&t.onResize===n.onResize&&t.onResizeStop===n.onResizeStop&&t.onDrop===n.onDrop&&r(t.droppingItem,n.droppingItem)&&r(t.innerRef,n.innerRef)};Object.defineProperty(qt,"__esModule",{value:!0});qt.bottom=tI;qt.childrenEqual=wje;qt.cloneLayout=Pq;qt.cloneLayoutItem=Fd;qt.collides=YC;qt.compact=Fq;qt.compactItem=$q;qt.compactType=Aje;qt.correctBounds=Lq;qt.fastPositionEqual=Cje;qt.fastRGLPropsEqual=void 0;qt.getAllCollisions=zq;qt.getFirstCollision=hd;qt.getLayoutItem=nI;qt.getStatics=rI;qt.modifyLayout=Oq;qt.moveElement=bg;qt.moveElementAwayFromCollision=UE;qt.noop=void 0;qt.perc=jje;qt.resizeItemInDirection=Mje;qt.setTopLeft=Ije;qt.setTransform=Dje;qt.sortLayoutItems=cI;qt.sortLayoutItemsByColRow=Wq;qt.sortLayoutItemsByRowCol=Uq;qt.synchronizeLayoutWithChildren=Rje;qt.validateLayout=qq;qt.withLayoutItem=vje;var U5=eI,gg=xje(C);function xje(e){return e&&e.__esModule?e:{default:e}}const yje=process.env.NODE_ENV==="production";function tI(e){let t=0,n;for(let r=0,s=e.length;r<s;r++)n=e[r].y+e[r].h,n>t&&(t=n);return t}function Pq(e){const t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=Fd(e[n]);return t}function Oq(e,t){const n=Array(e.length);for(let r=0,s=e.length;r<s;r++)t.i===e[r].i?n[r]=t:n[r]=e[r];return n}function vje(e,t,n){let r=nI(e,t);return r?(r=n(Fd(r)),e=Oq(e,r),[e,r]):[e,null]}function Fd(e){return{w:e.w,h:e.h,x:e.x,y:e.y,i:e.i,minW:e.minW,maxW:e.maxW,minH:e.minH,maxH:e.maxH,moved:!!e.moved,static:!!e.static,isDraggable:e.isDraggable,isResizable:e.isResizable,resizeHandles:e.resizeHandles,isBounded:e.isBounded}}function wje(e,t){return(0,U5.deepEqual)(gg.default.Children.map(e,n=>n==null?void 0:n.key),gg.default.Children.map(t,n=>n==null?void 0:n.key))&&(0,U5.deepEqual)(gg.default.Children.map(e,n=>n==null?void 0:n.props["data-grid"]),gg.default.Children.map(t,n=>n==null?void 0:n.props["data-grid"]))}qt.fastRGLPropsEqual=bje;function Cje(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function YC(e,t){return!(e.i===t.i||e.x+e.w<=t.x||e.x>=t.x+t.w||e.y+e.h<=t.y||e.y>=t.y+t.h)}function Fq(e,t,n,r){const s=rI(e),o=cI(e,t),i=Array(e.length);for(let a=0,l=o.length;a<l;a++){let u=Fd(o[a]);u.static||(u=$q(s,u,t,n,o,r),s.push(u)),i[e.indexOf(o[a])]=u,u.moved=!1}return i}const Sje={x:"w",y:"h"};function HE(e,t,n,r){const s=Sje[r];t[r]+=1;const o=e.map(i=>i.i).indexOf(t.i);for(let i=o+1;i<e.length;i++){const a=e[i];if(!a.static){if(a.y>t.y+t.h)break;YC(t,a)&&HE(e,a,n+t[s],r)}}t[r]=n}function $q(e,t,n,r,s,o){const i=n==="vertical",a=n==="horizontal";if(i)for(t.y=Math.min(tI(e),t.y);t.y>0&&!hd(e,t);)t.y--;else if(a)for(;t.x>0&&!hd(e,t);)t.x--;let l;for(;(l=hd(e,t))&&!(n===null&&o);)if(a?HE(s,t,l.x+l.w,"x"):HE(s,t,l.y+l.h,"y"),a&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!hd(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function Lq(e,t){const n=rI(e);for(let r=0,s=e.length;r<s;r++){const o=e[r];if(o.x+o.w>t.cols&&(o.x=t.cols-o.w),o.x<0&&(o.x=0,o.w=t.cols),!o.static)n.push(o);else for(;hd(n,o);)o.y++}return e}function nI(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function hd(e,t){for(let n=0,r=e.length;n<r;n++)if(YC(e[n],t))return e[n]}function zq(e,t){return e.filter(n=>YC(n,t))}function rI(e){return e.filter(t=>t.static)}function bg(e,t,n,r,s,o,i,a,l){if(t.static&&t.isDraggable!==!0||t.y===r&&t.x===n)return e;`${t.i}${String(n)}${String(r)}${t.x}${t.y}`;const u=t.x,d=t.y;typeof n=="number"&&(t.x=n),typeof r=="number"&&(t.y=r),t.moved=!0;let f=cI(e,i);(i==="vertical"&&typeof r=="number"?d>=r:i==="horizontal"&&typeof n=="number"?u>=n:!1)&&(f=f.reverse());const m=zq(f,t),p=m.length>0;if(p&&l)return Pq(e);if(p&&o)return`${t.i}`,t.x=u,t.y=d,t.moved=!1,e;for(let g=0,b=m.length;g<b;g++){const x=m[g];`${t.i}${t.x}${t.y}${x.i}${x.x}${x.y}`,!x.moved&&(x.static?e=UE(e,x,t,s,i):e=UE(e,t,x,s,i))}return e}function UE(e,t,n,r,s,o){const i=s==="horizontal",a=s==="vertical",l=t.static;if(r){r=!1;const f={x:i?Math.max(t.x-n.w,0):n.x,y:a?Math.max(t.y-n.h,0):n.y,w:n.w,h:n.h,i:"-1"},h=hd(e,f),m=h&&h.y+h.h>t.y,p=h&&t.x+t.w>h.x;if(h){if(m&&a)return bg(e,n,void 0,t.y+1,r,l,s);if(m&&s==null)return t.y=n.y,n.y=n.y+n.h,e;if(p&&i)return bg(e,t,n.x,void 0,r,l,s)}else return`${n.i}${f.x}${f.y}`,bg(e,n,i?f.x:void 0,a?f.y:void 0,r,l,s)}const u=i?n.x+1:void 0,d=a?n.y+1:void 0;return u==null&&d==null?e:bg(e,n,i?n.x+1:void 0,a?n.y+1:void 0,r,l,s)}function jje(e){return e*100+"%"}const Bq=(e,t,n,r)=>e+n>r?t:n,Vq=(e,t,n)=>e<0?t:n,Hq=e=>Math.max(0,e),sI=e=>Math.max(0,e),oI=(e,t,n)=>{let{left:r,height:s,width:o}=t;const i=e.top-(s-e.height);return{left:r,width:o,height:Vq(i,e.height,s),top:sI(i)}},iI=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{top:r,height:o,width:Bq(e.left,e.width,i,n),left:Hq(s)}},aI=(e,t,n)=>{let{top:r,height:s,width:o}=t;const i=e.left-(o-e.width);return{height:s,width:i<0?e.width:Bq(e.left,e.width,o,n),top:sI(r),left:Hq(i)}},lI=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{width:i,left:s,height:Vq(r,e.height,o),top:sI(r)}},Nje=function(){return oI(arguments.length<=0?void 0:arguments[0],iI(...arguments))},kje=function(){return oI(arguments.length<=0?void 0:arguments[0],aI(...arguments))},Eje=function(){return lI(arguments.length<=0?void 0:arguments[0],iI(...arguments))},_je=function(){return lI(arguments.length<=0?void 0:arguments[0],aI(...arguments))},Tje={n:oI,ne:Nje,e:iI,se:Eje,s:lI,sw:_je,w:aI,nw:kje};function Mje(e,t,n,r){const s=Tje[e];return s?s(t,{...t,...n},r):n}function Dje(e){let{top:t,left:n,width:r,height:s}=e;const o=`translate(${n}px,${t}px)`;return{transform:o,WebkitTransform:o,MozTransform:o,msTransform:o,OTransform:o,width:`${r}px`,height:`${s}px`,position:"absolute"}}function Ije(e){let{top:t,left:n,width:r,height:s}=e;return{top:`${t}px`,left:`${n}px`,width:`${r}px`,height:`${s}px`,position:"absolute"}}function cI(e,t){return t==="horizontal"?Wq(e):t==="vertical"?Uq(e):e}function Uq(e){return e.slice(0).sort(function(t,n){return t.y>n.y||t.y===n.y&&t.x>n.x?1:t.y===n.y&&t.x===n.x?0:-1})}function Wq(e){return e.slice(0).sort(function(t,n){return t.x>n.x||t.x===n.x&&t.y>n.y?1:-1})}function Rje(e,t,n,r,s){e=e||[];const o=[];gg.default.Children.forEach(t,a=>{if((a==null?void 0:a.key)==null)return;const l=nI(e,String(a.key)),u=a.props["data-grid"];l&&u==null?o.push(Fd(l)):u?(yje||qq([u],"ReactGridLayout.children"),o.push(Fd({...u,i:a.key}))):o.push(Fd({w:1,h:1,x:0,y:tI(o),i:String(a.key)}))});const i=Lq(o,{cols:n});return s?i:Fq(i,r,n)}function qq(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Layout";const n=["x","y","w","h"];if(!Array.isArray(e))throw new Error(t+" must be an array!");for(let r=0,s=e.length;r<s;r++){const o=e[r];for(let i=0;i<n.length;i++){const a=n[i],l=o[a];if(typeof l!="number"||Number.isNaN(l))throw new Error(`ReactGridLayout: ${t}[${r}].${a} must be a number! Received: ${l} (${typeof l})`)}if(typeof o.i<"u"&&typeof o.i!="string")throw new Error(`ReactGridLayout: ${t}[${r}].i must be a string! Received: ${o.i} (${typeof o.i})`)}}function Aje(e){const{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}const Pje=()=>{};qt.noop=Pje;var Qa={};Object.defineProperty(Qa,"__esModule",{value:!0});Qa.calcGridColWidth=GC;Qa.calcGridItemPosition=Oje;Qa.calcGridItemWHPx=WE;Qa.calcWH=$je;Qa.calcXY=Fje;Qa.clamp=md;function GC(e){const{margin:t,containerPadding:n,containerWidth:r,cols:s}=e;return(r-t[0]*(s-1)-n[0]*2)/s}function WE(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function Oje(e,t,n,r,s,o){const{margin:i,containerPadding:a,rowHeight:l}=e,u=GC(e),d={};return o&&o.resizing?(d.width=Math.round(o.resizing.width),d.height=Math.round(o.resizing.height)):(d.width=WE(r,u,i[0]),d.height=WE(s,l,i[1])),o&&o.dragging?(d.top=Math.round(o.dragging.top),d.left=Math.round(o.dragging.left)):o&&o.resizing&&typeof o.resizing.top=="number"&&typeof o.resizing.left=="number"?(d.top=Math.round(o.resizing.top),d.left=Math.round(o.resizing.left)):(d.top=Math.round((l+i[1])*n+a[1]),d.left=Math.round((u+i[0])*t+a[0])),d}function Fje(e,t,n,r,s){const{margin:o,containerPadding:i,cols:a,rowHeight:l,maxRows:u}=e,d=GC(e);let f=Math.round((n-i[0])/(d+o[0])),h=Math.round((t-i[1])/(l+o[1]));return f=md(f,0,a-r),h=md(h,0,u-s),{x:f,y:h}}function $je(e,t,n,r,s,o){const{margin:i,maxRows:a,cols:l,rowHeight:u}=e,d=GC(e);let f=Math.round((t+i[0])/(d+i[0])),h=Math.round((n+i[1])/(u+i[1])),m=md(f,0,l-r),p=md(h,0,a-s);return["sw","w","nw"].indexOf(o)!==-1&&(m=md(f,0,l)),["nw","n","ne"].indexOf(o)!==-1&&(p=md(h,0,a)),{w:m,h:p}}function md(e,t,n){return Math.max(Math.min(e,n),t)}var KC={},qE={exports:{}},_0={exports:{}},wn={};/** @license React v16.13.1
|
|
754
754
|
* react-is.production.min.js
|
|
755
755
|
*
|
|
756
756
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
@@ -1074,7 +1074,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1074
1074
|
|
|
1075
1075
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
1076
1076
|
|
|
1077
|
-
`)}})}});var AZe=EKe(()=>wee(vi([ir({type:Lt("text-start"),id:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("text-delta"),id:ft(),delta:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("text-end"),id:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("error"),errorText:ft()}),ir({type:Lt("tool-input-start"),toolCallId:ft(),toolName:ft(),providerExecuted:co().optional(),dynamic:co().optional()}),ir({type:Lt("tool-input-delta"),toolCallId:ft(),inputTextDelta:ft()}),ir({type:Lt("tool-input-available"),toolCallId:ft(),toolName:ft(),input:ya(),providerExecuted:co().optional(),providerMetadata:Sr.optional(),dynamic:co().optional()}),ir({type:Lt("tool-input-error"),toolCallId:ft(),toolName:ft(),input:ya(),providerExecuted:co().optional(),providerMetadata:Sr.optional(),dynamic:co().optional(),errorText:ft()}),ir({type:Lt("tool-output-available"),toolCallId:ft(),output:ya(),providerExecuted:co().optional(),dynamic:co().optional(),preliminary:co().optional()}),ir({type:Lt("tool-output-error"),toolCallId:ft(),errorText:ft(),providerExecuted:co().optional(),dynamic:co().optional()}),ir({type:Lt("reasoning-start"),id:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("reasoning-delta"),id:ft(),delta:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("reasoning-end"),id:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("source-url"),sourceId:ft(),url:ft(),title:ft().optional(),providerMetadata:Sr.optional()}),ir({type:Lt("source-document"),sourceId:ft(),mediaType:ft(),title:ft(),filename:ft().optional(),providerMetadata:Sr.optional()}),ir({type:Lt("file"),url:ft(),mediaType:ft(),providerMetadata:Sr.optional()}),ir({type:gee(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:ft().optional(),data:ya(),transient:co().optional()}),ir({type:Lt("start-step")}),ir({type:Lt("finish-step")}),ir({type:Lt("start"),messageId:ft().optional(),messageMetadata:ya().optional()}),ir({type:Lt("finish"),finishReason:hee(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:ya().optional()}),ir({type:Lt("abort")}),ir({type:Lt("message-metadata"),messageMetadata:ya()})])));function PZe(e){return e.type.startsWith("data-")}function Tee(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]=Tee(o,s):n[r]=s}return n}function OZe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){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(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,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,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"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=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;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=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){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 Mee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await j1({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await j1({text:OZe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function $v(e){return e.type.startsWith("tool-")}function FZe(e){return e.type==="dynamic-tool"}function J_(e){return $v(e)||FZe(e)}function h6(e){return e.type.split("-").slice(1).join("-")}function $Ze({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 LZe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(w){const S=u.message.parts.filter($v).find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(w){const S=u.message.parts.filter(N=>N.type==="dynamic-tool").find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(w){var j;const S=u.message.parts.find(_=>$v(_)&&_.toolCallId===w.toolCallId),N=w,E=S;S!=null?(S.state=w.state,E.input=N.input,E.output=N.output,E.errorText=N.errorText,E.rawInput=N.rawInput,E.preliminary=N.preliminary,E.providerExecuted=(j=N.providerExecuted)!=null?j:S.providerExecuted,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,rawInput:N.rawInput,errorText:N.errorText,providerExecuted:N.providerExecuted,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}function y(w){var j,S;const N=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),E=w,_=N;N!=null?(N.state=w.state,_.toolName=w.toolName,_.input=E.input,_.output=E.output,_.errorText=E.errorText,_.rawInput=(j=E.rawInput)!=null?j:_.rawInput,_.preliminary=E.preliminary,_.providerExecuted=(S=E.providerExecuted)!=null?S:N.providerExecuted,E.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function v(w){if(w!=null){const j=u.message.metadata!=null?Tee(u.message.metadata,w):w;t!=null&&await l6({value:j,schema:t}),u.message.metadata=j}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,w.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 w=u.message.parts.filter($v);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:j}=await Mee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:j}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:j}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({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?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({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 w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:h6(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:h6(w),state:"output-error",input:w.input,rawInput:w.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 v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(PZe(a)){(n==null?void 0:n[a.type])!=null&&await l6({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const j=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;j!=null?j.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function zZe({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()}}Ay({prefix:"aitxt",size:24});Ay({prefix:"aiobj",size:24});var BZe=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()})}};Ay({prefix:"aiobj",size:24});var VZe={};jZe(VZe,{object:()=>UZe,text:()=>HZe});var HZe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),UZe=({schema:e})=>{const t=CZe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Mee(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 j1({text:n});if(!s.success)throw new d6({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 d6({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 WZe(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=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var qZe=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 nh(this.body),l=await nh(this.headers),u=await nh(this.credentials),d={...ed(l),...ed(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,m=(f==null?void 0:f.headers)!==void 0?ed(f.headers):d,p=(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},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:i6({"Content-Type":"application/json",...m},`ai-sdk/${f6}`,o6()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await nh(this.body),a=await nh(this.headers),l=await nh(this.credentials),u={...ed(a),...ed(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:l,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?ed(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:l,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:i6(h,`ai-sdk/${f6}`,o6()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},MA=class extends qZe{constructor(e={}){super(e)}processResponseStream(e){return MKe({stream:e,schema:AZe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},YZe=class{constructor({generateId:e=vKe,id:t=e(),transport:n=new MA,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new BZe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await WZe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+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:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>J_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>J_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.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=l,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,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:$Ze({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await zZe({stream:LZe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}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(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function GZe({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(J_).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function KZe(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,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var ZZe=KZe;const XZe=hf(ZZe);var Dee=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Gn=(e,t,n)=>(Dee(e,t,"read from private field"),n?n.call(e):t.get(e)),ma=(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)},vc=(e,t,n,r)=>(Dee(e,t,"write to private field"),t.set(e,n),n);function QZe(e,t){return t!=null?XZe(e,t):e}var Qo,Lv,zv,kg,Eg,_g,lh,eT,tT,JZe=class{constructor(e=[]){ma(this,Qo,void 0),ma(this,Lv,"ready"),ma(this,zv,void 0),ma(this,kg,new Set),ma(this,Eg,new Set),ma(this,_g,new Set),this.pushMessage=t=>{vc(this,Qo,Gn(this,Qo).concat(t)),Gn(this,lh).call(this)},this.popMessage=()=>{vc(this,Qo,Gn(this,Qo).slice(0,-1)),Gn(this,lh).call(this)},this.replaceMessage=(t,n)=>{vc(this,Qo,[...Gn(this,Qo).slice(0,t),this.snapshot(n),...Gn(this,Qo).slice(t+1)]),Gn(this,lh).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?QZe(t,n):t;return Gn(this,kg).add(r),()=>{Gn(this,kg).delete(r)}},this["~registerStatusCallback"]=t=>(Gn(this,Eg).add(t),()=>{Gn(this,Eg).delete(t)}),this["~registerErrorCallback"]=t=>(Gn(this,_g).add(t),()=>{Gn(this,_g).delete(t)}),ma(this,lh,()=>{Gn(this,kg).forEach(t=>t())}),ma(this,eT,()=>{Gn(this,Eg).forEach(t=>t())}),ma(this,tT,()=>{Gn(this,_g).forEach(t=>t())}),vc(this,Qo,e)}get status(){return Gn(this,Lv)}set status(e){vc(this,Lv,e),Gn(this,eT).call(this)}get error(){return Gn(this,zv)}set error(e){vc(this,zv,e),Gn(this,tT).call(this)}get messages(){return Gn(this,Qo)}set messages(e){vc(this,Qo,[...e]),Gn(this,lh).call(this)}};Qo=new WeakMap;Lv=new WeakMap;zv=new WeakMap;kg=new WeakMap;Eg=new WeakMap;_g=new WeakMap;lh=new WeakMap;eT=new WeakMap;tT=new WeakMap;var ch,m6=class extends YZe{constructor({messages:e,...t}){const n=new JZe(e);super({...t,state:n}),ma(this,ch,void 0),this["~registerMessagesCallback"]=(r,s)=>Gn(this,ch)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Gn(this,ch)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Gn(this,ch)["~registerErrorCallback"](r),vc(this,ch,n)}};ch=new WeakMap;function Iee({experimental_throttle:e,resume:t=!1,...n}={}){const r=C.useRef("chat"in n?n.chat:new m6(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new m6(n));const o="id"in n?n.id:null,i=C.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=C.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=C.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=C.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=C.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return C.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:l,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function eXe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function tXe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function nXe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function rXe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function Ree(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:rXe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function Aee(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 sXe(){var b;const{authToken:e,tokenProps:t}=Xe(),n=J(x=>x.dashboard.aiScopeTables),r=(b=L1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=Iee({transport:new MA({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=la.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:Dq(x)}})}),onToolCall:m,sendAutomaticallyWhen:GZe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:Ree(n||[])}}),x.toolName==="getDashboardContext"){const y=J.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=Aee(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function Pee(){var u;const{authToken:e,tokenProps:t}=Xe(),n=(u=L1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=En({queryKey:["assistant-profile",n],queryFn:()=>rr(`${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 Oee({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(c8,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(se,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function N1(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(eM,{className:r});case"view":return c.jsx(tu,{className:r});case"materialized view":return c.jsx(Woe,{className:r});case"model":return c.jsx(U1,{className:r});case"file":return c.jsx(Ji,{className:r});case"dataset":return c.jsx($l,{className:r});case"upload":return c.jsx(sM,{className:r});case"url":return c.jsx(p8,{className:r});default:return c.jsx(Sx,{className:r})}}const Fee=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Ko,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx($s.Input,{ref:n,className:X("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})]}));Fee.displayName=$s.Input.displayName;const uv=e=>e.label||(e==null?void 0:e.name),p6=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function oXe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Xe(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=C.useState(""),[p,g]=C.useState(""),b=s.filter(S=>{if(!h)return!0;const N=uv(S).toLowerCase(),E=p6(S).toLowerCase(),_=h.toLowerCase();return N.includes(_)||E.includes(_)});C.useEffect(()=>{e||(m(""),g(""))},[e]),C.useEffect(()=>{b.length>0&&!p&&g(uv(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(N=>uv(N)===p);S&&(o.some(E=>"id"in S&&"id"in E?S.id===E.id:S.name===E.name&&S.connectionId===E.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(N=>"id"in S&&"id"in N?S.id===N.id:S.name===N.name&&S.connectionId===N.connectionId),w=o.length===s.length,j=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(op,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(Fee,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(Tr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),j&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(St,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(ip,{className:"min-h-60",children:[c.jsx(ap,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(Tr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(lp,{children:b.map((S,N)=>{const E=v(S),_="id"in S?S.id:`${S.connectionId}-${S.name}`,k=uv(S);return c.jsxs(cp,{value:k,onSelect:()=>{E?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:X("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:N1(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:k}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:p6(S)})]}),E&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Ar,{className:"h-3 w-3 text-background"})})]},_)})})]})]})})}const nT=e=>e.name||e.name,iXe=e=>{const t=nT(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function aXe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=C.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Ln,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(an,{children:[c.jsx(ln,{asChild:!0,children:c.jsxs(Ve,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[N1(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:nT(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(St,{className:"h-3 w-3"})})]})}),c.jsx(dn,{side:"top",className:"max-w-xs",children:iXe(d)})]},h)}),u&&c.jsxs(an,{open:s,onOpenChange:o,children:[c.jsx(ln,{asChild:!0,children:c.jsxs(Ve,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(f8,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(St,{className:"h-3 w-3"})})]})}),c.jsx(dn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:N1(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:nT(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(St,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function $ee(e){return e.type==="dataset"&&e.label||e.name}function lXe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function cXe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ae,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Ve,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),$ee(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(St,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function uXe(e){const{tokenProps:t}=Xe(),n=J(l=>l.authToken)||e;Ae(l=>l.selectedConnectionId),Ae(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=En({queryKey:["semantic-domains"],queryFn:()=>rr(`${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 dXe(e,t){const{tokenProps:n}=Xe(),r=J(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=En({queryKey:["datasets",e],queryFn:()=>rr(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function fXe(e){var g,b;const{tokenProps:t}=Xe(),n=J(x=>x.authToken)||e,{connections:r}=Ci(e),s=Ae(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:m}=En({queryKey:["databases",s],queryFn:()=>rr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function hXe(e){var g;const{tokenProps:t}=Xe(),n=J(b=>b.authToken)||e,{connections:r}=Ci(e),s=Ae(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ae(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:m}=En({queryKey:["schemas",s,o],queryFn:()=>rr(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function Lee(e){const{tokenProps:t}=Xe(),n=J(h=>h.authToken)||e,{connections:r}=Ci(e),s=Ae(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=En({queryKey:["dataModels",s],queryFn:()=>rr(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function mXe(){var j,S,N;const e=Ae(E=>E.card.dataSource);Ae(E=>E.actions.updateDirectSource);const t=Ae(E=>E.actions.updateDataSource),[n,r]=C.useState(""),{selectedConnection:s,error:o}=Ci(),{databases:i,isPending:a,error:l,label:u}=fXe(),{schemas:d,isPending:f,error:h,label:m}=hXe(),{error:p}=Lee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=E=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const _=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{..._,schema:E},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(se,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium",children:u}),c.jsxs(ot,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.database)||"",onValueChange:v,disabled:a,children:[c.jsx(nt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(xn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(rt,{children:i.map(E=>c.jsx(ve,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium",children:m}),c.jsxs(ot,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(nt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(xn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(rt,{children:d.map(E=>c.jsx(ve,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function pXe(){const e=Ae(l=>l.card.dataSource),t=Ae(l=>l.actions.updateDataSource),[n,r]=C.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(sM,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(se,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ae,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ji,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(St,{className:"h-3 w-3"})})]},l.id))})]})]})}function gXe(){const e=Ae(f=>f.card.dataSource),t=Ae(f=>f.actions.updateDataSource),[n,r]=C.useState(""),[s,o]=C.useState(""),[i,a]=C.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(mn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(mn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(se,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(Tr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ae,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Sx,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(St,{className:"h-3 w-3"})})]},f.id))})]})]})}function bXe(e,t){var y,v;const{tokenProps:n}=Xe(),r=J(w=>w.authToken)||t,{connections:s}=Ci(t),o=Ae(w=>{var j,S;return(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.connectionId}),i=Ae(w=>{var j,S,N;return(N=(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.database}),a=Ae(w=>{var j,S,N;return(N=(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=En({queryKey:[e,o,i,a],queryFn:()=>rr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var j;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(j=w==null?void 0:w.table_type)==null?void 0:j.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function k1({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(Yl,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function xXe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ci(),[i,a]=C.useState(""),[l,u]=C.useState(""),[d,f]=C.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=cr(),{entities:p,isLoading:g,error:b}=bXe("table"),{dataModels:x,isPending:y,error:v}=Lee(),w=k=>{const M=s.find(P=>P.id===k);if(!M)return;const T=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:M.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},j=k=>{var O,I;const M=n||[],T=M.some($=>$.name===k.name&&$.type===k.type);let P;if(T)P=M.filter($=>!($.name===k.name&&$.type===k.type));else{const $={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((O=e.dbSelection)==null?void 0:O.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:k.name,dialect:k.dialect};P=[...M,$]}t==null||t(P)},S=k=>{const M=n||[],T=M.some(O=>O.type==="model"&&O.name===k.name);let P;T?P=M.filter(O=>!(O.type==="model"&&O.name===k.name)):P=[...M,k],t==null||t(P)},N=p.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),E=x.filter(k=>k.name.toLowerCase().includes(l.toLowerCase())),_=C.useCallback(()=>{if(!t)return;const k=n||[];let M=[...k];if(d==="tables"){const P=N.filter(O=>!k.some(I=>I.name===O.name&&I.type==="table")).map(O=>{var I,$;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:O.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:(($=e.dbSelection)==null?void 0:$.schema)||"",name:O.name,dialect:O.dialect}});M=[...k,...P]}else if(d==="datamodels"){const T=E.filter(P=>!k.some(O=>O.name===P.name&&O.type==="model"));M=[...k,...T]}t(M)},[d,N,E,n,e,t]);return C.useEffect(()=>{r&&r(_)},[r,_]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(ot,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(nt,{className:"w-full",children:c.jsx(at,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(rt,{children:s.map(k=>c.jsx(ve,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx($l,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:k.name}),c.jsx(Ve,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(pXe,{}),e.connectionType==="url"&&c.jsx(gXe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(mXe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(Os,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[c.jsxs(ys,{className:"grid w-full grid-cols-2",children:[c.jsxs(nn,{value:"tables",children:["Tables & Views (",N.length,")"]}),c.jsxs(nn,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),c.jsxs(pr,{value:"tables",className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(k1,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):N.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):N.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>j(k),children:[c.jsx(cn,{id:`table-${k.name}`,checked:M,onCheckedChange:()=>j(k),onClick:T=>T.stopPropagation(),disabled:g}),c.jsxs(ae,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&c.jsx(Ve,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&c.jsx(Ve,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),c.jsxs(pr,{value:"datamodels",className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search data models...",value:l,onChange:k=>u(k.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(k1,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):E.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):E.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(k),children:[c.jsx(cn,{id:`dataModel-${k.name}`,checked:M,onCheckedChange:()=>S(k),onClick:T=>T.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ae,{className:"cursor-pointer",children:k.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function yXe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var j;const[l,u]=C.useState(""),d=C.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);C.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=uXe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=dXe(e==null?void 0:e.semanticDomainId),y=S=>{const N=r||[],E=N.some(k=>k.id===S.id&&k.type==="dataset");let _;if(E)_=N.filter(k=>!(k.id===S.id&&k.type==="dataset"));else{const k={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};_=[...N,k]}n==null||n(_)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),w=C.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],E=v.filter(k=>!S.some(M=>M.id===k.id&&M.type==="dataset")).map(k=>({id:k.id,datasetType:k.type,name:k.name||k.table,label:k.label,domainId:k.domainId,description:k.description,database:k.database,schema:k.schema,type:"dataset",connectionId:k.connectionId,connectionType:k.connectionType,dialect:k.dialect,datamodelId:k.datamodelId,sql:k.sql})),_=[...S,...E];n(_)},[v,r,e==null?void 0:e.semanticDomainId,n]);return C.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(ot,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(nt,{className:"w-full",children:c.jsx(at,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((j=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:j.label)||"Select semantic domain"})}),c.jsx(rt,{children:p.map(S=>c.jsx(ve,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(k1,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(k1,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const N=r.some(E=>E.id===S.id&&E.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(cn,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>y(S),onClick:E=>E.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ae,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function DA({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Xe(),{allowedSemanticDomains:i}=o,[a,l]=C.useState([]),{updateDataSource:u}=cr(),d=J(M=>M.isVisualEditing),f=J(M=>M.dashboard.aiContext),{setAiContext:h}=Wt(),m=C.useRef(null),[p,g]=C.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=C.useCallback(M=>{const T=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=C.useCallback(M=>{u({...n,...M})},[n,u]);C.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),C.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),C.useEffect(()=>{e?l(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const j=M=>{const T=a.filter(P=>!(P.name===M.name&&P.type===M.type));l(T)},S=()=>{l([])},N=C.useCallback(M=>{l(M)},[]),E=C.useCallback(()=>{m.current&&m.current()},[]),_=C.useCallback(M=>{m.current=M,g(!0)},[]);function k(){var M,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const P=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,O=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:P,connectionType:O,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(Gr,{open:e,onOpenChange:t,children:c.jsx(zr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Br,{className:"flex-shrink-0",children:[c.jsx(Vr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(is,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(Os,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(ys,{className:"grid w-full grid-cols-2",children:[c.jsx(nn,{value:"database",children:"Direct Source"}),c.jsx(nn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(yXe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:_}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(xXe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,onRegisterSelectAll:_})]})}),c.jsx(cXe,{selectedEntities:a,onDeselectEntity:j}),c.jsx(os,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(se,{variant:"outline",onClick:E,disabled:!p,children:"Select All"}),c.jsx(se,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(se,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(St,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(se,{onClick:k,children:[c.jsx(Ar,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function vXe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=C.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=gl-n;if(l.length>u){ze.error(`You can only attach ${gl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=SJ(l);if(f.forEach(({file:h,error:m})=>{ze.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>vA(m)));e(h)}catch(h){console.error("Failed to process files:",h),ze.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.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>=gl}),c.jsx(se,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=gl,title:n>=gl?`Maximum ${gl} files allowed`:"Attach files",children:c.jsx(ZT,{className:"h-4 w-4 text-muted-foreground"})})]})}function wXe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=C.useState(!1),a=C.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=C.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=C.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=C.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 m=gl-r;if(h.length>m){ze.error(`You can only attach ${gl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=SJ(h);if(g.forEach(({file:b,error:x})=>{ze.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>vA(x)));t(b),ze.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),ze.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:X("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(sM,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[gl-r," slot(s) available"]})]})})]})}const IA=C.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=C.useState(!1),[h,m]=C.useState(!1),[p,g]=C.useState(!1),b=C.useRef(null),x=dp();gje(),pje();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:j}=WC(),{queueMessage:S}=fp(),{addFileAttachment:N,removeFileAttachment:E,clearFileAttachments:_,getFileAttachments:k}=QD(),M=XD(l),T=Ae(U=>U.card.dataSource),P=J(U=>U.dashboard.aiContext),O=J(U=>{var G;return(G=U.dashboard.aiContext)==null?void 0:G.selectedEntities});C.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=C.useCallback(()=>{const U=b.current;if(U){if(!e||e.length===0){U.style.height="10px";return}U.style.height="auto";const G=Math.min(Math.max(U.scrollHeight,10),200);U.style.height=`${G}px`}},[e]);C.useEffect(()=>{I()},[I]),C.useEffect(()=>{const U=setTimeout(()=>{I()},0);return()=>clearTimeout(U)},[I]);const $=()=>{const U=e.trim();!U&&M.length===0||(a!=="ready"?(S(l,U,M),t(""),_(l)):r({preventDefault:()=>{}}))},V=U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),$()),U.key==="@"&&(q(),f(!0))},W=C.useCallback(U=>{const G=WUe(U.nativeEvent);G.length>0&&(U.preventDefault(),G.forEach(async Z=>{const Q=await vA(Z);N(l,Q)}))},[N,l]),L=C.useCallback(U=>{U.forEach(G=>{N(l,G)})},[N,l]),R=C.useCallback(U=>{U.forEach(G=>{N(l,G)})},[N,l]),z=C.useCallback(U=>{E(l,U)},[E,l]),F=U=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===U.id||Z.name===U.name)){const Z=x.selectedEntities.filter(Q=>!(Q.id&&Q.id===U.id||Q.name===U.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,U];y({selectedEntities:Z})}},A=U=>{F(U)},H=U=>{var Q;if(!x.selectedEntities.some(K=>K.id&&K.id===U.id||K.name===U.name)){const K=[...x.selectedEntities,U];y({selectedEntities:K})}const Z="label"in U?U.label:U.name;t(e+`@${Z} `),f(!1),(Q=b.current)==null||Q.focus()},B=U=>{const G=x.selectedEntities.filter(K=>!(K.id&&K.id===U.id||K.name===U.name));y({selectedEntities:G});const Q=`@${"label"in U?U.label:U.name}`;e.includes(Q)&&t(e.replace(Q,"").trim())},Y=U=>{const G=new Set(U.map(K=>K.id||K.name)),Z=x.selectedEntities.filter(K=>!G.has(K.id||K.name));y({selectedEntities:Z});let Q=e;U.forEach(K=>{const le=`@${"label"in K?K.label:K.name}`;Q=Q.replace(le,"").trim()}),t(Q)},q=C.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(P==null?void 0:P.selectedEntities)||[]})},[x.selectedEntities.length,P==null?void 0:P.selectedEntities,y]);return c.jsxs(wXe,{onFilesDropped:L,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(aXe,{entities:x.selectedEntities,availableEntities:O||[],onRemoveEntity:B,onRemoveEntities:Y}),M.length>0&&c.jsx(qUe,{files:M,onRemove:z,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:V,onPaste:W,onFocus:()=>{I(),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 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(ms,{open:d,onOpenChange:U=>{U&&q(),f(U)},children:[c.jsx(ps,{asChild:!0,children:c.jsx(se,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(zoe,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(gs,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:U=>U.preventDefault(),children:c.jsx(oXe,{isOpen:!0,onSelect:F,onDeselect:A,onClose:()=>{var U;f(!1),(U=b.current)==null||U.focus()},availableEntities:O||[],selectedEntities:x.selectedEntities,onTabComplete:H,onSelectAll:()=>{O&&y({selectedEntities:O})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(vXe,{onFilesSelected:R,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(se,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(tie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(se,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:$,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(w8,{className:"size-4"})})]})]})]}),c.jsx(DA,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||HS,dialogMode:"aiContext"})]})});IA.displayName="ChatInputWithContext";function zee({assistantType:e,className:t}){const n=Iq(e),{removeFromQueue:r}=fp();return n.length===0?null:c.jsxs("div",{className:X("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(Gl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.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:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(se,{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:c.jsx(St,{className:"h-3 w-3"})})]})},s.id))})]})}function Bee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=Iq(e),{dequeueMessage:o}=fp();C.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 Vee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=C.useRef(null),[a,l]=C.useState(!0),[u,d]=C.useState(!0),[f,h]=C.useState(!1),[m,p]=C.useState(0),g=C.useRef(0),b=C.useRef(!1),x=C.useRef(0),y=C.useRef(a),v=C.useRef(void 0),w=C.useRef({key:null,count:0,length:0}),j=C.useCallback(()=>{const _=i.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight:0},[]),S=C.useCallback((_={})=>{if(!i.current)return;const{force:M=!1,instant:T=!1}=_;if(!M&&!y.current||!a&&!M)return;const P=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const O=i.current;if(!O){b.current=!1,v.current=void 0;return}const I=O.scrollHeight;P==="smooth"&&"scrollTo"in O?O.scrollTo({top:I,behavior:P}):O.scrollTop=I,g.current=O.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),N=C.useCallback(()=>{const _=i.current;if(!_)return;const k=g.current,M=_.scrollTop,T=M-k;if(g.current=M,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const P=j()<=n;d(P),l(P),y.current=P,P&&(h(!1),p(0))},[j,n]),E=C.useCallback(()=>{p(0),h(!1)},[]);return C.useEffect(()=>{y.current=a},[a]),C.useEffect(()=>{const _=i.current;if(!_||!e||e.length===0){h(!1),p(0),w.current={key:null,count:0,length:0},g.current=_?_.scrollTop:0,x.current=_?_.scrollHeight:0;return}g.current=_.scrollTop,x.current=_.scrollHeight;const k=w.current,M=e[e.length-1],T=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,P=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce((L,R)=>R?typeof R=="string"?L+R.length:typeof R.text=="string"?L+R.text.length:typeof R.content=="string"?L+R.content.length:typeof R.value=="string"?L+R.value.length:L:L,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,O=e.length>k.count,I=T!==k.key,$=P>k.length,V=s&&(M==null?void 0:M.role)==="assistant"&&!O&&(I||$),W=o||V;if(w.current={key:T,count:e.length,length:P},a&&(O||I||$||W)){S({force:!1,instant:W});return}if(!a&&O){const L=e.length-k.count;L>0&&(h(!0),p(R=>R+L))}else!a&&$&&(h(!0),p(L=>L>0?L:1))},[e,S,a,s,o]),C.useEffect(()=>{S({instant:!0})},[S]),C.useEffect(()=>{if(typeof ResizeObserver>"u")return;const _=i.current;if(!_)return;x.current=_.scrollHeight;const k=new ResizeObserver(()=>{const M=i.current;if(!M)return;const T=x.current,P=M.scrollHeight;x.current=P,!b.current&&y.current&&P>T&&S({force:!1,instant:!0})});return k.observe(_),()=>{k.disconnect()}},[S]),C.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:S,handleScroll:N,resetNewMessageCount:E}}function Hee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=C.useState(r),a=C.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=C.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=C.useCallback(()=>{i(r)},[r]);return C.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Uee(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:r.text||"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:jJ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const CXe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function SXe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=C.useState(!1),[a,l]=C.useState(gT),[u,d]=C.useState(!1),[f,h]=C.useState(!1),[m,p]=C.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=Hm(),y=C.useRef(null);J(Ye=>Ye.dashboard.aiScopeTables),J(Ye=>Ye.isDashboardEditing);const v=J(Ye=>Ye.selectedSheetId),{setDataSource:w}=cr(),{addFrame:j,setSelectedFrameId:S,setIsDashboardEditing:N}=Wt(),E=dp(),{setCurrentAIContext:_,updateSelectedEntities:k,setReasoningEffort:M,setShowReasoning:T}=WC(),{clearQueue:P}=fp(),{clearFileAttachments:O,getFileAttachments:I}=QD(),$=XD("dashboard"),V=J(Ye=>Ye.dashboard.aiContext),W=Ae(Ye=>Ye.card.dataSource),{assistantProfile:L}=Pee(),R=J(Ye=>Ye.handleOpenAssistantProfile),{sendMessage:z,isLoading:F,messages:A,setMessages:H,status:B,stop:Y,errorMessage:q,clearError:U}=sXe(),G=C.useCallback(Ye=>{r==null||r(Ye),n===void 0&&p(Ye)},[n,r]),Z=C.useCallback(()=>{G(!g)},[g,G]);C.useEffect(()=>{if(!g)return;function Ye(Yt){Yt.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Ye),()=>{window.removeEventListener("keydown",Ye)}},[g,G]);const[Q,K]=C.useState(""),te=Ye=>{K(Ye.target.value)};function le({sql:Ye,cardTitle:Yt,connectionId:Ge,cardType:et,python:Be,cardConfig:Ke,dataSource:kt,customVisualPreferences:pe}){if(!v)return;const Re={id:Rr(),title:Yt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:et==="horizontalBar"?"y":"x"}},type:et,sql:Ye,python:Be,dataSource:kt,config:Ke,connectionId:Ge,customCardPreferences:pe?{url:pe.url,componentName:pe.componentName,pluginChartType:pe.pluginChartType,settings:pe.settings,type:"component"}:void 0},re={id:Rr(),cards:[Re],activeCardId:Re.id};N(!0),j(v,re,"end"),S(re.id)}const de=Ye=>{Ye.preventDefault();const Yt=Q.trim();if(!Yt&&$.length===0)return;const Ge=[];Yt&&Ge.push({type:"text",text:Yt}),$.forEach(et=>{et.data&&Ge.push({type:"file",mediaType:et.type,filename:et.name,url:`data:${et.type};base64,${et.data}`})}),z({role:"user",parts:Ge}),K(""),O("dashboard"),ie({force:!0})};C.useEffect(()=>{var Ye;e&&((Ye=y.current)==null||Ye.focus())},[e]),Bee({assistantType:"dashboard",status:B,isLoading:F,sendMessage:z});const{hasActiveTools:ce}=Uee(A),{visibleMessages:Ce,hasMoreMessages:ge,totalMessageCount:he,loadMoreMessages:me,resetMessageWindow:oe}=Hee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Ne,isAtBottom:fe,hasNewMessages:Me,newMessageCount:ke,scrollToBottom:ie,handleScroll:xe,resetNewMessageCount:Oe}=Vee(Ce,{threshold:50,behavior:"smooth",isStreaming:F});function be(Ye){Fe();const Yt={role:"user",parts:[{type:"text",text:Ye.title+" "+Ye.subtitle}]};z(Yt)}function De(Ye){Fe(),z({role:"user",parts:[{type:"text",text:Ye}]})}function qe(Ye){Fe(),z({role:"user",parts:[{type:"text",text:Ye}]}),ie({force:!0})}const He=C.useCallback(async()=>{const Ye=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ye),ze.success("Conversation copied")}catch(Yt){console.error("Failed to copy conversation",Yt),ze.error("Unable to copy conversation")}},[A]);function Fe(){E.selectedEntities.length===0&&_({selectedEntities:(V==null?void 0:V.selectedEntities)||[]})}const yt=(Q==null?void 0:Q.length)===0&&(A==null?void 0:A.filter(Ye=>Ye.role==="user").length)===0;function je(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function dt(){return c.jsxs(wf,{children:[c.jsx(Cf,{asChild:!0,children:c.jsx(Wc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Pm,{className:"size-3.5"})})}),c.jsxs(yu,{align:"end",children:[c.jsx(Eh,{children:"Options"}),c.jsx(Kd,{}),c.jsx(Mg,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Mg,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Mg,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const Ct=c.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[je(),R&&c.jsx(se,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:R,children:(L==null?void 0:L.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&dt(),a&&c.jsx(se,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:He,children:"Copy Conversation"}),c.jsx(Wc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(KT,{className:"size-4"}):c.jsx(W1,{className:"size-4"})}),c.jsx(Wc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{H([]),P("dashboard"),U(),oe()},children:c.jsx(Y1,{className:"size-4"})}),c.jsx(Wc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(St,{className:"size-4"})})]})]}),c.jsxs(tl,{"data-role":"dashboard-assistant-scroll-area",ref:Ne,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:xe,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[ge&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(se,{variant:"outline",size:"sm",onClick:me,className:"text-xs",children:["Load ",Math.min(5,he-Ce.length)," ","more messages (",he-Ce.length," ","hidden)"]})}),c.jsx(kJ,{showTools:a,showSystemMessage:u,messages:Ce,onAddToDashboard:le,onQuickReply:qe,disableQuickReplies:F}),!ce&&c.jsx(NJ,{status:B,errorMessage:q})]}),c.jsx(bi,{orientation:"horizontal"})]}),e&&!fe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(se,{onClick:()=>{ie({force:!0}),Oe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(kr,{className:"h-4 w-4"}),Me&&ke>0&&c.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:ke>9?"9+":ke})]})}),c.jsxs("div",{className:"space-y-3",children:[!L&&yt&&c.jsx(EJ,{onClick:be,placeholders:CXe}),c.jsx("div",{children:yt&&L&&c.jsx(Oee,{seedQuestions:L.seedQuestions||[],handleSeedQuestionClick:De})}),c.jsx(zee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(IA,{ref:y,setInput:K,stop:Y,input:Q,handleInputChange:te,handleSubmit:Ye=>{Fe(),de(Ye),ie({force:!0})},isLoading:F,status:B,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(DA,{incomingSelectedEntities:(V==null?void 0:V.selectedEntities)||[],open:f,onOpenChange:h,dataSource:W||HS,dialogMode:"aiContext"})]});return g&&s?Zn.createPortal(c.jsx("div",{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:c.jsx("div",{className:"flex h-full w-full",children:Ct})}),s):Ct}function jXe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Wt(),o=J(d=>d.dashboard.sheets),a=J(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=J(d=>d.isDashboardEditing),u=J(d=>d.isVisualEditing);C.useEffect(()=>{if(!l||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),ze.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=NR(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),ze.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function NXe(e,t){switch(e.interactionMode){case"drillToDetail":kXe(e,t);break;case"drillThrough":EXe(e,t);break;case"drillToURL":_Xe(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 kXe(e,t){var l;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=((l=t.getCurrentFilters)==null?void 0:l.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 EXe(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))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function _Xe(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 TXe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(Gr,{open:e,onOpenChange:t,children:c.jsxs(zr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Br,{children:[c.jsx(Vr,{children:i||"Insight Detail"}),c.jsx(is,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(YZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(XZ,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function MXe(){const e=Vt(w=>w.interactionStates),t=Vt(w=>w.setInteractionState),n=Vt(w=>w.clearLastInteractionEvent),r=Vt(w=>w.replaceCardWithInsight),s=Vt(w=>w.setPendingDrillThrough),o=Vt(w=>w.pendingDrillThrough),i=Vt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Wt(),{selectDashboard:u}=Cx(),d=J(w=>w.dashboard),f=J(w=>w.filterValues),{data:h,isLoading:m}=F7((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=C.useState({open:!1,insightId:""}),b=QZ(p.insightId,{enabled:p.open&&!!p.insightId}),x=C.useRef(new Set),y=C.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:j,contextMode:S})=>{g({open:!0,insightId:w,filters:j,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:j,filters:S,contextMode:N})=>{r(w,j,S,N)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:j,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:E})=>{const k={sourceCardId:Da,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...ii(),appliedClickFilters:[k],contextMode:j,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:E};t(Da,M)}}),[a,r,f,l,d,s,t]);C.useEffect(()=>{Object.entries(e).forEach(([w,j])=>{if(j!=null&&j.lastInteractionEvent){const S=j.lastInteractionEvent,N=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(N))return;x.current.add(N);try{NXe(S,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(w),setTimeout(()=>{x.current.delete(N)},5e3)}}})},[e,n,y]),C.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(TXe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(xn,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function DXe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=IXe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function IXe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function RXe(e){return e?`Back to ${e}`:"Back"}function AXe(){var x,y,v,w,j;const e=Vt(S=>S.interactionStates[Da]),t=J(S=>S.actions.goBackFromDrill),n=J(S=>S.actions.clearDrillContext),{selectDashboard:r}=Cx(),[s,o]=C.useState({x:16,y:16}),[i,a]=C.useState(!1),l=C.useRef({x:0,y:0});C.useEffect(()=>{if(!i)return;const S=E=>{o({x:E.clientX-l.current.x,y:E.clientY-l.current.y})},N=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",N),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",N)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.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||!((j=e.appliedClickFilters)!=null&&j.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};DXe(f);const b=RXe(d);return c.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:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,N)=>{const E=S.field.label||S.field.name,_=String(S.value);return c.jsxs(Ve,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",_]},N)})})]}),c.jsx(se,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(St,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(se,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(t8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Wee(){var ge;const{showAssistant:e,tokenProps:t}=Xe(),{preferences:n,isConsoleMode:r}=Hm(),s=((ge=n==null?void 0:n.cardDisplay)==null?void 0:ge.mode)==="print",o=C.useRef(null),i=C.useRef(null),[a,l]=C.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=L6e({initialPosition:"bottom-right"}),m=Od(he=>he.setFullscreen),p=Od(he=>he.setPanelOpen),g=Od(he=>he.setContainer),b=_q("dashboard"),x=Tq(),y=Mq("dashboard"),v=b.isOpen,w=x==="dashboard",j=J(he=>he.isVisualEditing),S=J(he=>he.themeStyle),N=J(he=>{var me;return(me=he.dashboard)==null?void 0:me.sheets}),E=J(he=>he.showFilters),_=J(he=>he.isDashboardEditing),k=J(he=>he.selectedSheetId),M=J(he=>{var me;return(me=he.dashboard)==null?void 0:me.id}),T=J(he=>he.isDashboardPanelOpen),P=J(he=>he.actions.setIsDashboardPanelOpen),{getDefaultSheetId:O,setDefaultSheetId:I,clearDefaultSheetId:$}=Zz(M),[V,W]=C.useState(null);iC(Ut.DASHBOARD);const{setSelectedSheetId:L,setSheetTitle:R,addSheet:z,setSheets:F}=Wt();jXe(i);const{setActiveAssistantType:A}=WC();C.useEffect(()=>{if(M){const he=O();W(he)}},[M,O]),C.useEffect(()=>{v?A("dashboard"):x==="dashboard"&&m(null)},[v,A,x,m]),C.useEffect(()=>{var he;v||(he=o.current)==null||he.resize(0)},[v]);function H(he){var me,oe;he?((me=o.current)==null||me.resize(40),p("dashboard",!0),A("dashboard")):(p("dashboard",!1),m(null),(oe=o.current)==null||oe.resize(0),A(null))}function B(){const he={id:Rr(),title:"New Sheet"};z(he),L(he.id)}function Y(he,me){if(!M)return;V===he?($(),W(null),ze.success("Default sheet cleared")):(I(he),W(he),ze.success(`"${me}" set as default sheet`))}function q(he){var me;he<1?(p("dashboard",!1),m(null),A(null),(me=o.current)==null||me.resize(0)):(v||p("dashboard",!0),A("dashboard"))}function U(){return(S==null?void 0:S.canvasTheme)==="muted"||!(S!=null&&S.canvasTheme)?"hsl(var(--semaphor-muted))":(S==null?void 0:S.canvasTheme)==="clear"?"":S==null?void 0:S.canvasTheme}const G=(he,me)=>{he.dataTransfer.setData("tabIndex",me.toString())},Z=he=>{he.preventDefault()},Q=(he,me)=>{const oe=he.dataTransfer.getData("tabIndex");if(oe===me.toString())return;const Ne=Array.from(N||[]),[fe]=Ne.splice(parseInt(oe),1);Ne.splice(me,0,fe),F(Ne)},K=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,te=e===!0&&!s&&!v&&!j&&!E;function le(){var he,me;if(N&&N.length>1||_)return c.jsxs(ys,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none border-b border-b-muted bg-transparent px-3",children:[r&&K&&c.jsx(se,{style:{borderRadius:S==null?void 0:S.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{P(!T)},className:"h-8 shrink-0 p-2",children:T?c.jsx(i8,{className:"h-4 w-4"}):c.jsx(a8,{className:"h-4 w-4"})}),N==null?void 0:N.map((oe,Ne)=>{const fe=k===oe.id,Me=V===oe.id;return c.jsxs(nn,{draggable:!0,onDragStart:ke=>G(ke,Ne),onDragOver:Z,onDrop:ke=>Q(ke,Ne),style:{borderRadius:S==null?void 0:S.controlInputRadius},onClick:()=>L(oe.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:oe.id,children:[c.jsx(Vb,{enabled:_&&fe,text:oe.title,onSave:ke=>R(oe.id,ke),children:oe.title},oe.id),!_&&fe&&c.jsx("div",{title:Me?"Clear default sheet":"Set as default sheet",children:c.jsx(JT,{className:X("ml-1 size-3 cursor-pointer transition-all",Me?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:ke=>{ke.stopPropagation(),Y(oe.id,oe.title||"Sheet")}})}),_&&fe&&N.length>1&&c.jsx(St,{className:"ml-1 size-3",onClick:()=>l(!0)})]},oe.id)}),_&&c.jsx("div",{style:{borderRadius:(me=(he=S==null?void 0:S.chart)==null?void 0:he.options)==null?void 0:me.borderRadius},className:"flex h-7 shrink-0 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:B,children:c.jsx(Tr,{className:"size-3"})})]})}function de(){return c.jsx("div",{ref:i,style:{},className:"grow",children:N==null?void 0:N.map(he=>c.jsx(pr,{style:{backgroundColor:U()},className:X("mt-0",{}),value:he.id,children:c.jsx(c6e,{sheet:he})},he.id))})}function ce(){var he;return c.jsxs(Os,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",S==null?void 0:S.dashboardTabsContainer),onValueChange:me=>{L(me)},value:k||((he=N==null?void 0:N[0])==null?void 0:he.id),children:[le(),c.jsx(tl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:de()}),c.jsx(z6e,{open:a,setOpen:l})]})}const Ce=C.useCallback(he=>{g("dashboard",he)},[g]);return N?c.jsxs(c.Fragment,{children:[c.jsx(MXe,{}),c.jsx(AXe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(aQ,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",w&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(I_,{children:ce()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx($6e,{open:v,onTabClick:H,withHandle:!0,disabled:!v}),c.jsx(I_,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:q,defaultSize:v?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(SXe,{open:v,setOpen:H,isFullscreen:w,onFullscreenChange:he=>m(he?"dashboard":null),fullscreenContainer:y})})})]})]}),c.jsx("div",{ref:Ce,className:X("absolute inset-0",!w&&"pointer-events-none")}),te&&c.jsx("div",{className:X("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:c.jsx(se,{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:()=>{d.current||H(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:c.jsx(q1,{className:"h-5 w-5"})})})]})]}):null}function RA({children:e}){return c.jsx(Za,{style:{height:"100%",width:"100%"},children:c.jsx(eoe,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Ln,{delayDuration:0,children:e})})})}function qee({children:e,preferences:t}){const{currentUser:n}=Ps(),r=C.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 c.jsx(m7.Provider,{value:r,children:c.jsx(AR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function PXe(e=2e3,t=500){const n=Toe(),[r,s]=C.useState(!1),[o,i]=C.useState(!1),a=C.useRef(null);return C.useEffect(()=>{const l=setTimeout(()=>s(!0),e);return()=>clearTimeout(l)},[e]),C.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 AA({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=PXe(e,t);return C.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]),c.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 Yee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(rl,{FallbackComponent:gS,children:c.jsxs(PT,{dashboardProps:e,children:[c.jsx(AA,{componentType:"dashboard",componentId:e.id}),c.jsx(RA,{children:c.jsx(qee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(JD,{...e,type:"dashboard",children:c.jsx(Wee,{})})})})})]})})}function g6(e,t){return e.map(n=>({...n,fieldScope:t}))}function OXe(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function b6(e){if(sc(e)||Ux(e))return e.expression}function PA(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=kD(),i=Ae(g=>g.frame.calculatedFields),a=Ae(g=>g.card.config),l=C.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=C.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=C.useMemo(()=>i!=null&&i.length?g6(i,"dashboard"):[],[i]),f=C.useMemo(()=>{const g=new Map;return d.forEach(b=>{const x=`${b.name}-${b.role||"unknown"}`;g.set(x,b)}),g},[d]),h=C.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(sc),b=((a==null?void 0:a.groupByColumns)||[]).filter(Ux),y=OXe([...g,...b]).filter(v=>{const w=`${v.name}-${v.role||"unknown"}`,j=f.get(w);if(!j)return!0;const S=b6(v),N=b6(j);return S&&N?S!==N:!0});return g6(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=C.useMemo(()=>[...l,...d,...h,...u],[h,u,d,l]),p=C.useMemo(()=>t.filter(g=>g.entityId!==pz),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:l,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function OA(e){const{tokenProps:t,authToken:n}=Xe(),r=t==null?void 0:t.apiServiceUrl;return En({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return rr(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 Gee(e,t,n){if(t==="source")return{isValid:!0};const r=yr(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 Kee(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=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const Zee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=OA(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=cr(),h=Ae(I=>I.card.type),m=e==null?void 0:e.id,p=(I,$)=>{if(I.id)return I.id;const V=I.qualifiedEntityName||I.entityName||$;return`${$}-${V}-${I.name}`},g=C.useCallback(I=>{if(!(e!=null&&e.config))return[];switch(I){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:p($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:p($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:p($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:p($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return(e.config.detailColumns||[]).map($=>({id:p($,"detailColumns"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,dateFormat:$.dateFormat,customFormat:$.customFormat}));case"source":return[];default:return[]}},[e]),b=C.useCallback((I,$)=>{if(m)switch(I){case"groupBy":{r(m,{groupByColumns:$});break}case"metrics":{r(m,{metricColumns:$});break}case"pivotBy":{r(m,{pivotByColumns:$});break}case"sortBy":{r(m,{sortByColumns:$});break}case"detailColumns":{r(m,{detailColumns:$});break}}},[m,r]),x=C.useCallback((I,$,V)=>{if(!m)return;const W=g(I),L=W[$];if(L)switch(I){case"groupBy":s(m,L.id,{label:V});break;case"metrics":o(m,L.id,{label:V});break;case"pivotBy":i(m,L.id,{label:V});break;case"sortBy":a(m,L.id,{label:V});break;case"detailColumns":{const R=W.map((z,F)=>F===$?{...z,label:V}:z);r(m,{detailColumns:R});break}}},[m,g,s,o,i,a,r]),y=C.useCallback((I,$)=>{if(!m)return;const W=g("metrics")[I];W&&o(m,W.id,{aggregate:$,label:IU(W.name,$)})},[m,g,o]),v=C.useCallback((I,$,V,W="groupBy")=>{if(!m)return;const L=g(W),R=L[I];if(!R)return;const z={dateFormat:$,customFormat:$==="custom"&&V?V:void 0};if(W==="detailColumns"){const F=L.map((A,H)=>H===I?{...A,...z}:A);r(m,{detailColumns:F});return}s(m,R.id,z)},[m,g,r,s]),w=C.useCallback((I,$)=>{if(!m)return;const W=g("groupBy")[I];W&&s(m,W.id,{granularity:$})},[m,g,s]),j=C.useCallback((I,$)=>{if(!m)return;const W=g("metrics")[I];W&&o(m,W.id,{aliasTemplate:$})},[m,g,o]),S=C.useCallback((I,$)=>{if(console.log("handleValueAliasesChange",I,$),!m)return;console.log("handleValueAliasesChange",I,$);const W=g("metrics")[I];W&&(console.log("handleValueAliasesChange",$),o(m,W.id,{valueAliases:$}))},[m,g,o]),N=C.useCallback(I=>{if(!m)return;if(g("metrics").length===0){ze.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(m,{comparisonType:I})},[m,r,g]),E=C.useCallback(I=>{m&&r(m,{showTrendline:I})},[m,r]),_=C.useCallback(I=>{m&&r(m,{trendlineWindow:I})},[m,r]),k=C.useCallback(I=>{m&&r(m,{trendlineGranularity:I})},[m,r]),M=C.useCallback(I=>{m&&r(m,{targetValue:I})},[m,r]),T=C.useCallback(async I=>{var A;if(!m)return;const $=[...g("groupBy"),...g("pivotBy"),...g("metrics"),...g("sortBy"),...g("detailColumns")],V=I,W=G1e(V,$,{joinPlan:(A=e==null?void 0:e.config)==null?void 0:A.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!W.isValid){W.showError&&TU();return}const L=X1e(V,$,h);if(!L){ze.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const R=Gee(V,L,h);if(!R.isValid){ze.error("Invalid Field Type",{description:R.reason,position:"top-center",duration:3e3});return}const z=g(L);if(MU(V,z))return;const F=RU(V,L,z);if(F){const H=[...z,F];b(L,H),L==="metrics"&&Kee(h,e==null?void 0:e.config,r,m,H)}},[m,e==null?void 0:e.config,g,b,t,n,h,r]),P=C.useCallback((I,$)=>{if(!m)return;const W=g(I)[$];if(W){if(I!=="sortBy"){const L=g("sortBy"),R=L.filter(z=>!(z.name===W.name&&z.qualifiedEntityName===W.qualifiedEntityName));R.length!==L.length&&r(m,{sortByColumns:R})}switch(I){case"groupBy":l(m,W.id);break;case"metrics":u(m,W.id);break;case"pivotBy":d(m,W.id);break;case"sortBy":f(m,W.id);break;case"detailColumns":{r(m,{detailColumns:(g("detailColumns")||[]).filter((L,R)=>R!==$)});break}}}},[m,g,l,u,d,f,r]);return{getFieldsForContainer:g,setFieldsForContainer:b,updateLabel:x,handleAggregationChange:y,handleDateFormatChange:v,handleGranularityChange:w,handleAliasTemplateChange:j,handleValueAliasesChange:S,removeField:P,handleFieldClick:T,handleKpiComparisonTypeChange:N,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:M,cardType:h}};function YS(e,t){var De,qe,He,Fe,yt;const{tokenProps:n}=Xe(),r=so(),s=Xe().authToken||e,o=Ae(je=>je.selectedConnectionId),i=Ae(je=>je.card),{queryKey:a}=phe(i),l=Ae(je=>je.selectedDatamodelId),u=Ae(je=>je.isDevMode),d=Ae(je=>je.selectedDatabaseName),f=Ae(je=>je.selectedSchemaName),h=Ae(je=>je.selectedTableName),m=Ae(je=>je.actions.setSelectedConnectionId),p=Ae(je=>je.actions.setSelectedDatamodelId),g=Ae(je=>je.actions.setSelectedDatabaseName),b=Ae(je=>je.actions.setSelectedSchemaName),x=Ae(je=>je.actions.setSelectedTableName);Ae(je=>je.actions.setCardSql);const{setQueryConfig:y}=cr();function v(je){var Ct;return o&&je==="API"?!1:o&&je==="S3"?!0:!(!o||!d||d==="NA"||((Ct=_==null?void 0:_.capabilities)==null?void 0:Ct.path.includes("schema"))&&!f)}function w(je){return o&&je?!(je==="API"||je==="S3"):!1}const{refetchConnections:j,connectionsData:S,isConnectionsLoading:N,isConnectionsError:E,selectedConnection:_}=Ci(e),{refetch:k,data:M,isLoading:T,isError:P}=En({queryKey:["models",o],queryFn:()=>rr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),O=_==null?void 0:_.type,I=(_==null?void 0:_.type)==="API"||(_==null?void 0:_.type)==="S3",{data:$,isLoading:V,isFetching:W,isError:L,refetch:R}=En({queryKey:["databases",o],queryFn:()=>rr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(O)}),{data:z,isLoading:F,isFetching:A,isError:H,refetch:B}=En({queryKey:["schemas",o,d],queryFn:()=>rr(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:Y,isLoading:q,isFetching:U,isError:G,refetch:Z}=En({queryKey:["tables",o,d,f],queryFn:()=>rr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(O)}),{columns:Q,isColumnsLoading:K,isColumnsFetching:te,isColumnsError:le,refetchColumns:de}=AU(e);C.useEffect(()=>{(O==="S3"||O==="API")&&(g(""),b(""),p(""),O==="API"&&x("api"))},[O,x,g,b,p]);const ce=(_==null?void 0:_.type)==="API"?(De=_==null?void 0:_.type)==null?void 0:De.toLowerCase():h||"",Ce=I?"":f||"";function ge(je){x(je),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function he(je){b(je),x("")}function me(je){g(je==="none"?"":je),b(""),x(""),je!=="none"&&je!==""&&p("")}function oe(je){m(je)}function Ne(je){p(je==="none"?"":je),je!=="none"&&je!==""&&g("")}$&&((qe=$==null?void 0:$.databases)==null?void 0:qe.length)>0,z&&((He=z==null?void 0:z.schemas)==null?void 0:He.length)>0;const fe=S==null?void 0:S.connections.map(je=>({id:je.id,name:je.name,type:je.type})),Me=(Fe=M==null?void 0:M.datamodels)==null?void 0:Fe.map(je=>({id:je.id,name:je.name})),ke=$==null?void 0:$.databases.map(je=>({id:je.database_name,name:je.database_name})),ie=z==null?void 0:z.schemas.map(je=>({id:je.schema_name,name:je.schema_name})),xe=Y==null?void 0:Y.tables.map(je=>({id:je.table_name,name:je.table_name})),Oe=(yt=M==null?void 0:M.datamodels.find(je=>je.id===l))==null?void 0:yt.name,be=_!=null&&_.capabilities?qv({schemaName:Ce,tableName:ce,modelName:Oe,databaseName:d||"",capabilities:_.capabilities}):ce;return{connectionItems:fe,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:N,isConnectionsError:E,modelItems:Me,selectedDatamodelId:l,selectedDatamodelName:Oe,isModelsLoading:T,isModelsError:P,selectedDatabaseName:d,databaseItems:ke,isDatabasesLoadingOrFetching:V||W,isDatabaseError:L,schemaItems:ie,selectedSchemaName:f,isSchemaLoadingOrFetching:F||A,isSchemaError:H,tableItems:xe,selectedTableName:h,isTableLoadingOrFetching:q||U,isTableError:G,columns:Q,isColumnsLoadingOrFetching:K||te,isColumnsError:le,isNonDbConnection:I,connectionType:O,tableName:ce,formattedTableName:be,schemaName:Ce,refetchConnections:j,refetchModels:k,refetchDatabases:R,refetchSchemas:B,refetchTables:Z,refetchColumns:de,handleConnectionChange:oe,handleDatamodelChange:Ne,handleDatabaseChange:me,handleSchemaChange:he,handleTableChange:ge}}function dv(e){return`${e}-${Rr()}`}function x6(e,t){const n=pi(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 FXe(e,t){const n=pi(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function FA(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 Xee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Qee(){const e=Ae(N=>N.sqlGen),t=Ae(N=>N.isDevMode),n=Ae(N=>N.card.dataSource),r=Ae(N=>{var E,_;return(_=(E=N.card)==null?void 0:E.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=FA(n),a=Xee(n),l=Ae(N=>N.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=cr(),{modelItems:g,selectedDatamodelName:b}=YS(),{selectedConnection:x}=Ci(),y=x==null?void 0:x.capabilities,v=N=>({column_name:N.name,data_type:N.dataType,label:N.label,description:N.description});return{handleDevModeFieldClick:N=>{var _;if(!t)return;const E=v(N);if(t&&a&&s&&y){const k=CT(E,e);m(k);const M=(_=g==null?void 0:g.find(P=>P.id===l))==null?void 0:_.name,T=wT(k,o||"",s,M||"",i||"",y,N.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(yx(E.data_type))if(r&&r.length>0){const k={...E,role:"groupby",id:dv(E.column_name),name:E.column_name,type:E.data_type};d(k)}else{const k={...E,role:"metric",id:dv(E.column_name),name:E.column_name,label:x6(E.column_name,"COUNT"),type:E.data_type,aggregate:"COUNT"};u(k)}if(Ki(E.data_type)){const k={...E,role:"groupby",id:dv(E.column_name),name:E.column_name,type:E.data_type,label:FXe(E.column_name,"month"),granularity:"month"};d(k)}if(Gi(E.data_type)){const k={...E,role:"metric",id:dv(E.column_name),name:E.column_name,label:x6(E.column_name,"SUM"),type:E.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const N=qv({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});p(!1);const _=(x==null?void 0:x.type)==="MSSQL"?`SELECT top 10 * FROM ${N}`:`SELECT * FROM ${N} LIMIT 10`;f(_),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const N=qv({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${N}`),h(!0)},isNumberField:N=>Gi(N.dataType)}}function $Xe(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>ab(o)).join("."),s=ab(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function Jee(){const e=J(a=>a.dashboard.filters)||[],t=J(a=>a.selectedSheetId),n=J(a=>a.actions.addFilter),r=J(a=>a.actions.removeFilter),{removeFilterValues:s}=Wt(),{selectedConnection:o}=Ci();function i(a,l="sheet"){const{qualifiedColumnName:u,qualifiedTableName:d,formattedColumnName:f}=$Xe(a);let h;if(l==="sheet"&&t?h=oke(e,u,d,t):h=e==null?void 0:e.find(m=>wm(m.column)===wm(u)),h)s(h.id),r(h.id);else{const m=Rr(),p=l==="sheet"&&t?[t]:void 0;return n({id:m,location:l,column:u,title:a.label||a.name,dataType:a.dataType,qualifiedTableName:d,connectionId:(o==null?void 0:o.id)||"",operation:"in",applyToSheetIds:p,sql:wK(a.dataType,d,f)}),m}}return{assignFilter:i}}function LXe({column:e}){const[t,n]=C.useState(!1),r=Ae(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=FA(r),a=Ae(y=>y.selectedDatamodelId),l=Ae(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=YS(),f=d==null?void 0:d.capabilities,h=Ae(y=>y.actions.setSqlGen),m=Ae(y=>y.actions.setCardSql),p=Ae(y=>y.actions.setRunSql),g=Xee(r);function b(y,v){var E,_;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const w=CT(y,l,v),j=(E=u==null?void 0:u.find(k=>k.id===a))==null?void 0:E.name;if(h(w),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const S=(_=y.qualifiedFieldName)==null?void 0:_.split(".").slice(0,-1).join("."),N=wT(w,o||"",s,j||"",i||"",f,S);N&&(m(N),p(!0)),n(!1)}function x(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>b(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>b(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>b(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>b(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>b(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return g?c.jsxs(Wm,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(qm,{asChild:!0,children:c.jsx(Pm,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Mf,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:x()})]}):null}function zXe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function y6({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=Ae(K=>K.isDevMode),a=t==="filter"||t==="inline-filter",l=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=J(K=>K.dashboard.filters),d=J(K=>K.selectedSheetId),f=J(K=>K.actions.removeFilter),{removeFilterValues:h}=Wt(),{assignFilter:m}=Jee(),p=t==="filter"?oc(u,d):u,g=t==="filter"?p==null?void 0:p.find(K=>{if(K.title===e.name)return!0;const te=wm(K.column||""),le=wm(e.name);return te.endsWith(`.${le}`)||te===le}):void 0,b=!!g,x=t==="inline-filter"&&(s==null?void 0:s.some(K=>K.column===e.qualifiedFieldName||K.column===e.name)),y=b||x,v=g&&a?u==null?void 0:u.find(K=>K.id===g.id):void 0,w=v&&(v.applyToSheetIds&&v.applyToSheetIds.length>1||v.excludeSheetIds&&v.excludeSheetIds.length>0||!v.applyToSheetIds&&!v.excludeSheetIds&&!v.sheetId);a&&y&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:y,activeFilterOnSheet:g?{id:g.id,title:g.title,column:g.column,applyToSheetIds:g.applyToSheetIds,excludeSheetIds:g.excludeSheetIds}:null,activeFilterForField:v?{id:v.id,title:v.title,column:v.column,applyToSheetIds:v.applyToSheetIds,excludeSheetIds:v.excludeSheetIds}:null,isMultiSheetFilter:w,selectedSheetId:d});const[j,S]=C.useState(!1),[N,E]=C.useState(null),{attributes:_,listeners:k,setNodeRef:M,transform:T,transition:P,isDragging:O}=Ey({id:e.id,disabled:l}),[I,$]=C.useState(!1),V=Ae(K=>K.card),{handleFieldClick:W}=Zee(V),{handleDevModeFieldClick:L,isNumberField:R}=Qee(),z=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),E(null),S(!1)},F=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&w?(E(e),S(!0)):m(e,"sheet"):i?L(e):W(e)},A={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},H={transform:yi.Transform.toString(T),transition:P},B=()=>{if(!n||a)return{};const te={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...te},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...te},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...te}}[n.state]||te};function Y(K){return K==="domain"?{label:"Domain",Icon:Sx,className:"border-border bg-muted text-foreground"}:K==="dashboard"?{label:"Dashboard",Icon:qT,className:"border-border bg-muted/70 text-foreground"}:{label:"Card",Icon:S8,className:"border-border bg-muted/40 text-foreground"}}const q=B(),U=e.fieldScope,G=U?Y(U):null,Z=Pw(e),Q=Z&&sc(e);return c.jsxs("div",{ref:M,style:H,...l?{}:_,...l?{}:k,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",O&&"scale-95 opacity-50",!O&&"border",q.borderColor||"border-transparent",q.bgColor||"",q.hoverBorderColor,q.hoverBgColor||"hover:bg-muted",q.opacity,q.cursor,b&&"border-accent-foreground/20 bg-accent",x&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!l&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:F,children:[c.jsxs("div",{className:"relative shrink-0",children:[_m(e.dataType),Z&&c.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",Q?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),c.jsx(Ln,{children:c.jsxs(an,{children:[c.jsx(ln,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${I?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(dn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(zXe,{field:e,fieldState:n})})]})}),t==="editor"&&G&&c.jsx("span",{title:G.label,className:X("shrink-0 rounded-full border p-1",G.className),children:c.jsx(G.Icon,{className:"h-3.5 w-3.5"})}),i&&!a&&R(e)&&c.jsx("div",{onClick:K=>K.stopPropagation(),children:c.jsx(LXe,{column:A})}),o&&c.jsx("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:o})]}),I&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(Uo,{className:"",children:c.jsxs(Qi,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(j8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(iie,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Ve,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Um,{open:j,onOpenChange:S,children:c.jsxs(Sf,{children:[c.jsxs(jf,{children:[c.jsx(kf,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(Ef,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(Nf,{children:[c.jsx(Tf,{children:"Cancel"}),c.jsx(_f,{onClick:z,children:"Remove Filter"})]})]})})]})}var da="Accordion",BXe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[$A,VXe,HXe]=Ex(da),[GS]=Lr(da,[HXe,gW]),LA=gW(),ete=C.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx($A.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(YXe,{...o,ref:t}):c.jsx(qXe,{...s,ref:t})})});ete.displayName=da;var[tte,UXe]=GS(da),[nte,WXe]=GS(da,{collapsible:!1}),qXe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=ss({prop:n,defaultProp:r??"",onChange:s,caller:da});return c.jsx(tte,{scope:e.__scopeAccordion,value:C.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:C.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(nte,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(rte,{...i,ref:t})})})}),YXe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=ss({prop:n,defaultProp:r??[],onChange:s,caller:da}),l=C.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=C.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(tte,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(nte,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(rte,{...o,ref:t})})})}),[GXe,KS]=GS(da),rte=C.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=C.useRef(null),l=ut(a,t),u=VXe(n),f=bu(s)==="ltr",h=Ie(e.onKeyDown,m=>{var E;if(!BXe.includes(m.key))return;const p=m.target,g=u().filter(_=>{var k;return!((k=_.ref.current)!=null&&k.disabled)}),b=g.findIndex(_=>_.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,w=x-1,j=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(m.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?j():S());break;case"ArrowDown":o==="vertical"&&j();break;case"ArrowLeft":o==="horizontal"&&(f?S():j());break;case"ArrowUp":o==="vertical"&&S();break}const N=y%x;(E=g[N].ref.current)==null||E.focus()});return c.jsx(GXe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx($A.Slot,{scope:n,children:c.jsx(Ze.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),E1="AccordionItem",[KXe,zA]=GS(E1),ste=C.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=KS(E1,n),i=UXe(E1,n),a=LA(n),l=xr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(KXe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(yW,{"data-orientation":o.orientation,"data-state":ute(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});ste.displayName=E1;var ote="AccordionHeader",ite=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(da,n),o=zA(ote,n);return c.jsx(Ze.h3,{"data-orientation":s.orientation,"data-state":ute(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});ite.displayName=ote;var rT="AccordionTrigger",ate=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(da,n),o=zA(rT,n),i=WXe(rT,n),a=LA(n);return c.jsx($A.ItemSlot,{scope:n,children:c.jsx(aSe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});ate.displayName=rT;var lte="AccordionContent",cte=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(da,n),o=zA(lte,n),i=LA(n);return c.jsx(lSe,{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}})});cte.displayName=lte;function ute(e){return e?"open":"closed"}var ZXe=ete,XXe=ste,QXe=ite,dte=ate,fte=cte;const BA=ZXe,rx=D.forwardRef(({className:e,...t},n)=>c.jsx(XXe,{ref:n,className:X("border-b",e),...t}));rx.displayName="AccordionItem";const sx=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(QXe,{className:"flex",children:c.jsxs(dte,{ref:r,className:X("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,c.jsx(kr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));sx.displayName=dte.displayName;const ox=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(fte,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:X("pb-4 pt-0",e),children:t})}));ox.displayName=fte.displayName;let hte=(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 ix=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],fl=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),Nl=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function v6(e,t,n,r,s,o,i,a,l,u){const d=ix.find(x=>x.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(l===void 0||Number.isNaN(l))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(l)),h=[n],m=l}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=fl(e);return{id:i||`calc_${hte(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",aggregate:"SUM",expression:f,calculatedFormula:p,entityId:o,entityName:cu,entityType:"table",description:`Calculated field: ${e}`}}function JXe(e){var r,s;const t=ix.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 eQe(e,t,n,r,s,o){const i=fl(e);return{id:o||`calc_dim_${hte(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:cu,entityType:"table",description:`Calculated field: ${e.trim()}`}}function tQe(){const{domainCalculatedFields:e}=PA(),t=C.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=C.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function nQe({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(l=>s.includes(l)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return c.jsx(Os,{value:a,onValueChange:l=>t(l),className:"w-full",children:c.jsx(ys,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(l=>c.jsx(nn,{value:l,disabled:i,className:"text-xs",children:l==="metric"?"Calculated Metric":"Calculated Dimension"},l))})})}function rQe({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,l=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),p=h.toLowerCase();return m.startsWith(`${p}.`)?f.slice(h.length+1):f},d=(f,h)=>{const p=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),g=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const b of g){const x=u(p,b);if(x!==p)return x}return p.includes(".")&&p.split(".").pop()||p};return c.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&c.jsxs("div",{className:"relative",children:[c.jsx(Ko,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(jn,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&c.jsx("button",{type:"button",onClick:()=>n(""),className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",children:c.jsx(St,{className:"size-3.5"})})]}),c.jsx(tl,{className:"min-h-0 flex-1",children:e.length===0?c.jsx("div",{className:"rounded-md border border-dashed border-muted px-3 py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):c.jsx(BA,{type:"multiple",defaultValue:l,className:"space-y-2",children:e.map(f=>c.jsxs(rx,{value:f.id,className:"border-none",children:[c.jsx(sx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),c.jsx(Ve,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),c.jsx(ox,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:f.fields.map(h=>{const m=i.has(h.id),p=!h.isCompatible||o,g=h.isCalculated&&h.role==="metric",b=d(h,f.label);return c.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:X("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[c.jsxs("div",{className:"relative shrink-0",children:[_m(h.dataType),h.isCalculated&&c.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:X("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:b})}),m&&c.jsx(Ve,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function sQe({value:e,onChange:t,allowCustom:n,disabled:r}){const s=ix.filter(l=>n?!0:l.id!=="custom"),i=!s.some(l=>l.id==="custom")&&e==="custom"?[...s,ix.find(l=>l.id==="custom")]:s,a=i.find(l=>l.id===e);return c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ot,{value:e,onValueChange:l=>t(l),disabled:r,children:[c.jsx(nt,{children:c.jsx(at,{})}),c.jsx(rt,{children:c.jsxs(WD,{children:[c.jsx(BC,{children:"OPERATIONS"}),i.map(l=>c.jsx(ve,{value:l.id,children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-mono text-sm",children:l.symbol}),c.jsx("span",{children:l.label})]})},l.id))]})})]}),a&&c.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const oQe={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function iQe({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?yr(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],l=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return c.jsxs(ot,{value:e,onValueChange:u=>t(u),disabled:n,children:[c.jsx(nt,{className:"h-9",children:c.jsx(at,{})}),c.jsx(rt,{children:l.map(u=>c.jsx(ve,{value:u,children:oQe[u]},u))})]})}const aQe=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function w6({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:l,disabled:u}){const d=(t==null?void 0:t.field.id)||"",f=r!=null&&r.length?n.filter(h=>!r.includes(h.id)):n;return c.jsxs("div",{className:X("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[c.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),c.jsxs("div",{className:"flex flex-1 gap-2",children:[c.jsxs(ot,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[c.jsx(nt,{className:"h-9 flex-1",children:c.jsx(at,{placeholder:"Select field"})}),c.jsx(rt,{children:f.map(h=>c.jsx(ve,{value:h.id,children:aQe(h)},h.id))})]}),c.jsx("div",{className:"w-36",children:c.jsx(iQe,{value:(t==null?void 0:t.aggregate)||"SUM",onChange:o,disabled:u||(t==null?void 0:t.isCalculatedField),fieldDataType:t==null?void 0:t.field.dataType,allowMedian:l})})]}),t&&c.jsx(se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:c.jsx(St,{className:"h-3.5 w-3.5"})})]})}const C6=C.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,disabled:o},i){return c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"text-sm font-medium",children:"Expression"}),s&&c.jsxs(se,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:o,className:"h-7 gap-2 text-xs",children:[c.jsx(q1,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]}),c.jsx(Yb,{ref:i,value:t,onChange:a=>n(a.target.value),disabled:o,placeholder:"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-[140px] font-mono text-xs"})]})});function lQe({result:e}){const t=e.errors.length>0;return c.jsxs("div",{className:X("rounded-md border px-3 py-2 text-xs",t?"border-destructive/40 bg-destructive/10 text-destructive":"border-emerald-500/30 bg-emerald-500/10 text-emerald-700"),children:[c.jsx("div",{className:"font-medium",children:t?"Validation Failed":"Validation Passed"}),e.tokens.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Tokens Found"}),e.tokens.map(n=>c.jsx("div",{children:n.field?`{${n.token}} -> ${n.field.qualifiedFieldName||n.field.name}`:`{${n.token}}`},n.token))]}),e.errors.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Errors"}),e.errors.map((n,r)=>c.jsxs("div",{children:[n.message,n.suggestion?` (${n.suggestion})`:""]},`${n.code}-${r}`))]}),e.warnings.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Warnings"}),e.warnings.map((n,r)=>c.jsxs("div",{children:[n.message," ",n.suggestion]},`${n.code}-${r}`))]}),e.inferredDataType&&c.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground",children:["Inferred Output Type: ",e.inferredDataType]})]})}function S6({onValidate:e,isValidating:t,validationResult:n,fallbackResult:r,error:s,showFallback:o,disabled:i}){return c.jsxs("div",{className:"space-y-2",children:[c.jsx(se,{type:"button",variant:"outline",onClick:e,disabled:t||i,className:"h-8",children:t?"Validating...":"Validate Expression"}),s&&c.jsx("div",{className:"text-xs text-destructive",children:s}),(n||o)&&c.jsx(lQe,{result:n||r})]})}function cQe({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return c.jsxs("div",{className:"space-y-3 border-t border-border pt-4",children:[c.jsx(ae,{children:"Availability"}),c.jsxs(Qs,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(bn,{id:"scope-card",value:"card"}),c.jsx(ae,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(bn,{id:"scope-dashboard",value:"dashboard"}),c.jsx(ae,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(bn,{id:"scope-domain",value:"domain"}),c.jsx(ae,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&c.jsx("p",{className:"text-xs text-red-500",children:s})]})}function uQe({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return c.jsxs("div",{className:"space-y-3 rounded-md border border-muted bg-muted/30 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"domain-description",children:"Description"}),c.jsx(vu,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:X("text-sm",s&&"border-red-500"),rows:3,disabled:o}),s&&c.jsx("p",{className:"text-xs text-red-500",children:s})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"domain-tags",children:"Tags (optional)"}),c.jsx(mn,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o})]}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function dQe({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=Xe(),[o,i]=C.useState(!1),[a,l]=C.useState(null);return{generateExpression:C.useCallback(async d=>{var f;if(!e)return l("AI generation is not available"),null;if(!d.trim())return l("Describe what you want to calculate"),null;i(!0),l(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType})),fieldType:n},options:{dialect:r}},m=await eo(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return l((h==null?void 0:h.error)||(h==null?void 0:h.message)||"AI generation failed"),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function fQe({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,l]=C.useState(""),[u,d]=C.useState(""),[f,h]=C.useState(""),{generateExpression:m,isGenerating:p,error:g}=dQe({endpoint:o,availableFields:n,fieldType:r,dialect:i}),b=C.useMemo(()=>{const S=f.trim().toLowerCase();return S?n.filter(N=>[N.label,N.baseLabel,N.name,N.tokenLabel,N.entityName,N.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(S)):n},[n,f]),x=S=>{const E=(S.name||S.baseLabel||S.label||S.tokenLabel||"").trim();return E.includes(".")&&E.split(".").pop()||E},y=S=>{const N=S.entityName||S.qualifiedEntityName||"";return N?N==="SEMAPHOR_CALCULATED_FIELD"?"Calculated":N.includes(".")&&N.split(".").pop()||N:"—"},v=async()=>{const S=await m(a.trim());S&&d(S)},w=()=>{u.trim()&&(s(u.trim()),l(""),d(""),t(!1))},j=()=>{l(""),d(""),h(""),t(!1)};return c.jsx(Gr,{open:e,onOpenChange:S=>{S?t(!0):j()},children:c.jsxs(zr,{className:"max-w-3xl",children:[c.jsxs(Br,{children:[c.jsx(Vr,{children:"Generate Expression with AI"}),c.jsx(is,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),c.jsx(Yb,{id:"ai-prompt",value:a,onChange:S=>l(S.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[c.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),c.jsx(se,{size:"sm",onClick:v,disabled:p||!a.trim(),children:p?"Generating...":u?"Regenerate":"Generate"})]}),g&&c.jsx("p",{className:"text-xs text-destructive",children:g})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Available fields"}),c.jsxs("div",{className:"relative",children:[c.jsx(Ko,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),c.jsx(mn,{value:f,onChange:S=>h(S.target.value),placeholder:"Search fields...",className:"pl-9"})]}),c.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:c.jsx("div",{className:"max-h-48 overflow-y-auto",children:c.jsxs("table",{className:"w-full text-sm",children:[c.jsx("thead",{className:"sticky top-0 z-10 border-b bg-muted",children:c.jsxs("tr",{children:[c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Field"}),c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Type"}),c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Category"})]})}),c.jsx("tbody",{className:"divide-y",children:b.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:3,className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."})}):b.map(S=>c.jsxs("tr",{className:"hover:bg-muted/30",children:[c.jsx("td",{className:"px-3 py-1.5 font-mono text-xs",children:x(S)}),c.jsx("td",{className:"px-3 py-1.5",children:c.jsx(Ve,{variant:"secondary",className:"px-1.5 py-0 text-[11px]",children:S.dataType})}),c.jsx("td",{className:"px-3 py-1.5 text-sm text-muted-foreground",children:y(S)})]},S.id))})]})})})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Generated expression"}),c.jsx(Yb,{value:u,readOnly:!0,rows:2,className:"font-mono text-sm"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Review the generated expression before using it."})]})]}),c.jsxs(os,{className:"gap-2",children:[c.jsx(se,{variant:"ghost",onClick:j,children:"Cancel"}),c.jsx(se,{onClick:w,disabled:!u.trim(),children:"Use Expression"})]})]})})}const hQe=/\{([^}]+)\}/g;function ZS(e){return e.trim().toLowerCase()}function _1(e){return Array.from(e.matchAll(hQe)).map(t=>t[1]).filter(Boolean)}function mQe(e){const t=new Set,n=[];return e.forEach(r=>{const s=ZS(r);t.has(s)||(t.add(s),n.push(r))}),n}function VA(e){const t=new Map,n=(r,s)=>{const o=ZS(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 tg(e,t){const n=_1(e),r=mQe(n),s=VA(t),o=r.map(a=>{const l=s.get(ZS(a))||[];return l.length===1?l[0]:null}),i=r.filter((a,l)=>!o[l]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function j6(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${pQe(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function pQe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const gQe=e=>e.entityName===Qh||e.entityName===cu?"Calculated Fields":e.qualifiedEntityName?cb(e.entityName||e.qualifiedEntityName):cb(e.entityName||"Other"),bQe=e=>yr(e.dataType||"")==="number";function xQe(e,t,n){const r=new Set((n||[]).map(s=>Nl(s)));return e.filter(s=>{const o=Nl(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function yQe(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==cu?`${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 vQe(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||bQe(o);return{...o,isCompatible:i}}).filter(o=>r)}function wQe(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 CQe(e){const t=new Map;return e.forEach(n=>{var s;const r=n.qualifiedEntityName||n.entityName||"Other";t.has(r)||t.set(r,{id:r,label:gQe(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function SQe({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=C.useMemo(()=>xQe(e,t,r),[e,t,r]),a=C.useMemo(()=>yQe(i),[i]),l=C.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&sc(m)||m.role==="groupby"&&Ux(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=C.useMemo(()=>VA(l),[l]),d=C.useMemo(()=>vQe(l,t,s,o),[l,t,s,o]),f=C.useMemo(()=>wQe(d,n),[d,n]),h=C.useMemo(()=>CQe(f),[f]);return{allFields:l,filteredFields:f,groups:h,tokenCandidates:u}}const jQe=e=>{let t=0;for(const n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0},NQe=(e,t)=>{const n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return 0;if(!n.length)return r.length;if(!r.length)return n.length;const s=[];for(let o=0;o<=r.length;o+=1)s[o]=[o];for(let o=0;o<=n.length;o+=1)s[0][o]=o;for(let o=1;o<=r.length;o+=1)for(let i=1;i<=n.length;i+=1)r.charAt(o-1)===n.charAt(i-1)?s[o][i]=s[o-1][i-1]:s[o][i]=Math.min(s[o-1][i-1]+1,s[o][i-1]+1,s[o-1][i]+1);return s[r.length][n.length]},kQe=(e,t)=>t.map(r=>({candidate:r,distance:NQe(e,r)})).filter(r=>r.distance>0&&r.distance<=3).sort((r,s)=>r.distance-s.distance).slice(0,3).map(r=>r.candidate),EQe=(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){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}return"string"}},_Qe=e=>e.map(t=>({id:t.id,name:t.name,label:t.tokenLabel,dataType:t.dataType,entityName:t.entityName,role:t.role}));function TQe({expression:e,availableFields:t,excludeFieldIds:n,validationEndpoint:r,connectionId:s,dialect:o}){const{authToken:i}=Xe(),[a,l]=C.useState(null),[u,d]=C.useState(!1),[f,h]=C.useState(null),m=C.useMemo(()=>VA(t),[t]),p=C.useMemo(()=>{const x=[],y=[],v=e.trim();v||x.push({code:"SYNTAX_ERROR",message:"Expression is required"}),v&&!jQe(v)&&x.push({code:"SYNTAX_ERROR",message:"Unbalanced parentheses in expression"});const j=_1(e).map(N=>{const E=m.get(ZS(N))||[];if(!E.length){const M=Array.from(m.keys()),T=kQe(N,M),P=T.length?`Did you mean {${T[0]}}?`:void 0;return x.push({code:"UNKNOWN_TOKEN",message:`Unknown field token: {${N}}`,suggestion:P}),{token:N,field:null,error:"Unknown token"}}if(E.length>1)return x.push({code:"UNKNOWN_TOKEN",message:`Token {${N}} matches multiple fields. Use a disambiguated label.`}),{token:N,field:null,error:"Ambiguous token"};const _=E[0];return(n||[]).map(Nl).includes(Nl(_.id))?(x.push({code:"SELF_REFERENCE",message:"Cannot reference the field being edited"}),{token:N,field:null,error:"Self reference"}):{token:N,field:_}});/\bCASE\b/i.test(e)&&!/\bELSE\b/i.test(e)&&y.push({code:"MISSING_ELSE",message:"CASE expression missing ELSE clause",suggestion:"Add an ELSE branch to handle default values."}),/\//.test(e)&&!/NULLIF\s*\(/i.test(e)&&y.push({code:"DIVISION_BY_ZERO",message:"Division may result in divide-by-zero errors",suggestion:"Wrap the denominator in NULLIF(..., 0)."});const S=j.map(N=>N.field).filter(Boolean);return{isValid:x.length===0,tokens:j,errors:x,warnings:y,inferredDataType:EQe(e,S)}},[e,n,m]),g=C.useCallback(async()=>{var v;if(h(null),!r||!p.isValid)return l(p),p;const x=r,y={type:"calculated-field-expression",value:e,context:{availableFields:_Qe(t),connectionId:s,excludeFieldIds:n,dialect:o}};d(!0);try{const w=await eo(x,(i==null?void 0:i.accessToken)||"",y),j=w.errors||[],S=w.warnings||[],N={...p,isValid:w.valid&&j.length===0,errors:j,warnings:S,inferredDataType:((v=w.metadata)==null?void 0:v.inferredType)||p.inferredDataType};return l(N),N}catch(w){return h((w==null?void 0:w.error)||"Validation failed"),l(p),p}finally{d(!1)}},[r,p,e,t,s,n,o,i==null?void 0:i.accessToken]),b=C.useCallback(()=>{l(null),h(null)},[]);return{clientResult:p,validationResult:a,isValidating:u,serverError:f,validateExpression:g,resetValidation:b}}const N6=[{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"}],G2=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},mte=e=>yr(e.dataType||"")==="number",uh=e=>mte(e)?"SUM":"COUNT",K2=(e,t)=>mte(e)||t==="COUNT"||t==="DISTINCT"?t:uh(e);function Z2(e,t){if(e.role==="metric"){const n=e;return sc(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function rh(e,t){const n=e.role==="metric"&&sc(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function pte({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:l,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var zf;const{tokenProps:m}=Xe(),{selectedConnection:p}=EU(),g=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[b,x]=C.useState(f),[y,v]=C.useState(""),[w,j]=C.useState("ratio"),[S,N]=C.useState(null),[E,_]=C.useState(null),[k,M]=C.useState(1),[T,P]=C.useState(""),[O,I]=C.useState(null),[$,V]=C.useState("card"),[W,L]=C.useState(""),[R,z]=C.useState(""),[F,A]=C.useState({}),[H,B]=C.useState("A"),[Y,q]=C.useState(""),[U,G]=C.useState(!1),[Z,Q]=C.useState(null),[K,te]=C.useState(!1),[le,de]=C.useState(!1),[ce,Ce]=C.useState(!1),ge=C.useRef(null),he=C.useRef(!1),me=C.useRef(null),{userContext:oe}=Ps(),{metrics:Ne,dimensions:fe}=tQe(),Me=(oe==null?void 0:oe.type)==="organization",ke=!Me,ie=!!d&&Me,xe=ie&&!!a,Oe=ie&&!!l,be=!!(i||xe||Oe),De=!!i,qe=b==="metric"?xe:Oe,He=(zf=m==null?void 0:m.apiServiceUrl)==null?void 0:zf.replace(/\/$/,""),Fe=He?`${He}/v1/validate`:"/v1/validate",yt=He?`${He}/v1/ai/generate`:"/v1/ai/generate",je=C.useMemo(()=>{var Mt;const Se=[...n];return(((Mt=r==null?void 0:r.calculatedFormula)==null?void 0:Mt.inputFields)||[]).forEach(vn=>{Se.some(qn=>qn.id===vn.id||qn.qualifiedFieldName===vn.qualifiedFieldName||qn.name===vn.name)||Se.push(vn)}),Se},[n,r]),dt=H==="A"?S:E,Ct=b==="metric"&&w!=="custom"?dt==null?void 0:dt.aggregate:void 0,{allFields:Ye,groups:Yt}=SQe({fields:je,mode:b,searchTerm:Y,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:Ct,showIncompatible:!0}),Ge=Ye,{clientResult:et,validationResult:Be,validateExpression:Ke,isValidating:kt,serverError:pe,resetValidation:Re}=TQe({expression:T,availableFields:Ge,excludeFieldIds:r?[r.id]:void 0,validationEndpoint:Fe,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect}),re=(Be==null?void 0:Be.inferredDataType)||et.inferredDataType,_e=O||re||"string",We=ix.find(Se=>Se.id===w),it=C.useMemo(()=>{if(!y.trim())return!1;const Se=fl(y),lt=s==="domain"&&(r!=null&&r.name)?fl(r.name):null;return(b==="metric"?Ne:fe).some(vn=>{const Qt=fl(vn.name);return lt&&Qt===lt?!1:Qt===Se})},[fe,Ne,r,s,b,y]),zt=C.useMemo(()=>{if(b==="metric"&&w==="custom"){const{orderedFields:lt}=tg(T,Ge);return lt.filter(Mt=>!!Mt).map(Mt=>Mt.id)}const Se=[];return S!=null&&S.field.id&&Se.push(S.field.id),E!=null&&E.field.id&&Se.push(E.field.id),Se},[Ge,T,b,S,E,w]),un=Se=>{ke||(x(Se),Se==="dimension"&&$==="domain"&&!Oe&&V("card"),Se==="metric"&&$==="domain"&&!xe&&V("card"))},Dn=Se=>{ke||(j(Se),Se==="scale"&&_(null),Se==="custom"&&(N(null),_(null)))},Kr=()=>{v(""),j("ratio"),N(null),_(null),M(1),P(""),I(null),V("card"),L(""),z(""),A({}),q(""),G(!1),Q(null),te(!1),Ce(!1),Re(),t(!1)},Hr=C.useCallback(Se=>je.find(lt=>lt.qualifiedFieldName===Se.qualifiedFieldName||lt.name===Se.name)||Se,[je]),zs=C.useCallback(Se=>{if(!Se.calculatedFormula)return;const lt=Se.calculatedFormula;if(j(lt.operation),P(""),lt.operation==="scale"){const Qt=lt.inputFields[0];Qt&&N(rh(Hr(Qt),Qt.aggregate||"SUM")),M(lt.constant===void 0?1:lt.constant);return}if(lt.operation==="custom"){P(Ni(Se.expression||"",lt.inputFields||[])),N(null),_(null);return}const[Mt,vn]=lt.inputFields;Mt&&N(rh(Hr(Mt),Mt.aggregate||"SUM")),vn&&_(rh(Hr(vn),vn.aggregate||"SUM"))},[Hr]),Ni=C.useCallback((Se,lt)=>Se.replace(/\{field_(\d+)\}/g,(Mt,vn)=>{var Cr;const Qt=lt[Number(vn)];return Qt?`{${((Cr=Ge.find(ki=>ki.id===Qt.id))==null?void 0:Cr.tokenLabel)||Qt.label||Qt.name}}`:Mt}),[Ge]);C.useEffect(()=>{var Mt;if(!e){he.current=!1,me.current=null;return}const Se=r?`${r.role}-${r.id||r.name}`:"new";if(he.current&&me.current===Se)return;if(he.current=!0,me.current=Se,A({}),q(""),Ce(!1),Re(),r){const vn=r.tags||[];if(r.role==="metric"){x("metric"),v(r.label||r.name),V(s||"card"),L(r.description||""),z(vn.join(", ")),zs(r);return}x("dimension");const Qt=r;v(Qt.label||Qt.name),V(s||"card"),P(Ni(Qt.expression||"",((Mt=Qt.calculatedFormula)==null?void 0:Mt.inputFields)||[]));const qn=N6.some(Cr=>Cr.value===Qt.dataType)?Qt.dataType:"string";I(qn),L(Qt.description||""),z(vn.join(", "));return}const lt=h&&h.length>0?h.includes(f)?f:h[0]:f;x(lt),v(""),j("ratio"),N(null),_(null),M(1),P(""),I(null),V("card"),L(""),z("")},[e,r,s,f,h,zs,Ni,Re]);const Fu=Se=>{const lt=`{${Se}}`,Mt=ge.current;if(!Mt){P(Cr=>Cr+lt);return}const vn=Mt.selectionStart||0,Qt=Mt.selectionEnd||0,qn=`${T.slice(0,vn)}${lt}${T.slice(Qt)}`;P(qn),requestAnimationFrame(()=>{Mt.focus();const Cr=vn+lt.length;Mt.setSelectionRange(Cr,Cr)})},JS=Se=>{if(ke)return;if(b==="dimension"||w==="custom"){Fu(Se.tokenLabel||Se.label||Se.name);return}const lt=K2(Se,H==="A"?(S==null?void 0:S.aggregate)||uh(Se):(E==null?void 0:E.aggregate)||uh(Se)),Mt=rh(Se,lt);if(H==="A"){N(Mt),E||B("B");return}_(Mt),S||B("A")},Oy=(Se,lt)=>{if(!ke){if(Se==="A"&&S){N({...S,aggregate:lt});return}Se==="B"&&E&&_({...E,aggregate:lt})}},uc=async()=>{const Se={};if(y.trim()||(Se.name="Name is required"),w==="custom")T.trim()||(Se.expression="Expression is required"),_1(T).length===0&&(Se.expression=Se.expression||"Expression must include field tokens"),tg(T,Ge).unresolvedTokens.length>0&&(Se.expression=Se.expression||"Expression contains unknown or ambiguous tokens"),Se.expression||(await Ke()).isValid||(Se.expression="Fix validation errors before saving");else if(w==="scale")S||(Se.inputA="Please select a metric for input A"),Number.isNaN(k)&&(Se.constant="Please enter a valid multiplication factor");else{if(S||(Se.inputA="Please select a metric for input A"),E||(Se.inputB="Please select a metric for input B"),S&&E){const lt=S.field.id===E.field.id,Mt=S.aggregate===E.aggregate;lt&&Mt&&(Se.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const lt=Nl(r.id);(Nl(S==null?void 0:S.field.id)===lt||Nl(E==null?void 0:E.field.id)===lt)&&(Se.inputs="Cannot reference the field being edited")}}return be&&($==="domain"&&!xe&&(Se.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(Se.description="Description is required for domain fields"),$==="domain"&&it&&(Se.name="A domain field with this name already exists")),A(Se),Object.keys(Se).length===0},ej=async()=>{const Se={};return y.trim()||(Se.name="Name is required"),T.trim()||(Se.expression="Expression is required"),_1(T).length===0&&(Se.expression=Se.expression||"Expression must include field tokens"),tg(T,Ge).unresolvedTokens.length>0&&(Se.expression=Se.expression||"Expression contains unknown or ambiguous tokens"),Se.expression||(await Ke()).isValid||(Se.expression="Fix validation errors before saving"),be&&($==="domain"&&!Oe&&(Se.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(Se.description="Description is required for domain fields"),$==="domain"&&it&&(Se.name="A domain field with this name already exists")),A(Se),Object.keys(Se).length===0},tj=()=>{const{orderedTokens:Se,orderedFields:lt}=tg(T,Ge),Mt=lt.filter(qn=>!!qn),vn=j6(T,Se),Qt=eQe(y,vn,Mt,_e,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...Qt}:Qt},nj=()=>{var vn;if(w==="custom"){const{orderedTokens:Qt,orderedFields:qn}=tg(T,Ge),Cr=qn.filter(Ot=>!!Ot),ki=(r==null?void 0:r.role)==="metric"?((vn=r.calculatedFormula)==null?void 0:vn.inputFields)||[]:[],No=new Map;ki.forEach(Ot=>{const dr=Nl(Ot.id);dr&&No.set(dr,Ot),Ot.qualifiedFieldName&&No.set(Ot.qualifiedFieldName,Ot),Ot.name&&No.set(Ot.name,Ot)});const dc=Cr.map(Ot=>{const dr=Nl(Ot.id),Ei=dr&&No.get(dr)||Ot.qualifiedFieldName&&No.get(Ot.qualifiedFieldName)||No.get(Ot.name),oj=((Ei==null?void 0:Ei.role)==="metric"?Ei.aggregate:void 0)||(Ot.role==="metric"?Ot.aggregate:void 0)||uh(Ot);return Z2(Ot,oj)}),Jn=j6(T,Qt),rn=v6(y,w,null,null,{},u,r==null?void 0:r.id,Jn,void 0,dc);return r&&r.role==="metric"?{...r,...rn}:rn}const Se=S?Z2(S.field,S.aggregate):null,lt=E?Z2(E.field,E.aggregate):null,Mt=v6(y,w,Se,lt,{},u,r==null?void 0:r.id,void 0,w==="scale"?k:void 0);return r&&r.role==="metric"?{...r,...Mt}:Mt},Fy=async Se=>{var Mt,vn,Qt;if(b==="dimension"){const qn=tj();if(Se==="dashboard"){if(!i){A(Cr=>({...Cr,scope:"Dashboard scope is not available"}));return}i(qn),Kr();return}if(Se==="domain"){if(!l){A(rn=>({...rn,scope:"Domain scope is not available"}));return}const Cr=((Mt=qn.calculatedFormula)==null?void 0:Mt.inputFields)||[],ki=new Map,No=Cr.map(rn=>{const Ot=fl(rn.label||rn.name),dr=ki.get(Ot)||0;return ki.set(Ot,dr+1),dr===0?Ot:`${Ot}_${dr+1}`}),dc=((vn=qn.expression)==null?void 0:vn.replace(/\{field_(\d+)\}/g,(rn,Ot)=>`{${No[Number(Ot)]||Ot}}`))||"",Jn=No.reduce((rn,Ot,dr)=>{const Ei=Cr[dr];return Ux(Ei)?rn[Ot]={dimension:Ei.name}:rn[Ot]={dataset:Ei.entityName,field:Ei.name},rn},{});try{await l({name:fl(y),label:y.trim(),description:W.trim(),expression:dc,inputs:Jn,dataType:_e,tags:R.split(",").map(rn=>rn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(rn){A(Ot=>({...Ot,scope:(rn==null?void 0:rn.message)||"Failed to save to domain"}));return}Kr();return}o(qn),Kr();return}const lt=nj();if(Se==="dashboard"){if(!i){A(qn=>({...qn,scope:"Dashboard scope is not available"}));return}i(lt),Kr();return}if(Se==="domain"){if(!a){A(Jn=>({...Jn,scope:"Domain scope is not available"}));return}if(!lt.calculatedFormula){A(Jn=>({...Jn,scope:"Calculated formula missing"}));return}const qn=lt.calculatedFormula.inputFields,Cr=new Map,ki=qn.map(Jn=>{const rn=fl(Jn.label||Jn.name),Ot=Cr.get(rn)||0;return Cr.set(rn,Ot+1),Ot===0?rn:`${rn}_${Ot+1}`}),No=((Qt=lt.expression)==null?void 0:Qt.replace(/\{field_(\d+)\}/g,(Jn,rn)=>`{${ki[Number(rn)]||rn}}`))||"",dc=ki.reduce((Jn,rn,Ot)=>{const dr=qn[Ot];return dr.role==="metric"?sc(dr)?Jn[rn]={metric:dr.name}:Jn[rn]={dataset:dr.entityName,field:dr.name,aggregate:dr.aggregate}:Jn[rn]={dataset:dr.entityName,field:dr.name},Jn},{});try{await a({name:fl(y),label:y.trim(),description:W.trim(),expression:No,inputs:dc,tags:R.split(",").map(Jn=>Jn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Jn){A(rn=>({...rn,scope:(Jn==null?void 0:Jn.message)||"Failed to save to domain"}));return}Kr();return}o(lt),Kr()},rj=async()=>{if(ke)return;if(A({}),b==="metric"){if(!await uc())return}else if(!await ej())return;const Se=be?$:s||"card";if(b==="metric"&&Se!=="domain"&&it&&!r){Q(Se),te(!0);return}de(!0);try{await Fy(Se)}finally{de(!1)}},sj=C.useMemo(()=>{if(!We||w==="custom")return"";if(w==="scale"){const Se=Number.isFinite(k)?k:1;return`${G2(S)} x ${Se}`}return`${G2(S)||"A"} ${We.symbol} ${G2(E)||"B"}`},[We,w,S,E,k]);return c.jsxs(c.Fragment,{children:[c.jsxs(Gr,{modal:!1,open:e,onOpenChange:Se=>{Se?t(!0):Kr()},children:[e&&c.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),c.jsxs(zr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:Se=>{Se.preventDefault()},children:[c.jsxs(Br,{children:[c.jsxs(Vr,{children:[r?"Edit":"Create"," Calculated Field"]}),c.jsx(is,{children:"Build calculated metrics and dimensions using expressions."})]}),c.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[c.jsx(rQe,{groups:Yt,searchTerm:Y,onSearchTermChange:q,onFieldClick:JS,selectedFieldIds:zt,disabled:ke}),c.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Field Type"}),c.jsx(nQe,{value:b,onChange:un,disabled:ke||!!r,options:h||["metric","dimension"]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"calculated-name",children:"Name"}),c.jsx(mn,{id:"calculated-name",value:y,onChange:Se=>v(Se.target.value),placeholder:"e.g., Profit Margin",className:F.name?"border-red-500":"",disabled:ke}),F.name&&c.jsx("p",{className:"text-xs text-red-500",children:F.name})]}),b==="metric"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Operation"}),c.jsx(sQe,{value:w,onChange:Dn,allowCustom:!0,disabled:ke}),F.operation&&c.jsx("p",{className:"text-xs text-red-500",children:F.operation})]}),w==="custom"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(C6,{ref:ge,value:T,onChange:Se=>{P(Se),Ce(!1)},onGenerate:()=>G(!0),showGenerate:!!yt&&!ke,disabled:ke}),c.jsx(S6,{onValidate:async()=>{Ce(!0),await Ke()},isValidating:kt,validationResult:Be,fallbackResult:et,error:pe,showFallback:ce,disabled:ke}),F.expression&&c.jsx("p",{className:"text-xs text-red-500",children:F.expression})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx(ae,{children:"Inputs"}),c.jsx(w6,{label:"A",input:S,availableFields:Ge,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:Se=>{const lt=K2(Se,(S==null?void 0:S.aggregate)||uh(Se));N(rh(Se,lt))},onAggregateChange:Se=>Oy("A",Se),onRemove:()=>N(null),onActivate:()=>B("A"),allowMedian:g,disabled:ke}),F.inputA&&c.jsx("p",{className:"text-xs text-red-500",children:F.inputA}),w!=="scale"&&c.jsxs(c.Fragment,{children:[c.jsx(w6,{label:"B",input:E,availableFields:Ge,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:Se=>{const lt=K2(Se,(E==null?void 0:E.aggregate)||uh(Se));_(rh(Se,lt))},onAggregateChange:Se=>Oy("B",Se),onRemove:()=>_(null),onActivate:()=>B("B"),allowMedian:g,disabled:ke}),F.inputB&&c.jsx("p",{className:"text-xs text-red-500",children:F.inputB})]}),w==="scale"&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"constantFactor",children:"Multiplication Factor"}),c.jsx(mn,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(k)?"":k,onChange:Se=>M(Se.target.value===""?Number.NaN:Number(Se.target.value)),className:F.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:ke}),F.constant&&c.jsx("p",{className:"text-xs text-red-500",children:F.constant})]}),c.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:sj||"Select inputs to preview formula"}),F.inputs&&c.jsxs(kI,{variant:"destructive",children:[c.jsx(Yl,{className:"h-4 w-4"}),c.jsx(EI,{children:F.inputs})]})]})]}),b==="dimension"&&c.jsxs("div",{className:"space-y-4",children:[c.jsx(C6,{ref:ge,value:T,onChange:Se=>{P(Se),Ce(!1)},onGenerate:()=>G(!0),showGenerate:!!yt&&!ke,disabled:ke}),c.jsx(S6,{onValidate:async()=>{Ce(!0),await Ke()},isValidating:kt,validationResult:Be,fallbackResult:et,error:pe,showFallback:ce,disabled:ke}),F.expression&&c.jsx("p",{className:"text-xs text-red-500",children:F.expression}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Output Type"}),c.jsxs(ot,{value:_e,onValueChange:Se=>I(Se),disabled:ke,children:[c.jsx(nt,{className:"h-9 w-full",children:c.jsx(at,{placeholder:"Select output type"})}),c.jsx(rt,{children:N6.map(Se=>c.jsx(ve,{value:Se.value,children:Se.label},Se.value))})]}),re&&!O&&c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",re]})]})]}),be&&(De||qe)&&c.jsxs("div",{className:"space-y-3",children:[c.jsx(cQe,{scope:$,onChange:V,showDashboardScope:De,showDomainScope:qe,error:F.scope,disabled:ke}),$==="domain"&&c.jsx(uQe,{description:W,tags:R,onDescriptionChange:L,onTagsChange:z,descriptionError:F.description,disabled:ke})]})]})]}),c.jsxs(os,{children:[c.jsx(se,{variant:"outline",onClick:Kr,children:"Cancel"}),c.jsxs(se,{onClick:rj,disabled:le||ke,children:[r?"Update":"Create"," ",b==="metric"?"Metric":"Dimension"]})]})]})]}),c.jsx(fQe,{open:U,onOpenChange:G,availableFields:Ge,fieldType:b,onExpressionGenerated:async Se=>{P(Se),Ce(!1),Re()},endpoint:yt,dialect:p==null?void 0:p.dialect}),c.jsx(Um,{open:K,onOpenChange:te,children:c.jsxs(Sf,{children:[c.jsxs(jf,{children:[c.jsx(kf,{children:"Name Conflict"}),c.jsxs(Ef,{children:['A domain metric named "',y.trim(),'" already exists. Your local version will override it in this'," ",Z==="dashboard"?"dashboard":"card",". Continue?"]})]}),c.jsxs(Nf,{children:[c.jsx(Tf,{onClick:()=>{Q(null)},children:"Choose Different Name"}),c.jsx(_f,{onClick:async()=>{if(Z){te(!1),de(!0);try{await Fy(Z)}finally{de(!1),Q(null)}}},children:"Continue"})]})]})})]})}function gte({domainId:e}){const{authToken:t,tokenProps:n}=Xe(),[r,s]=C.useState(!1),[o,i]=C.useState(null),a=C.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-metrics`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),l=C.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-dimensions`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),u=C.useCallback(async f=>{if(!a){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await eo(a,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=C.useCallback(async f=>{if(!l){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await eo(l,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[l,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,isPromoting:r,error:o}}const bte=C.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ke,kt,pe,Re;const[s,o]=C.useState(""),[i,a]=C.useState("all"),[l,u]=C.useState(!1),[d,f]=C.useState(null),[h,m]=C.useState("card"),[p,g]=C.useState("metric");Ae(re=>re.isDevMode);const b=Ae(re=>re.card.dataSource),x=Ae(re=>re.card.config),y=Ae(re=>re.card),v=Ae(re=>re.frame),w=Ae(re=>re.actions.updateCardConfig),j=Ae(re=>re.actions.updateFrame),{userContext:S}=Ps(),{autoJoinMetadata:N}=Ha(y),{columns:E,rawColumnGroups:_,scopedFields:k,dashboardCalculatedFields:M,cardCalculatedFields:T,isLoading:P,error:O,refetch:I}=PA(),$=(b==null?void 0:b.mode)==="semanticDomain"?b.semanticDomainId:void 0,{data:V}=OA($),{promoteMetric:W,promoteDimension:L}=gte({domainId:$}),R=C.useMemo(()=>[...(x==null?void 0:x.groupByColumns)||[],...(x==null?void 0:x.metricColumns)||[],...(x==null?void 0:x.detailColumns)||[]],[x==null?void 0:x.groupByColumns,x==null?void 0:x.metricColumns,x==null?void 0:x.detailColumns]);(kt=(Ke=x==null?void 0:x.joinPlan)==null?void 0:Ke.baseEntity)==null||kt.name,(Re=(pe=N==null?void 0:N.resolvedJoinPlan)==null?void 0:pe.baseEntity)==null||Re.name,Qee();const z=t==="editor",F=(S==null?void 0:S.type)==="organization",A=z?k:E,H=_,B=s.toLowerCase(),Y=(x==null?void 0:x.metricColumns)||[],q=(x==null?void 0:x.groupByColumns)||[],U=C.useCallback(async re=>{await W(re),I()},[W,I]),G=C.useCallback(async re=>{await L(re),I()},[L,I]),Z=re=>re.name.toLowerCase().includes(B)||re.dataType.toLowerCase().includes(B)||re.label&&re.label.toLowerCase().includes(B)||re.qualifiedEntityName&&re.qualifiedEntityName.toLowerCase().includes(B),Q=A.filter(Z),K=re=>{if(re.role==="metric"&&sc(re)||re.role==="groupby"&&re.expression)return"calculated";if(re.dataType==="number"||re.dataType==="integer"||re.dataType==="float"||re.dataType==="decimal"||re.dataType==="currency")return"metrics";const _e=yr(re.dataType);return["date","string","boolean"].includes(_e)?"dimensions":_e==="number"?"metrics":"dimensions"},te=re=>{const _e=re.filter(Z);return i==="all"?_e:_e.filter(We=>K(We)===i)},le=i==="all"?Q:Q.filter(re=>K(re)===i),de=z?[...M,...T]:[],ce=z?te(de):[],ge=te(E).reduce((re,_e)=>{const We=_e.qualifiedEntityName||"Other Fields";return re[We]||(re[We]={label:cb(_e.entityName),fields:[]}),re[We].fields.push(_e),re},{}),he=re=>re.id||`${re.entityName}-${re.qualifiedEntityName}-${re.name}-${re.role||"field"}`,me=C.useMemo(()=>{const re=new Map;return(z?k:E).forEach(We=>{re.set(he(We),ED(We,{joinabilityMap:(V==null?void 0:V.joinabilityMap)||null,selectedFields:R,cardConfig:x,autoJoinMetadata:N}))}),re},[z,k,E,V==null?void 0:V.joinabilityMap,R,x,N]),oe=z?[{key:"scope-calculated",label:"Calculated Fields",fields:ce}].filter(re=>re.fields.length>0):[],fe=[...oe.map(re=>re.key),...Object.keys(ge)],Me=Q.filter(re=>K(re)==="dimensions").length,ke=Q.filter(re=>K(re)==="metrics").length,ie=Q.filter(re=>K(re)==="calculated").length,xe=Q.length>0&&t!=="inline-filter",Oe=t==="inline-filter"?"w-full":"w-[290px]";if(P)return c.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",Oe),children:c.jsx(fu,{size:"md",color:"muted","aria-label":"Loading data"})});if(O)return c.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",Oe),children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:O.message||"Failed to load column data"})]});if(!b||!b.selectedEntities||b.selectedEntities.length===0)return c.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",Oe),children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-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 be=t==="inline-filter"?"px-3 pb-3":"px-6 pb-6",De=t==="inline-filter"?"overflow-hidden":"",qe=re=>re!=null&&re.startsWith("card-source-")?re.replace("card-source-",""):re,He=(re,_e,We)=>{const it=qe(re.id),zt=qe(_e.id);return it&&zt&&it===zt?!0:!it||!zt||We!=null&&We.allowNameFallback?re.name===_e.name&&re.role===_e.role:!1},Fe=(re,_e,We)=>re.findIndex(it=>He(it,_e,We)),yt=re=>{if(!v)return re;const _e=v.calculatedFields||[],We=Fe(_e,re),it=We>=0&&_e[We].id!==re.id?{...re,id:_e[We].id}:re,zt=We>=0?_e.map((un,Dn)=>Dn===We?it:un):[..._e,it];return j({calculatedFields:zt}),it},je=(re,_e,We,it)=>{var un;const zt=Fe(re,We||_e,it);if(zt>=0){const Dn=(un=re[zt])==null?void 0:un.id,Kr=Dn&&Dn!==_e.id?{..._e,id:Dn}:_e;return re.map((Hr,zs)=>zs===zt?Kr:Hr)}return[...re,_e]},dt=re=>{if(re.role==="metric")return Y.find(_e=>He(_e,re));if(re.role==="groupby")return q.find(_e=>He(_e,re))},Ct=re=>{var _e;return(_e=v==null?void 0:v.calculatedFields)==null?void 0:_e.find(We=>He(We,re))},Ye=re=>{if(re.role==="metric"){w(y.id,{metricColumns:Y.filter(_e=>!He(_e,re,{allowNameFallback:re.fieldScope==="dashboard"}))});return}re.role==="groupby"&&w(y.id,{groupByColumns:q.filter(_e=>!He(_e,re,{allowNameFallback:re.fieldScope==="dashboard"}))})},Yt=re=>{if(!v)return;const _e=(v.calculatedFields||[]).filter(We=>!He(We,re));j({calculatedFields:_e})},Ge=re=>{if(!F)return;if(re.fieldScope==="domain"){f(re),m("domain"),g(re.role==="metric"?"metric":"dimension"),u(!0);return}if(re.fieldScope==="dashboard"){const We=Ct(re);if(!We)return;f(We),m("dashboard"),g(We.role==="metric"?"metric":"dimension"),u(!0);return}const _e=dt(re);_e&&(f(_e),m("card"),g(_e.role==="metric"?"metric":"dimension"),u(!0))},et=re=>{if(F&&re.fieldScope!=="domain"){if(re.fieldScope==="dashboard"){Yt(re),Ye(re);return}Ye(re)}},Be=re=>{if(!F)return null;const _e=re.fieldScope==="domain";return c.jsxs(wf,{children:[c.jsx(Cf,{asChild:!0,children:c.jsx(se,{variant:"ghost",size:"icon",className:"h-6 w-6","aria-label":"Calculated field actions",children:c.jsx(f8,{className:"h-4 w-4"})})}),c.jsxs(yu,{align:"end",className:"w-40",children:[c.jsx(po,{onClick:()=>Ge(re),children:"Edit"}),c.jsx(po,{disabled:_e,onClick:()=>et(re),children:"Delete"})]})]})};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",be,De),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[A.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(Ko,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(jn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:re=>o(re.target.value)}),s&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:c.jsx(St,{className:"size-3.5"})})]}),xe&&c.jsx(Os,{defaultValue:"all",value:i,onValueChange:re=>a(re),className:"mb-4",children:c.jsxs(ys,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(nn,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:Q.length})]}),c.jsxs(nn,{value:"dimensions",className:"text-xs",children:[c.jsx(U1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:Me})]}),c.jsxs(nn,{value:"metrics",className:"text-xs",children:[c.jsx(Am,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:ke})]}),c.jsxs(nn,{value:"calculated",className:"text-xs",children:[c.jsx(OT,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:ie})]})]})}),t==="editor"&&i==="calculated"&&F&&c.jsx("div",{className:"flex items-center justify-end gap-2",children:c.jsxs(se,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[c.jsx(Tr,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),c.jsxs(tl,{className:"min-h-0 flex-1",children:[c.jsxs(BA,{type:"multiple",defaultValue:fe,className:"space-y-2",children:[oe.map(re=>c.jsxs(rx,{value:re.key,className:"border-none",children:[c.jsx(sx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:re.label}),c.jsx(Ve,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:re.fields.length})]})}),c.jsx(ox,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:re.fields.map(_e=>{const We=me.get(he(_e)),it=t==="editor"&&i==="calculated";return c.jsx(y6,{field:_e,context:t,fieldState:We,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:it?Be(_e):void 0},_e.id)})})})]},re.key)),Object.entries(ge).map(([re,_e])=>{const We=H.find(zt=>zt.entityName===re)||{entityName:re,label:_e.label},it=re===Qh?"Domain Calculated Fields":We.label||We.entityName;return c.jsxs(rx,{value:re,className:"border-none",children:[c.jsx(sx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:it,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:it}),c.jsx(Ve,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:_e.fields.length})]})}),c.jsx(ox,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:_e.fields.map(zt=>{const un=me.get(he(zt));return c.jsx(y6,{field:zt,context:t,fieldState:un,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0},zt.id)})})})]},re)})]}),A.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.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"})]}),A.length>0&&le.length===0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(bi,{orientation:"horizontal"}),c.jsx(bi,{orientation:"vertical"})]})]}),c.jsx(pte,{open:l,onOpenChange:re=>{u(re),re||(f(null),m("card"))},availableFields:k,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:re=>{if(re.role==="metric"){if(d&&h==="card"){w(y.id,{metricColumns:je(Y,re,d)});return}w(y.id,{metricColumns:je(Y,re)});return}if(d&&h==="card"){w(y.id,{groupByColumns:je(q,re,d)});return}w(y.id,{groupByColumns:je(q,re)})},onSaveToDashboard:re=>{const _e=!!(d&&h==="dashboard"),We=_e?d:void 0;if(re.role==="metric"){const zt=yt(re);w(y.id,{metricColumns:je(Y,zt,We,{allowNameFallback:_e})});return}const it=yt(re);w(y.id,{groupByColumns:je(q,it,We,{allowNameFallback:_e})})},cardId:y.id,onPromoteMetricToDomain:$?U:void 0,onPromoteDimensionToDomain:$?G:void 0,domainId:$})]})}),xte=C.memo(function({context:t="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(bte,{context:t})," "]})});function yte(){const e=Ae(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=cr();C.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=FA(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function MQe(){yte();const e=J(l=>l.selectedSheetId),t=J(l=>l.selectedFrameId),n=J(l=>l.dashboard),r=J(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Wt(),{setCard:o}=cr(),i=Ae(l=>l.card.dataSource);return C.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function DQe(){const e=J(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Wt(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return c.jsxs(ms,{children:[c.jsx(ps,{asChild:!0,children:c.jsx(se,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:c.jsx(Ll,{className:"h-4 w-4"})})}),c.jsx(gs,{className:"w-[280px]",align:"end",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),c.jsxs(Qs,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(bn,{value:"canvas",id:"canvas",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(ae,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(bn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(ae,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[c.jsx(cn,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),c.jsx(ae,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),c.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[c.jsx(cn,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),c.jsx(ae,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),c.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function IQe(){const e=J(n=>n.actions.setShowFilters),{hasEntities:t}=MQe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ae,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(DQe,{}),c.jsx(se,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(eX,{})})]})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(Ny,{collisionDetection:Cy,children:c.jsx(ky,{items:[],strategy:WR,children:c.jsx(xte,{context:"filter"})})})})]})}function RQe(){const e=J(r=>r.dashboard.filters),t=J(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:X("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=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx($R,{filter:r}),c.jsx(Sp,{filter:r})]},r.id))}):null}function AQe(){const e=J(r=>r.showFilters),t=J(r=>r.isVisualEditing),n=J(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:X("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(RQe,{}),c.jsx(Wee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(IQe,{})})]})}const PQe=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-DJZwTob9.js"))),OQe=C.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-ZMOTcM3N.js"))),FQe=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-2sYazVkw.js"))),$Qe=C.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-L-xXWN55.js")).then(e=>({default:e.ResourceManagementPanel})));function LQe({showControls:e=!1,showFooter:t=!0,...n}){const r=J(l=>l.isDashboardPanelOpen),s=J(l=>l.isVisualEditing),o=J(l=>l.showDashboardJSON),i=J(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(rl,{FallbackComponent:gS,children:c.jsxs(PT,{dashboardProps:n,children:[c.jsx(tde,{}),c.jsx(AA,{componentType:"surfboard",componentId:n.id}),c.jsx(RA,{children:c.jsxs(qee,{preferences:a,children:[o&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(FQe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(PQe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(C.Suspense,{fallback:null,children:c.jsx($Qe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(JD,{...n,type:"dashboard",children:[s&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(OQe,{})}),c.jsx(AQe,{})]})})]})]})]})})]})})}var zQe=Object.defineProperty,BQe=(e,t,n)=>t in e?zQe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,fv=(e,t,n)=>BQe(e,typeof t!="symbol"?t+"":t,n);const VQe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},HQe={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}},UQe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function WQe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function vte(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const qQe={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=vte(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},YQe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},GQe={stringify:e=>e,parse:e=>e},X2={string:GQe,number:YQe,boolean:VQe,function:HQe,method:qQe,json:UQe},ng=Symbol.for("r2wc.render"),hv=Symbol.for("r2wc.connected"),Ku=Symbol.for("r2wc.context"),To=Symbol.for("r2wc.props");function KQe(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),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=WQe(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),fv(this,o,!0),fv(this,s),fv(this,r,{}),fv(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[To].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?X2[x]:null;if(x==="method"){const v=vte(g);Object.defineProperty(this[To].container,v,{enumerable:!0,configurable:!0,get(){return this[To][v]},set(w){this[To][v]=w,this[ng]()}}),this[To][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[To][p]=y.parse(b,g,this))}for(const p of a)this[To][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[hv]=!0,this[ng]()}disconnectedCallback(){this[hv]=!1,this[Ku]&&n.unmount(this[Ku]),delete this[Ku]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?X2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[To][x]=v.parse(b,p,this),this[ng]())}[(o=hv,s=Ku,r=To,ng)](){this[hv]&&(this[Ku]?n.update(this[Ku],this[To]):this[Ku]=n.mount(this.container,e,this[To]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[To][m]},set(b){this[To][m]=b;const x=g?X2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[ng]()}})}return h}function ZQe(e,t,n){const r=vne.createRoot(e),s=C.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function XQe({root:e,ReactComponent:t},n){const r=C.createElement(t,n);e.render(r)}function QQe({root:e}){e.unmount()}function JQe(e,t={}){return KQe(e,t,{mount:ZQe,update:XQe,unmount:QQe})}const eJe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},tJe=JQe(Yee,{props:eJe});function k6(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function nJe(e){if(Array.isArray(e))return e}function rJe(e,t,n){return(t=uJe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function sJe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],l=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);l=!0);}catch(d){u=!0,s=d}finally{try{if(!l&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function oJe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1077
|
+
`)}})}});var AZe=EKe(()=>wee(vi([ir({type:Lt("text-start"),id:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("text-delta"),id:ft(),delta:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("text-end"),id:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("error"),errorText:ft()}),ir({type:Lt("tool-input-start"),toolCallId:ft(),toolName:ft(),providerExecuted:co().optional(),dynamic:co().optional()}),ir({type:Lt("tool-input-delta"),toolCallId:ft(),inputTextDelta:ft()}),ir({type:Lt("tool-input-available"),toolCallId:ft(),toolName:ft(),input:ya(),providerExecuted:co().optional(),providerMetadata:Sr.optional(),dynamic:co().optional()}),ir({type:Lt("tool-input-error"),toolCallId:ft(),toolName:ft(),input:ya(),providerExecuted:co().optional(),providerMetadata:Sr.optional(),dynamic:co().optional(),errorText:ft()}),ir({type:Lt("tool-output-available"),toolCallId:ft(),output:ya(),providerExecuted:co().optional(),dynamic:co().optional(),preliminary:co().optional()}),ir({type:Lt("tool-output-error"),toolCallId:ft(),errorText:ft(),providerExecuted:co().optional(),dynamic:co().optional()}),ir({type:Lt("reasoning-start"),id:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("reasoning-delta"),id:ft(),delta:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("reasoning-end"),id:ft(),providerMetadata:Sr.optional()}),ir({type:Lt("source-url"),sourceId:ft(),url:ft(),title:ft().optional(),providerMetadata:Sr.optional()}),ir({type:Lt("source-document"),sourceId:ft(),mediaType:ft(),title:ft(),filename:ft().optional(),providerMetadata:Sr.optional()}),ir({type:Lt("file"),url:ft(),mediaType:ft(),providerMetadata:Sr.optional()}),ir({type:gee(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:ft().optional(),data:ya(),transient:co().optional()}),ir({type:Lt("start-step")}),ir({type:Lt("finish-step")}),ir({type:Lt("start"),messageId:ft().optional(),messageMetadata:ya().optional()}),ir({type:Lt("finish"),finishReason:hee(["stop","length","content-filter","tool-calls","error","other","unknown"]).optional(),messageMetadata:ya().optional()}),ir({type:Lt("abort")}),ir({type:Lt("message-metadata"),messageMetadata:ya()})])));function PZe(e){return e.type.startsWith("data-")}function Tee(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]=Tee(o,s):n[r]=s}return n}function OZe(e){const t=["ROOT"];let n=-1,r=null;function s(l,u,d){switch(l){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(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{n=u,t.pop();break}}}function i(l,u){switch(l){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{n=u,t.pop();break}}}for(let l=0;l<e.length;l++){const u=e[l];switch(t[t.length-1]){case"ROOT":s(u,l,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY");break}case"}":{n=l,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,l,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{o(u,l);break}case"INSIDE_STRING":{switch(u){case'"':{t.pop(),n=l;break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:n=l}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{n=l,t.pop();break}default:{n=l,s(u,l,"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=l,t.pop();break}default:{n=l;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{s(u,l,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),n=l;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=l;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"}":{t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&o(u,l);break}case"]":{t.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l);break}default:{t.pop();break}}break}case"INSIDE_LITERAL":{const f=e.substring(r,l+1);!"false".startsWith(f)&&!"true".startsWith(f)&&!"null".startsWith(f)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?o(u,l):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&i(u,l)):n=l;break}}}let a=e.slice(0,n+1);for(let l=t.length-1;l>=0;l--)switch(t[l]){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 Mee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await j1({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await j1({text:OZe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function $v(e){return e.type.startsWith("tool-")}function FZe(e){return e.type==="dynamic-tool"}function J_(e){return $v(e)||FZe(e)}function h6(e){return e.type.split("-").slice(1).join("-")}function $Ze({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 LZe({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:s,onToolCall:o,onData:i}){return e.pipeThrough(new TransformStream({async transform(a,l){await r(async({state:u,write:d})=>{var f,h,m,p;function g(w){const S=u.message.parts.filter($v).find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function b(w){const S=u.message.parts.filter(N=>N.type==="dynamic-tool").find(N=>N.toolCallId===w);if(S==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return S}function x(w){var j;const S=u.message.parts.find(_=>$v(_)&&_.toolCallId===w.toolCallId),N=w,E=S;S!=null?(S.state=w.state,E.input=N.input,E.output=N.output,E.errorText=N.errorText,E.rawInput=N.rawInput,E.preliminary=N.preliminary,E.providerExecuted=(j=N.providerExecuted)!=null?j:S.providerExecuted,N.providerMetadata!=null&&S.state==="input-available"&&(S.callProviderMetadata=N.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:N.input,output:N.output,rawInput:N.rawInput,errorText:N.errorText,providerExecuted:N.providerExecuted,preliminary:N.preliminary,...N.providerMetadata!=null?{callProviderMetadata:N.providerMetadata}:{}})}function y(w){var j,S;const N=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),E=w,_=N;N!=null?(N.state=w.state,_.toolName=w.toolName,_.input=E.input,_.output=E.output,_.errorText=E.errorText,_.rawInput=(j=E.rawInput)!=null?j:_.rawInput,_.preliminary=E.preliminary,_.providerExecuted=(S=E.providerExecuted)!=null?S:N.providerExecuted,E.providerMetadata!=null&&N.state==="input-available"&&(N.callProviderMetadata=E.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:E.input,output:E.output,errorText:E.errorText,preliminary:E.preliminary,providerExecuted:E.providerExecuted,...E.providerMetadata!=null?{callProviderMetadata:E.providerMetadata}:{}})}async function v(w){if(w!=null){const j=u.message.metadata!=null?Tee(u.message.metadata,w):w;t!=null&&await l6({value:j,schema:t}),u.message.metadata=j}}switch(a.type){case"text-start":{const w={type:"text",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeTextParts[a.id]=w,u.message.parts.push(w),d();break}case"text-delta":{const w=u.activeTextParts[a.id];w.text+=a.delta,w.providerMetadata=(f=a.providerMetadata)!=null?f:w.providerMetadata,d();break}case"text-end":{const w=u.activeTextParts[a.id];w.state="done",w.providerMetadata=(h=a.providerMetadata)!=null?h:w.providerMetadata,delete u.activeTextParts[a.id],d();break}case"reasoning-start":{const w={type:"reasoning",text:"",providerMetadata:a.providerMetadata,state:"streaming"};u.activeReasoningParts[a.id]=w,u.message.parts.push(w),d();break}case"reasoning-delta":{const w=u.activeReasoningParts[a.id];w.text+=a.delta,w.providerMetadata=(m=a.providerMetadata)!=null?m:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(p=a.providerMetadata)!=null?p:w.providerMetadata,w.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 w=u.message.parts.filter($v);u.partialToolCalls[a.toolCallId]={text:"",toolName:a.toolName,index:w.length,dynamic:a.dynamic},a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}):x({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-streaming",input:void 0,providerExecuted:a.providerExecuted}),d();break}case"tool-input-delta":{const w=u.partialToolCalls[a.toolCallId];w.text+=a.inputTextDelta;const{value:j}=await Mee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:j}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:j}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({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?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"output-error",input:a.input,errorText:a.errorText,providerExecuted:a.providerExecuted,providerMetadata:a.providerMetadata}):x({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 w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-available",input:w.input,output:a.output,preliminary:a.preliminary})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:h6(w),state:"output-available",input:w.input,output:a.output,providerExecuted:a.providerExecuted,preliminary:a.preliminary})}d();break}case"tool-output-error":{if(a.dynamic){const w=b(a.toolCallId);y({toolCallId:a.toolCallId,toolName:w.toolName,state:"output-error",input:w.input,errorText:a.errorText,providerExecuted:a.providerExecuted})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:h6(w),state:"output-error",input:w.input,rawInput:w.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 v(a.messageMetadata),(a.messageId!=null||a.messageMetadata!=null)&&d();break}case"finish":{a.finishReason!=null&&(u.finishReason=a.finishReason),await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"message-metadata":{await v(a.messageMetadata),a.messageMetadata!=null&&d();break}case"error":{s==null||s(new Error(a.errorText));break}default:if(PZe(a)){(n==null?void 0:n[a.type])!=null&&await l6({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const j=w.id!=null?u.message.parts.find(S=>w.type===S.type&&w.id===S.id):void 0;j!=null?j.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function zZe({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()}}Ay({prefix:"aitxt",size:24});Ay({prefix:"aiobj",size:24});var BZe=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()})}};Ay({prefix:"aiobj",size:24});var VZe={};jZe(VZe,{object:()=>UZe,text:()=>HZe});var HZe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),UZe=({schema:e})=>{const t=CZe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await Mee(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 j1({text:n});if(!s.success)throw new d6({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 d6({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 WZe(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=l=>{var u;o((u=l.target)==null?void 0:u.result)},a.onerror=l=>i(l),a.readAsDataURL(t)});return{type:"file",mediaType:r,filename:n,url:s}}))}var qZe=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 nh(this.body),l=await nh(this.headers),u=await nh(this.credentials),d={...ed(l),...ed(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,m=(f==null?void 0:f.headers)!==void 0?ed(f.headers):d,p=(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},g=(s=f==null?void 0:f.credentials)!=null?s:u,x=await((o=this.fetch)!=null?o:globalThis.fetch)(h,{method:"POST",headers:i6({"Content-Type":"application/json",...m},`ai-sdk/${f6}`,o6()),body:JSON.stringify(p),credentials:g,signal:e});if(!x.ok)throw new Error((i=await x.text())!=null?i:"Failed to fetch the chat response.");if(!x.body)throw new Error("The response body is empty.");return this.processResponseStream(x.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await nh(this.body),a=await nh(this.headers),l=await nh(this.credentials),u={...ed(a),...ed(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:l,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?ed(d.headers):u,m=(r=d==null?void 0:d.credentials)!=null?r:l,g=await((s=this.fetch)!=null?s:globalThis.fetch)(f,{method:"GET",headers:i6(h,`ai-sdk/${f6}`,o6()),credentials:m});if(g.status===204)return null;if(!g.ok)throw new Error((o=await g.text())!=null?o:"Failed to fetch the chat response.");if(!g.body)throw new Error("The response body is empty.");return this.processResponseStream(g.body)}},MA=class extends qZe{constructor(e={}){super(e)}processResponseStream(e){return MKe({stream:e,schema:AZe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},YZe=class{constructor({generateId:e=vKe,id:t=e(),transport:n=new MA,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new BZe,this.sendMessage=async(f,h)=>{var m,p,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(m=this.lastMessage)==null?void 0:m.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await WZe(f.files),..."text"in f&&f.text!=null?[{type:"text",text:f.text}]:[]]}:x=f,f.messageId!=null){const y=this.state.messages.findIndex(v=>v.id===f.messageId);if(y===-1)throw new Error(`message with id ${f.messageId} not found`);if(this.state.messages[y].role!=="user")throw new Error(`message with id ${f.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,y+1),this.state.replaceMessage(y,{...x,id:f.messageId,role:(p=x.role)!=null?p:"user",metadata:f.metadata})}else this.state.pushMessage({...x,id:(g=x.id)!=null?g:this.generateId(),role:(b=x.role)!=null?b:"user",metadata:f.metadata});await this.makeRequest({trigger:"submit-message",messageId:f.messageId,...h})},this.regenerate=async({messageId:f,...h}={})=>{const m=f==null?this.state.messages.length-1:this.state.messages.findIndex(p=>p.id===f);if(m===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[m].role==="assistant"?m:m+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:m,output:p,errorText:g})=>this.jobExecutor.run(async()=>{var b,x;const y=this.state.messages,v=y[y.length-1];this.state.replaceMessage(y.length-1,{...v,parts:v.parts.map(w=>J_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>J_(w)&&w.toolCallId===m?{...w,state:f,output:p,errorText:g}:w)),this.status!=="streaming"&&this.status!=="submitted"&&((b=this.sendAutomaticallyWhen)!=null&&b.call(this,{messages:this.state.messages}))&&this.makeRequest({trigger:"submit-message",messageId:(x=this.lastMessage)==null?void 0:x.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=l,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,l;this.setStatus({status:"submitted",error:void 0});const u=this.lastMessage;let d=!1,f=!1,h=!1;try{const m={state:$Ze({lastMessage:this.state.snapshot(u),messageId:this.generateId()}),abortController:new AbortController};m.abortController.signal.addEventListener("abort",()=>{d=!0}),this.activeResponse=m;let p;if(e==="resume-stream"){const b=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(b==null){this.setStatus({status:"ready"});return}p=b}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:m.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const g=b=>this.jobExecutor.run(()=>b({state:m.state,write:()=>{var x;this.setStatus({status:"streaming"}),m.state.message.id===((x=this.lastMessage)==null?void 0:x.id)?this.state.replaceMessage(this.state.messages.length-1,m.state.message):this.state.pushMessage(m.state.message)}}));await zZe({stream:LZe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:g,onError:b=>{throw b}}),onError:b=>{throw b}}),this.setStatus({status:"ready"})}catch(m){if(d||m.name==="AbortError")return d=!0,this.setStatus({status:"ready"}),null;h=!0,m instanceof TypeError&&(m.message.toLowerCase().includes("fetch")||m.message.toLowerCase().includes("network"))&&(f=!0),this.onError&&m instanceof Error&&this.onError(m),this.setStatus({status:"error",error:m})}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(m){console.error(m)}this.activeResponse=void 0}(a=this.sendAutomaticallyWhen)!=null&&a.call(this,{messages:this.state.messages})&&!h&&await this.makeRequest({trigger:"submit-message",messageId:(l=this.lastMessage)==null?void 0:l.id,metadata:t,headers:n,body:r})}};function GZe({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(J_).filter(s=>!s.providerExecuted);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function KZe(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,l=t-a;l<=0?(r=i,e.apply(this,o)):n=setTimeout(()=>{r=Date.now(),e.apply(this,o)},l)}}var ZZe=KZe;const XZe=hf(ZZe);var Dee=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Gn=(e,t,n)=>(Dee(e,t,"read from private field"),n?n.call(e):t.get(e)),ma=(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)},vc=(e,t,n,r)=>(Dee(e,t,"write to private field"),t.set(e,n),n);function QZe(e,t){return t!=null?XZe(e,t):e}var Qo,Lv,zv,kg,Eg,_g,lh,eT,tT,JZe=class{constructor(e=[]){ma(this,Qo,void 0),ma(this,Lv,"ready"),ma(this,zv,void 0),ma(this,kg,new Set),ma(this,Eg,new Set),ma(this,_g,new Set),this.pushMessage=t=>{vc(this,Qo,Gn(this,Qo).concat(t)),Gn(this,lh).call(this)},this.popMessage=()=>{vc(this,Qo,Gn(this,Qo).slice(0,-1)),Gn(this,lh).call(this)},this.replaceMessage=(t,n)=>{vc(this,Qo,[...Gn(this,Qo).slice(0,t),this.snapshot(n),...Gn(this,Qo).slice(t+1)]),Gn(this,lh).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?QZe(t,n):t;return Gn(this,kg).add(r),()=>{Gn(this,kg).delete(r)}},this["~registerStatusCallback"]=t=>(Gn(this,Eg).add(t),()=>{Gn(this,Eg).delete(t)}),this["~registerErrorCallback"]=t=>(Gn(this,_g).add(t),()=>{Gn(this,_g).delete(t)}),ma(this,lh,()=>{Gn(this,kg).forEach(t=>t())}),ma(this,eT,()=>{Gn(this,Eg).forEach(t=>t())}),ma(this,tT,()=>{Gn(this,_g).forEach(t=>t())}),vc(this,Qo,e)}get status(){return Gn(this,Lv)}set status(e){vc(this,Lv,e),Gn(this,eT).call(this)}get error(){return Gn(this,zv)}set error(e){vc(this,zv,e),Gn(this,tT).call(this)}get messages(){return Gn(this,Qo)}set messages(e){vc(this,Qo,[...e]),Gn(this,lh).call(this)}};Qo=new WeakMap;Lv=new WeakMap;zv=new WeakMap;kg=new WeakMap;Eg=new WeakMap;_g=new WeakMap;lh=new WeakMap;eT=new WeakMap;tT=new WeakMap;var ch,m6=class extends YZe{constructor({messages:e,...t}){const n=new JZe(e);super({...t,state:n}),ma(this,ch,void 0),this["~registerMessagesCallback"]=(r,s)=>Gn(this,ch)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Gn(this,ch)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Gn(this,ch)["~registerErrorCallback"](r),vc(this,ch,n)}};ch=new WeakMap;function Iee({experimental_throttle:e,resume:t=!1,...n}={}){const r=C.useRef("chat"in n?n.chat:new m6(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new m6(n));const o="id"in n?n.id:null,i=C.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=C.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=C.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=C.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=C.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return C.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:l,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput}}function eXe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function tXe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function nXe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function rXe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function Ree(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:rXe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function Aee(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 sXe(){var b;const{authToken:e,tokenProps:t}=Xe(),n=J(x=>x.dashboard.aiScopeTables),r=(b=L1().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=Iee({transport:new MA({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=la.getState();return{assistantId:"dashboard-assistant",assistantProfileId:r,aiContext:x.currentAIContext,reasoningEffort:x.reasoningEffort,showReasoning:x.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:x,body:y})=>({body:{...y,messages:Dq(x)}})}),onToolCall:m,sendAutomaticallyWhen:GZe,onFinish({isAbort:x,isDisconnect:y,isError:v}){console.log(x?"[Dashboard Assistant] Stream aborted by user":y?"[Dashboard Assistant] Stream disconnected (network error)":v?"[Dashboard Assistant] Stream error occurred":"[Dashboard Assistant] Stream completed successfully")},onError(x){var y;if(x.name==="AbortError"||(y=x.message)!=null&&y.includes("aborted")){console.log("[Dashboard Assistant] Stream aborted (expected)");return}console.error("[Dashboard Assistant] Stream error:",x)}});async function m({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:Ree(n||[])}}),x.toolName==="getDashboardContext"){const y=J.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const p=!["ready","error"].includes(l),g=Aee(d);return{sendMessage:s,regenerate:a,isLoading:p,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function Pee(){var u;const{authToken:e,tokenProps:t}=Xe(),n=(u=L1().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=En({queryKey:["assistant-profile",n],queryFn:()=>rr(`${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 Oee({seedQuestions:e,handleSeedQuestionClick:t}){return e.length===0?null:c.jsxs("div",{className:"overflow-x-auto rounded-md border bg-muted/40 p-4",children:[c.jsxs("div",{className:"mb-3 flex items-center",children:[c.jsx(c8,{className:"mr-2 h-4 w-4 text-muted-foreground"}),c.jsx("h3",{className:"font-medium",children:"Example Questions"})]}),c.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((n,r)=>c.jsx(se,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function N1(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(eM,{className:r});case"view":return c.jsx(tu,{className:r});case"materialized view":return c.jsx(Woe,{className:r});case"model":return c.jsx(U1,{className:r});case"file":return c.jsx(Ji,{className:r});case"dataset":return c.jsx($l,{className:r});case"upload":return c.jsx(sM,{className:r});case"url":return c.jsx(p8,{className:r});default:return c.jsx(Sx,{className:r})}}const Fee=D.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Ko,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx($s.Input,{ref:n,className:X("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})]}));Fee.displayName=$s.Input.displayName;const uv=e=>e.label||(e==null?void 0:e.name),p6=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function oXe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Xe(),f=(d==null?void 0:d.type)==="dashboard",[h,m]=C.useState(""),[p,g]=C.useState(""),b=s.filter(S=>{if(!h)return!0;const N=uv(S).toLowerCase(),E=p6(S).toLowerCase(),_=h.toLowerCase();return N.includes(_)||E.includes(_)});C.useEffect(()=>{e||(m(""),g(""))},[e]),C.useEffect(()=>{b.length>0&&!p&&g(uv(b[0]))},[b,p]);const x=()=>{if(!p)return;const S=b.find(N=>uv(N)===p);S&&(o.some(E=>"id"in S&&"id"in E?S.id===E.id:S.name===E.name&&S.connectionId===E.connectionId)||t(S),i(S),r())},y=S=>{(S.key==="Tab"||S.key==="Enter")&&(S.preventDefault(),x())};if(!e)return null;const v=S=>o.some(N=>"id"in S&&"id"in N?S.id===N.id:S.name===N.name&&S.connectionId===N.connectionId),w=o.length===s.length,j=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(op,{shouldFilter:!1,value:p,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(Fee,{placeholder:"Search entities...",value:h,onValueChange:m,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(Tr,{className:"mr-1 h-4 w-4"}),"Add"]})]}),s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-sm",children:[c.jsxs("div",{className:"text-muted-foreground",children:[o.length," ",o.length===1?"entity":"entities"," selected"]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),a==null||a()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),j&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),l==null||l()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(St,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(ip,{className:"min-h-60",children:[c.jsx(ap,{children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-4",children:[c.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"No entities found."}),!f&&c.jsxs(se,{onClick:S=>{S.preventDefault(),S.stopPropagation(),u==null||u()},onMouseDown:S=>{S.preventDefault(),S.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(Tr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(lp,{children:b.map((S,N)=>{const E=v(S),_="id"in S?S.id:`${S.connectionId}-${S.name}`,k=uv(S);return c.jsxs(cp,{value:k,onSelect:()=>{E?n==null||n(S):t(S)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:X("flex cursor-pointer items-start gap-2 p-2 hover:bg-gray-100"),children:[c.jsx("div",{className:"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center",children:N1(S.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:k}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:p6(S)})]}),E&&c.jsx("div",{className:"ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-foreground/80",children:c.jsx(Ar,{className:"h-3 w-3 text-background"})})]},_)})})]})]})})}const nT=e=>e.name||e.name,iXe=e=>{const t=nT(e),n="description"in e?e.description:"",r=e.database||"",s=e.schema||"";return c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"font-medium",children:t}),n&&c.jsx("div",{className:"text-sm text-muted-foreground",children:n}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["Type: ",e.type,r&&` • Database: ${r}`,s&&` • Schema: ${s}`]})]})};function aXe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=C.useState(!1),i=e.length>0;e.length,t.length,e.length<t.length;const a=e.length>=3?e.slice(0,2):e,l=e.length>=3?e.slice(2):[],u=l.length>0;return c.jsx(Ln,{children:c.jsx("div",{className:"space-y-2",children:i&&c.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.map((d,f)=>{const h="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs(an,{children:[c.jsx(ln,{asChild:!0,children:c.jsxs(Ve,{variant:"secondary",className:"group relative cursor-pointer gap-2 transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[N1(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:nT(d)}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>n(d),children:c.jsx(St,{className:"h-3 w-3"})})]})}),c.jsx(dn,{side:"top",className:"max-w-xs",children:iXe(d)})]},h)}),u&&c.jsxs(an,{open:s,onOpenChange:o,children:[c.jsx(ln,{asChild:!0,children:c.jsxs(Ve,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(f8,{className:"h-3 w-3"}),c.jsxs("span",{className:"text-xs",children:[l.length," more"]}),c.jsx("button",{className:"rounded-full p-0.5 transition-opacity hover:bg-red-100 group-hover:opacity-100",onClick:()=>r(l),children:c.jsx(St,{className:"h-3 w-3"})})]})}),c.jsx(dn,{side:"top",className:"max-h-60 max-w-xs overflow-y-auto p-2",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"Additional Datasets"}),c.jsx("div",{className:"space-y-2",children:l.map(d=>{const f="id"in d?d.id:`${d.connectionId}-${d.name}`;return c.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center",children:N1(d.type,{size:"h-3 w-3"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium",children:nT(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:()=>{n(d),l.length===1&&o(!1)},children:c.jsx(St,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function $ee(e){return e.type==="dataset"&&e.label||e.name}function lXe(e){const t=[];return t.push({label:"Type",value:e.type}),t.push({label:"Name",value:e.name}),e.connectionType&&t.push({label:"Connection",value:e.connectionType}),e.database&&t.push({label:"Database",value:e.database}),e.schema&&t.push({label:"Schema",value:e.schema}),e.type==="dataset"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="dataset"&&e.description&&t.push({label:"Description",value:e.description}),e.type==="model"&&e.label&&t.push({label:"Label",value:e.label}),e.type==="model"&&e.description&&t.push({label:"Description",value:e.description}),t}function cXe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ae,{className:"mb-2 text-xs font-medium text-muted-foreground",children:["Selected Entities (",e.length,")"]}),c.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border border-border/50 p-2",children:c.jsx("div",{className:"flex flex-wrap gap-1",children:e.map((n,r)=>c.jsxs(Ve,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[c.jsxs("span",{className:"mr-1 text-gray-500",children:["[",n.type,"]"]}),$ee(n),c.jsx("button",{onClick:s=>{s.stopPropagation(),t(n)},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 opacity-0 transition-opacity hover:bg-red-100 group-hover:opacity-100",children:c.jsx(St,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function uXe(e){const{tokenProps:t}=Xe(),n=J(l=>l.authToken)||e;Ae(l=>l.selectedConnectionId),Ae(l=>{var u,d;return(d=(u=l==null?void 0:l.card)==null?void 0:u.dataSource)==null?void 0:d.connectionId});const{refetch:r,isPending:s,data:o,isLoading:i,isError:a}=En({queryKey:["semantic-domains"],queryFn:()=>rr(`${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 dXe(e,t){const{tokenProps:n}=Xe(),r=J(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=En({queryKey:["datasets",e],queryFn:()=>rr(`${n.apiServiceUrl}/v1/datasets`,(r==null?void 0:r.accessToken)||"",{domainId:e}),enabled:!!(r!=null&&r.accessToken)&&!!e});return{isPending:o,error:l,datasets:(i==null?void 0:i.datasets)||[],isDatasetsLoading:a,isDatasetsError:l,refetchDatasets:s}}function fXe(e){var g,b;const{tokenProps:t}=Xe(),n=J(x=>x.authToken)||e,{connections:r}=Ci(e),s=Ae(x=>{var y,v;return(v=(y=x==null?void 0:x.card)==null?void 0:y.dataSource)==null?void 0:v.connectionId}),o=r==null?void 0:r.find(x=>x.id===s),i=o==null?void 0:o.type,a=o==null?void 0:o.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.database)||"Database";function u(x){return s&&x?!(x==="API"||x==="S3"):!1}const{data:d,isPending:f,error:h,refetch:m}=En({queryKey:["databases",s],queryFn:()=>rr(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),p=(b=d==null?void 0:d.databases)==null?void 0:b.map(x=>({id:x.database_name,name:x.database_name}));return{isPending:f,error:h,databases:p||[],refetch:m,label:l}}function hXe(e){var g;const{tokenProps:t}=Xe(),n=J(b=>b.authToken)||e,{connections:r}=Ci(e),s=Ae(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ae(b=>{var x,y,v;return(v=(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.dbSelection)==null?void 0:v.database}),i=r==null?void 0:r.find(b=>b.id===s),a=i==null?void 0:i.capabilities,l=((g=a==null?void 0:a.labels)==null?void 0:g.schema)||"Schema";function u(){return!(!s||(i==null?void 0:i.type)==="API"||(i==null?void 0:i.type)==="S3"||!o||!(a!=null&&a.path.includes("schema")))}const{data:d,isPending:f,error:h,refetch:m}=En({queryKey:["schemas",s,o],queryFn:()=>rr(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),p=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:p||[],refetch:m,label:l}}function Lee(e){const{tokenProps:t}=Xe(),n=J(h=>h.authToken)||e,{connections:r}=Ci(e),s=Ae(h=>{var m,p;return(p=(m=h==null?void 0:h.card)==null?void 0:m.dataSource)==null?void 0:p.connectionId}),o=r.find(h=>h.id===s);function i(){return!(!(n!=null&&n.accessToken)||!s)}const{data:a,isPending:l,error:u,refetch:d}=En({queryKey:["dataModels",s],queryFn:()=>rr(`${t.apiServiceUrl}/v1/datamodels`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:i()}),f=a==null?void 0:a.datamodels.map(h=>({id:h.id,name:h.name,label:h.label,description:h.description,connectionId:s,dialect:h.dialect,connectionType:o==null?void 0:o.type,type:"model",database:h.database,schema:h.schema}));return{isPending:l,error:u,dataModels:f||[],refetch:d}}function mXe(){var j,S,N;const e=Ae(E=>E.card.dataSource);Ae(E=>E.actions.updateDirectSource);const t=Ae(E=>E.actions.updateDataSource),[n,r]=C.useState(""),{selectedConnection:s,error:o}=Ci(),{databases:i,isPending:a,error:l,label:u}=fXe(),{schemas:d,isPending:f,error:h,label:m}=hXe(),{error:p}=Lee(),g=s==null?void 0:s.capabilities.path.includes("schema"),b=s==null?void 0:s.capabilities.path.includes("database"),x=u==null?void 0:u.toLowerCase(),y=m==null?void 0:m.toLowerCase(),v=E=>{e&&t({...e,dbSelection:{database:E,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=E=>{var k;if(!((k=e==null?void 0:e.dbSelection)!=null&&k.database))return;const _=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{..._,schema:E},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||p)&&c.jsxs("div",{className:"rounded-md border border-red-200 bg-red-50 p-3",children:[c.jsx("div",{className:"flex items-center",children:c.jsxs("div",{className:"text-sm text-red-800",children:[c.jsx("strong",{children:"Error loading data:"}),c.jsxs("ul",{className:"mt-1 list-inside list-disc",children:[o&&c.jsxs("li",{children:["Connections: ",o]}),l&&c.jsxs("li",{children:[u,": ",l.message]}),h&&c.jsxs("li",{children:[m,": ",h.message]}),p&&c.jsxs("li",{children:["Data Models: ",p.message]})]})]})}),c.jsx(se,{variant:"outline",size:"sm",className:"mt-2",onClick:()=>window.location.reload(),children:"Retry"})]}),c.jsxs("div",{className:"space-y-4",children:[b&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium",children:u}),c.jsxs(ot,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.database)||"",onValueChange:v,disabled:a,children:[c.jsx(nt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(xn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(rt,{children:i.map(E=>c.jsx(ve,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]}),((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium",children:m}),c.jsxs(ot,{value:((N=e==null?void 0:e.dbSelection)==null?void 0:N.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(nt,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(xn,{className:"h-4 w-4 animate-spin"}),c.jsx(at,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(rt,{children:d.map(E=>c.jsx(ve,{className:"hover:bg-muted",value:E.id,children:E.name},E.id))})]})]})]})]})}function pXe(){const e=Ae(l=>l.card.dataSource),t=Ae(l=>l.actions.updateDataSource),[n,r]=C.useState(!1),s=l=>{if(!l||(e==null?void 0:e.mode)!=="upload")return;const u=Array.from(l).map(f=>({id:`file-${Date.now()}-${Math.random()}`,name:f.name,type:"upload",connectionId:"default",connectionType:"none",label:f.name,description:`Uploaded ${new Date().toLocaleString()}`,originalName:f.name,file:f})),d=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...d,...u]})},o=l=>{if(!e)return;const u=(e.selectedEntities||[]).filter(d=>d.id!==l);t({...e,selectedEntities:u})},i=l=>{if(l===0)return"0 Bytes";const u=1024,d=["Bytes","KB","MB","GB"],f=Math.floor(Math.log(l)/Math.log(u));return Number.parseFloat((l/Math.pow(u,f)).toFixed(2))+" "+d[f]},a=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium",children:"Upload Files"}),c.jsxs("div",{className:`rounded-lg border-2 border-dashed p-6 text-center transition-colors ${n?"border-blue-400 bg-blue-50":"border-gray-300 hover:border-gray-400"}`,onDragOver:l=>{l.preventDefault(),r(!0)},onDragLeave:()=>r(!1),onDrop:l=>{l.preventDefault(),r(!1),s(l.dataTransfer.files)},children:[c.jsx(sM,{className:"mx-auto mb-2 h-8 w-8 text-gray-400"}),c.jsx("p",{className:"mb-2 text-sm text-gray-600",children:"Drag and drop files here, or click to select"}),c.jsx("input",{type:"file",multiple:!0,className:"hidden",id:"file-upload",onChange:l=>s(l.target.files),accept:".csv,.json,.xlsx,.xls"}),c.jsx(se,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=document.getElementById("file-upload"))==null?void 0:l.click()},children:"Select Files"}),c.jsx("p",{className:"mt-2 text-xs text-gray-500",children:"Supports CSV, JSON, Excel files"})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ae,{className:"text-xs text-gray-600",children:["Uploaded Files (",a.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:a.map(l=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Ji,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:l.originalName}),c.jsx("p",{className:"text-xs text-gray-500",children:l.file?i(l.file.size):""})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(St,{className:"h-3 w-3"})})]},l.id))})]})]})}function gXe(){const e=Ae(f=>f.card.dataSource),t=Ae(f=>f.actions.updateDataSource),[n,r]=C.useState(""),[s,o]=C.useState(""),[i,a]=C.useState("api"),l=()=>{if(!n.trim()||!s.trim()||!e)return;const f={id:`url-${Date.now()}-${Math.random()}`,name:n.trim(),type:"url",connectionId:"default",connectionType:"none",label:n.trim(),description:`URL source of type ${i}`,url:s.trim(),sourceType:i,originalName:n.trim()},h=(e==null?void 0:e.selectedEntities)||[];t({...e,selectedEntities:[...h,f]}),r(""),o(""),a("api")},u=f=>{if(!e)return;const h=(e.selectedEntities||[]).filter(m=>m.id!==f);t({...e,selectedEntities:h})},d=(e==null?void 0:e.selectedEntities)||[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium text-gray-700",children:"URL Sources"}),c.jsxs("div",{className:"space-y-3 rounded-lg border bg-gray-50 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(mn,{placeholder:"e.g., Sales API, Customer Data",value:n,onChange:f=>r(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(mn,{placeholder:"https://api.example.com/data",value:s,onChange:f=>o(f.target.value),className:"h-8 text-sm"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-xs text-gray-600",children:"Type"}),c.jsxs("select",{value:i,onChange:f=>a(f.target.value),className:"h-8 w-full rounded-md border border-gray-300 px-2 text-sm",children:[c.jsx("option",{value:"api",children:"API Endpoint"}),c.jsx("option",{value:"csv",children:"CSV File"}),c.jsx("option",{value:"json",children:"JSON File"})]})]}),c.jsxs(se,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(Tr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ae,{className:"text-xs text-gray-600",children:["Added Sources (",d.length,")"]}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:d.map(f=>c.jsxs("div",{className:"flex items-center justify-between rounded border bg-gray-50 p-2",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(Sx,{className:"h-4 w-4 flex-shrink-0 text-gray-500"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("p",{className:"truncate text-sm text-gray-700",children:f.name}),c.jsx("p",{className:"truncate text-xs text-gray-500",children:f.url})]})]}),c.jsx(se,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(St,{className:"h-3 w-3"})})]},f.id))})]})]})}function bXe(e,t){var y,v;const{tokenProps:n}=Xe(),r=J(w=>w.authToken)||t,{connections:s}=Ci(t),o=Ae(w=>{var j,S;return(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.connectionId}),i=Ae(w=>{var j,S,N;return(N=(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.database}),a=Ae(w=>{var j,S,N;return(N=(S=(j=w==null?void 0:w.card)==null?void 0:j.dataSource)==null?void 0:S.dbSelection)==null?void 0:N.schema}),l=s==null?void 0:s.find(w=>w.id===o),u=l==null?void 0:l.capabilities,d=((y=u==null?void 0:u.labels)==null?void 0:y.schema)||"Schema";function f(){return o?(l==null?void 0:l.type)==="API"||(l==null?void 0:l.type)==="S3"?!0:!(!i||u!=null&&u.path.includes("schema")&&!a):!1}const{data:h,isPending:m,isLoading:p,error:g,refetch:b}=En({queryKey:[e,o,i,a],queryFn:()=>rr(`${n.apiServiceUrl}/v1/${e}s`,(r==null?void 0:r.accessToken)||"",{connection_id:o,database_name:i,schema_name:a}),enabled:f()}),x=(v=h==null?void 0:h[`${e}s`])==null?void 0:v.map(w=>{var j;return{connectionId:l==null?void 0:l.id,connectionType:l==null?void 0:l.type,dialect:l==null?void 0:l.dialect,type:e,dbObjectType:(j=w==null?void 0:w.table_type)==null?void 0:j.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:m,isLoading:p,error:g,entities:x||[],refetch:b,label:d}}function k1({title:e,message:t}){return c.jsx("div",{className:"rounded-xl border border-destructive/40 bg-destructive/10 p-4 text-destructive shadow-sm",children:c.jsxs("div",{className:"flex items-start gap-4",children:[c.jsx(Yl,{className:"h-6 w-6 flex-shrink-0"}),c.jsxs("div",{className:"flex-1",children:[c.jsx("h4",{className:"text-base font-semibold",children:e}),t&&c.jsx("p",{className:"mt-1 text-sm text-destructive/90",children:t})]})]})})}function xXe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ci(),[i,a]=C.useState(""),[l,u]=C.useState(""),[d,f]=C.useState("tables"),{updateDataSource:h,setSelectedConnectionId:m}=cr(),{entities:p,isLoading:g,error:b}=bXe("table"),{dataModels:x,isPending:y,error:v}=Lee(),w=k=>{const M=s.find(P=>P.id===k);if(!M)return;const T=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:k,connectionType:M.type,mode:T,dbSelection:{database:"",schema:"",entityType:"table"}}),m(k)},j=k=>{var O,I;const M=n||[],T=M.some($=>$.name===k.name&&$.type===k.type);let P;if(T)P=M.filter($=>!($.name===k.name&&$.type===k.type));else{const $={connectionId:e.connectionId,connectionType:e.connectionType,type:k.type,dbObjectType:k.dbObjectType,database:((O=e.dbSelection)==null?void 0:O.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:k.name,dialect:k.dialect};P=[...M,$]}t==null||t(P)},S=k=>{const M=n||[],T=M.some(O=>O.type==="model"&&O.name===k.name);let P;T?P=M.filter(O=>!(O.type==="model"&&O.name===k.name)):P=[...M,k],t==null||t(P)},N=p.filter(k=>k.name.toLowerCase().includes(i.toLowerCase())),E=x.filter(k=>k.name.toLowerCase().includes(l.toLowerCase())),_=C.useCallback(()=>{if(!t)return;const k=n||[];let M=[...k];if(d==="tables"){const P=N.filter(O=>!k.some(I=>I.name===O.name&&I.type==="table")).map(O=>{var I,$;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:O.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:(($=e.dbSelection)==null?void 0:$.schema)||"",name:O.name,dialect:O.dialect}});M=[...k,...P]}else if(d==="datamodels"){const T=E.filter(P=>!k.some(O=>O.name===P.name&&O.type==="model"));M=[...k,...T]}t(M)},[d,N,E,n,e,t]);return C.useEffect(()=>{r&&r(_)},[r,_]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(ot,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(nt,{className:"w-full",children:c.jsx(at,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(rt,{children:s.map(k=>c.jsx(ve,{className:"hover:bg-muted",value:k.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx($l,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:k.name}),c.jsx(Ve,{variant:"secondary",className:"flex-shrink-0 text-xs",children:k.type})]})},k.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(pXe,{}),e.connectionType==="url"&&c.jsx(gXe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(mXe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(Os,{defaultValue:"tables",value:d,onValueChange:k=>f(k),className:"w-full",children:[c.jsxs(ys,{className:"grid w-full grid-cols-2",children:[c.jsxs(nn,{value:"tables",children:["Tables & Views (",N.length,")"]}),c.jsxs(nn,{value:"datamodels",children:["Data Models (",E.length,")"]})]}),c.jsxs(pr,{value:"tables",className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search tables and views...",value:i,onChange:k=>a(k.target.value),className:"h-8 text-sm",disabled:g}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:g?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading tables..."}):b?c.jsx(k1,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):N.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):N.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>j(k),children:[c.jsx(cn,{id:`table-${k.name}`,checked:M,onCheckedChange:()=>j(k),onClick:T=>T.stopPropagation(),disabled:g}),c.jsxs(ae,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[k.name,k.dbObjectType==="view"&&c.jsx(Ve,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),k.dbObjectType==="materialized view"&&c.jsx(Ve,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},k.name)})})]}),c.jsxs(pr,{value:"datamodels",className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search data models...",value:l,onChange:k=>u(k.target.value),className:"h-8 text-sm",disabled:y}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:y?c.jsx("div",{className:"py-4 text-center text-sm",children:"Loading data models..."}):v?c.jsx(k1,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):E.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):E.map(k=>{const M=n.some(T=>T.name===k.name&&T.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(k),children:[c.jsx(cn,{id:`dataModel-${k.name}`,checked:M,onCheckedChange:()=>S(k),onClick:T=>T.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ae,{className:"cursor-pointer",children:k.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:k.description})]})]},k.name)})})]})]})})})]})]})]})}function yXe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var j;const[l,u]=C.useState(""),d=C.useCallback(S=>{const N={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:S};t({...N})},[e,t]);C.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:m}=uXe(),p=o?f.filter(S=>s.includes(S.id)):f,{datasets:g,isPending:b,error:x}=dXe(e==null?void 0:e.semanticDomainId),y=S=>{const N=r||[],E=N.some(k=>k.id===S.id&&k.type==="dataset");let _;if(E)_=N.filter(k=>!(k.id===S.id&&k.type==="dataset"));else{const k={id:S.id,datasetType:S.type,name:S.name||S.table,label:S.label,domainId:S.domainId,description:S.description,database:S.database,schema:S.schema,type:"dataset",connectionId:S.connectionId,connectionType:S.connectionType,dialect:S.dialect,datamodelId:S.datamodelId,sql:S.sql};_=[...N,k]}n==null||n(_)},v=g.filter(S=>S.name.toLowerCase().includes(l.toLowerCase())),w=C.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const S=r||[],E=v.filter(k=>!S.some(M=>M.id===k.id&&M.type==="dataset")).map(k=>({id:k.id,datasetType:k.type,name:k.name||k.table,label:k.label,domainId:k.domainId,description:k.description,database:k.database,schema:k.schema,type:"dataset",connectionId:k.connectionId,connectionType:k.connectionType,dialect:k.dialect,datamodelId:k.datamodelId,sql:k.sql})),_=[...S,...E];n(_)},[v,r,e==null?void 0:e.semanticDomainId,n]);return C.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(ot,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(nt,{className:"w-full",children:c.jsx(at,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((j=p.find(S=>S.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:j.label)||"Select semantic domain"})}),c.jsx(rt,{children:p.map(S=>c.jsx(ve,{className:"hover:bg-muted",value:S.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:S.label}),c.jsx("span",{className:"text-xs",children:S.description})]})},S.id))})]}),m&&c.jsx(k1,{title:"Error loading semantic models",message:m.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(jn,{placeholder:"Search datasets...",value:l,onChange:S=>u(S.target.value),className:"h-8 text-sm",disabled:b}),c.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:b?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"Loading datasets..."}):x?c.jsx(k1,{title:"Error loading datasets",message:x.message||"Failed to load datasets. Please try again.",onRetry:()=>window.location.reload()}):v.length===0?c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:l?"No datasets match your search":"No datasets available"}):v.map(S=>{const N=r.some(E=>E.id===S.id&&E.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(S),children:[c.jsx(cn,{id:`dataset-${S.id}`,checked:N,onCheckedChange:()=>y(S),onClick:E=>E.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ae,{className:"cursor-pointer font-medium",children:S.label||S.name}),c.jsx("span",{className:"text-xs text-gray-500",children:S.description})]})]},S.label||S.name)})})]})]})]})}function DA({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Xe(),{allowedSemanticDomains:i}=o,[a,l]=C.useState([]),{updateDataSource:u}=cr(),d=J(M=>M.isVisualEditing),f=J(M=>M.dashboard.aiContext),{setAiContext:h}=Wt(),m=C.useRef(null),[p,g]=C.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=C.useCallback(M=>{const T=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:T,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...T!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=C.useCallback(M=>{u({...n,...M})},[n,u]);C.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),C.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),C.useEffect(()=>{e?l(s||[]):(m.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const j=M=>{const T=a.filter(P=>!(P.name===M.name&&P.type===M.type));l(T)},S=()=>{l([])},N=C.useCallback(M=>{l(M)},[]),E=C.useCallback(()=>{m.current&&m.current()},[]),_=C.useCallback(M=>{m.current=M,g(!0)},[]);function k(){var M,T;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const P=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,O=(T=a==null?void 0:a[0])==null?void 0:T.connectionType;u({...n,connectionId:P,connectionType:O,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(Gr,{open:e,onOpenChange:t,children:c.jsx(zr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Br,{className:"flex-shrink-0",children:[c.jsx(Vr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(is,{children:r==="aiContext"?"Set the overall data scope for the dashboard":"Select data sets to analyze"})]}),c.jsx("div",{className:"flex-1 grow overflow-y-auto py-4",children:c.jsxs("div",{className:"space-y-4",children:[x&&c.jsx("div",{className:"space-y-2",children:c.jsx(Os,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(ys,{className:"grid w-full grid-cols-2",children:[c.jsx(nn,{value:"database",children:"Direct Source"}),c.jsx(nn,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(yXe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:_}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(xXe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:N,onRegisterSelectAll:_})]})}),c.jsx(cXe,{selectedEntities:a,onDeselectEntity:j}),c.jsx(os,{className:"flex-shrink-0",children:c.jsx("div",{className:"flex w-full justify-between",children:c.jsxs("div",{className:"flex grow justify-end gap-2",children:[c.jsx(se,{variant:"outline",onClick:E,disabled:!p,children:"Select All"}),c.jsx(se,{variant:"outline",onClick:S,disabled:a.length===0,children:"Clear All"}),c.jsxs(se,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(St,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(se,{onClick:k,children:[c.jsx(Ar,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function vXe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=C.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=gl-n;if(l.length>u){ze.error(`You can only attach ${gl} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=SJ(l);if(f.forEach(({file:h,error:m})=>{ze.error(`${h.name}: ${m}`)}),d.length>0)try{const h=await Promise.all(d.map(m=>vA(m)));e(h)}catch(h){console.error("Failed to process files:",h),ze.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.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>=gl}),c.jsx(se,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=gl,title:n>=gl?`Maximum ${gl} files allowed`:"Attach files",children:c.jsx(ZT,{className:"h-4 w-4 text-muted-foreground"})})]})}function wXe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=C.useState(!1),a=C.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=C.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),m=f.clientX,p=f.clientY;(m<h.left||m>=h.right||p<h.top||p>=h.bottom)&&i(!1)},[]),u=C.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=C.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 m=gl-r;if(h.length>m){ze.error(`You can only attach ${gl} files per message. You have ${m} slot(s) remaining.`);return}const{valid:p,errors:g}=SJ(h);if(g.forEach(({file:b,error:x})=>{ze.error(`${b.name}: ${x}`)}),p.length>0)try{const b=await Promise.all(p.map(x=>vA(x)));t(b),ze.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),ze.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:X("relative",s),onDragEnter:a,onDragLeave:l,onDragOver:u,onDrop:d,children:[e,o&&!n&&c.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-lg border-2 border-dashed border-primary bg-primary/5 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx(sM,{className:"h-8 w-8 text-primary"}),c.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to upload"}),c.jsxs("p",{className:"text-xs text-muted-foreground",children:[gl-r," slot(s) available"]})]})})]})}const IA=C.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=C.useState(!1),[h,m]=C.useState(!1),[p,g]=C.useState(!1),b=C.useRef(null),x=dp();gje(),pje();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:j}=WC(),{queueMessage:S}=fp(),{addFileAttachment:N,removeFileAttachment:E,clearFileAttachments:_,getFileAttachments:k}=QD(),M=XD(l),T=Ae(U=>U.card.dataSource),P=J(U=>U.dashboard.aiContext),O=J(U=>{var G;return(G=U.dashboard.aiContext)==null?void 0:G.selectedEntities});C.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=C.useCallback(()=>{const U=b.current;if(U){if(!e||e.length===0){U.style.height="10px";return}U.style.height="auto";const G=Math.min(Math.max(U.scrollHeight,10),200);U.style.height=`${G}px`}},[e]);C.useEffect(()=>{I()},[I]),C.useEffect(()=>{const U=setTimeout(()=>{I()},0);return()=>clearTimeout(U)},[I]);const $=()=>{const U=e.trim();!U&&M.length===0||(a!=="ready"?(S(l,U,M),t(""),_(l)):r({preventDefault:()=>{}}))},V=U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),$()),U.key==="@"&&(q(),f(!0))},W=C.useCallback(U=>{const G=WUe(U.nativeEvent);G.length>0&&(U.preventDefault(),G.forEach(async Z=>{const Q=await vA(Z);N(l,Q)}))},[N,l]),L=C.useCallback(U=>{U.forEach(G=>{N(l,G)})},[N,l]),R=C.useCallback(U=>{U.forEach(G=>{N(l,G)})},[N,l]),z=C.useCallback(U=>{E(l,U)},[E,l]),F=U=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===U.id||Z.name===U.name)){const Z=x.selectedEntities.filter(Q=>!(Q.id&&Q.id===U.id||Q.name===U.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,U];y({selectedEntities:Z})}},A=U=>{F(U)},H=U=>{var Q;if(!x.selectedEntities.some(K=>K.id&&K.id===U.id||K.name===U.name)){const K=[...x.selectedEntities,U];y({selectedEntities:K})}const Z="label"in U?U.label:U.name;t(e+`@${Z} `),f(!1),(Q=b.current)==null||Q.focus()},B=U=>{const G=x.selectedEntities.filter(K=>!(K.id&&K.id===U.id||K.name===U.name));y({selectedEntities:G});const Q=`@${"label"in U?U.label:U.name}`;e.includes(Q)&&t(e.replace(Q,"").trim())},Y=U=>{const G=new Set(U.map(K=>K.id||K.name)),Z=x.selectedEntities.filter(K=>!G.has(K.id||K.name));y({selectedEntities:Z});let Q=e;U.forEach(K=>{const le=`@${"label"in K?K.label:K.name}`;Q=Q.replace(le,"").trim()}),t(Q)},q=C.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(P==null?void 0:P.selectedEntities)||[]})},[x.selectedEntities.length,P==null?void 0:P.selectedEntities,y]);return c.jsxs(wXe,{onFilesDropped:L,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(aXe,{entities:x.selectedEntities,availableEntities:O||[],onRemoveEntity:B,onRemoveEntities:Y}),M.length>0&&c.jsx(qUe,{files:M,onRemove:z,showRemove:!s,className:"mb-2"}),c.jsxs("div",{className:"rounded-lg border border-border bg-background shadow-sm focus-within:ring-1 focus-within:ring-foreground/40",children:[c.jsx("textarea",{ref:b,value:e,onChange:n,onKeyDown:V,onPaste:W,onFocus:()=>{I(),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 py-2 text-sm text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-0",style:{height:"40px",lineHeight:"1.5"}}),c.jsxs("div",{className:"flex items-center justify-between border-foreground/10 px-3 py-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[l==="dashboard"&&c.jsxs(ms,{open:d,onOpenChange:U=>{U&&q(),f(U)},children:[c.jsx(ps,{asChild:!0,children:c.jsx(se,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(zoe,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(gs,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:U=>U.preventDefault(),children:c.jsx(oXe,{isOpen:!0,onSelect:F,onDeselect:A,onClose:()=>{var U;f(!1),(U=b.current)==null||U.focus()},availableEntities:O||[],selectedEntities:x.selectedEntities,onTabComplete:H,onSelectAll:()=>{O&&y({selectedEntities:O})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),m(!0)}})})]}),c.jsx(vXe,{onFilesSelected:R,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(se,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(tie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(se,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:$,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(w8,{className:"size-4"})})]})]})]}),c.jsx(DA,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:m,dataSource:T||HS,dialogMode:"aiContext"})]})});IA.displayName="ChatInputWithContext";function zee({assistantType:e,className:t}){const n=Iq(e),{removeFromQueue:r}=fp();return n.length===0?null:c.jsxs("div",{className:X("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(Gl,{className:"h-3 w-3"}),c.jsxs("span",{children:["Pending messages (",n.length,")"]})]}),c.jsx("div",{className:"space-y-2",children:n.map(s=>c.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:c.jsxs("div",{className:"flex items-start justify-between gap-2",children:[c.jsx("div",{className:"flex-1 space-y-1",children:c.jsx("p",{className:"break-words text-foreground/70",children:s.text})}),c.jsx(se,{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:c.jsx(St,{className:"h-3 w-3"})})]})},s.id))})]})}function Bee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=Iq(e),{dequeueMessage:o}=fp();C.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 Vee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=C.useRef(null),[a,l]=C.useState(!0),[u,d]=C.useState(!0),[f,h]=C.useState(!1),[m,p]=C.useState(0),g=C.useRef(0),b=C.useRef(!1),x=C.useRef(0),y=C.useRef(a),v=C.useRef(void 0),w=C.useRef({key:null,count:0,length:0}),j=C.useCallback(()=>{const _=i.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight:0},[]),S=C.useCallback((_={})=>{if(!i.current)return;const{force:M=!1,instant:T=!1}=_;if(!M&&!y.current||!a&&!M)return;const P=T||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!M&&!y.current){b.current=!1,v.current=void 0;return}const O=i.current;if(!O){b.current=!1,v.current=void 0;return}const I=O.scrollHeight;P==="smooth"&&"scrollTo"in O?O.scrollTo({top:I,behavior:P}):O.scrollTop=I,g.current=O.scrollTop,d(!0),l(!0),y.current=!0,h(!1),p(0),b.current=!1,v.current=void 0})},[r,a]),N=C.useCallback(()=>{const _=i.current;if(!_)return;const k=g.current,M=_.scrollTop,T=M-k;if(g.current=M,T<-1){v.current&&(cancelAnimationFrame(v.current),v.current=void 0),b.current=!1,y.current=!1,l(!1),d(!1);return}if(b.current)return;const P=j()<=n;d(P),l(P),y.current=P,P&&(h(!1),p(0))},[j,n]),E=C.useCallback(()=>{p(0),h(!1)},[]);return C.useEffect(()=>{y.current=a},[a]),C.useEffect(()=>{const _=i.current;if(!_||!e||e.length===0){h(!1),p(0),w.current={key:null,count:0,length:0},g.current=_?_.scrollTop:0,x.current=_?_.scrollHeight:0;return}g.current=_.scrollTop,x.current=_.scrollHeight;const k=w.current,M=e[e.length-1],T=(M==null?void 0:M.id)??(M==null?void 0:M.messageId)??(M==null?void 0:M.createdAt)??(M==null?void 0:M.timestamp)??e.length,P=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce((L,R)=>R?typeof R=="string"?L+R.length:typeof R.text=="string"?L+R.text.length:typeof R.content=="string"?L+R.content.length:typeof R.value=="string"?L+R.value.length:L:L,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,O=e.length>k.count,I=T!==k.key,$=P>k.length,V=s&&(M==null?void 0:M.role)==="assistant"&&!O&&(I||$),W=o||V;if(w.current={key:T,count:e.length,length:P},a&&(O||I||$||W)){S({force:!1,instant:W});return}if(!a&&O){const L=e.length-k.count;L>0&&(h(!0),p(R=>R+L))}else!a&&$&&(h(!0),p(L=>L>0?L:1))},[e,S,a,s,o]),C.useEffect(()=>{S({instant:!0})},[S]),C.useEffect(()=>{if(typeof ResizeObserver>"u")return;const _=i.current;if(!_)return;x.current=_.scrollHeight;const k=new ResizeObserver(()=>{const M=i.current;if(!M)return;const T=x.current,P=M.scrollHeight;x.current=P,!b.current&&y.current&&P>T&&S({force:!1,instant:!0})});return k.observe(_),()=>{k.disconnect()}},[S]),C.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:m,scrollToBottom:S,handleScroll:N,resetNewMessageCount:E}}function Hee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=C.useState(r),a=C.useMemo(()=>{if(e.length<=o)return e;const h=Math.max(0,e.length-o);return e.slice(h)},[e,o]),l=e.length>o,u=o>=e.length,d=C.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=C.useCallback(()=>{i(r)},[r]);return C.useEffect(()=>{u&&e.length>o&&o<n&&i(Math.min(e.length,n))},[e.length,o,u,n]),{visibleMessages:a,hasMoreMessages:l,totalMessageCount:e.length,loadMoreMessages:d,resetMessageWindow:f,isShowingAll:u}}function Uee(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:r.text||"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:jJ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const CXe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function SXe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=C.useState(!1),[a,l]=C.useState(gT),[u,d]=C.useState(!1),[f,h]=C.useState(!1),[m,p]=C.useState(!1),g=n??m,{isLocalDev:b,isConsoleMode:x}=Hm(),y=C.useRef(null);J(Ye=>Ye.dashboard.aiScopeTables),J(Ye=>Ye.isDashboardEditing);const v=J(Ye=>Ye.selectedSheetId),{setDataSource:w}=cr(),{addFrame:j,setSelectedFrameId:S,setIsDashboardEditing:N}=Wt(),E=dp(),{setCurrentAIContext:_,updateSelectedEntities:k,setReasoningEffort:M,setShowReasoning:T}=WC(),{clearQueue:P}=fp(),{clearFileAttachments:O,getFileAttachments:I}=QD(),$=XD("dashboard"),V=J(Ye=>Ye.dashboard.aiContext),W=Ae(Ye=>Ye.card.dataSource),{assistantProfile:L}=Pee(),R=J(Ye=>Ye.handleOpenAssistantProfile),{sendMessage:z,isLoading:F,messages:A,setMessages:H,status:B,stop:Y,errorMessage:q,clearError:U}=sXe(),G=C.useCallback(Ye=>{r==null||r(Ye),n===void 0&&p(Ye)},[n,r]),Z=C.useCallback(()=>{G(!g)},[g,G]);C.useEffect(()=>{if(!g)return;function Ye(Yt){Yt.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Ye),()=>{window.removeEventListener("keydown",Ye)}},[g,G]);const[Q,K]=C.useState(""),te=Ye=>{K(Ye.target.value)};function le({sql:Ye,cardTitle:Yt,connectionId:Ge,cardType:et,python:Be,cardConfig:Ke,dataSource:kt,customVisualPreferences:pe}){if(!v)return;const Re={id:Rr(),title:Yt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:et==="horizontalBar"?"y":"x"}},type:et,sql:Ye,python:Be,dataSource:kt,config:Ke,connectionId:Ge,customCardPreferences:pe?{url:pe.url,componentName:pe.componentName,pluginChartType:pe.pluginChartType,settings:pe.settings,type:"component"}:void 0},re={id:Rr(),cards:[Re],activeCardId:Re.id};N(!0),j(v,re,"end"),S(re.id)}const de=Ye=>{Ye.preventDefault();const Yt=Q.trim();if(!Yt&&$.length===0)return;const Ge=[];Yt&&Ge.push({type:"text",text:Yt}),$.forEach(et=>{et.data&&Ge.push({type:"file",mediaType:et.type,filename:et.name,url:`data:${et.type};base64,${et.data}`})}),z({role:"user",parts:Ge}),K(""),O("dashboard"),ie({force:!0})};C.useEffect(()=>{var Ye;e&&((Ye=y.current)==null||Ye.focus())},[e]),Bee({assistantType:"dashboard",status:B,isLoading:F,sendMessage:z});const{hasActiveTools:ce}=Uee(A),{visibleMessages:Ce,hasMoreMessages:ge,totalMessageCount:he,loadMoreMessages:me,resetMessageWindow:oe}=Hee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Ne,isAtBottom:fe,hasNewMessages:Me,newMessageCount:ke,scrollToBottom:ie,handleScroll:xe,resetNewMessageCount:Oe}=Vee(Ce,{threshold:50,behavior:"smooth",isStreaming:F});function be(Ye){Fe();const Yt={role:"user",parts:[{type:"text",text:Ye.title+" "+Ye.subtitle}]};z(Yt)}function De(Ye){Fe(),z({role:"user",parts:[{type:"text",text:Ye}]})}function qe(Ye){Fe(),z({role:"user",parts:[{type:"text",text:Ye}]}),ie({force:!0})}const He=C.useCallback(async()=>{const Ye=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ye),ze.success("Conversation copied")}catch(Yt){console.error("Failed to copy conversation",Yt),ze.error("Unable to copy conversation")}},[A]);function Fe(){E.selectedEntities.length===0&&_({selectedEntities:(V==null?void 0:V.selectedEntities)||[]})}const yt=(Q==null?void 0:Q.length)===0&&(A==null?void 0:A.filter(Ye=>Ye.role==="user").length)===0;function je(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function dt(){return c.jsxs(wf,{children:[c.jsx(Cf,{asChild:!0,children:c.jsx(Wc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Pm,{className:"size-3.5"})})}),c.jsxs(yu,{align:"end",children:[c.jsx(Eh,{children:"Options"}),c.jsx(Kd,{}),c.jsx(Mg,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Mg,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Mg,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const Ct=c.jsxs("div",{"data-role":"dashboard-assistant",className:X("flex h-full grow flex-col justify-between break-words px-6 py-4",g&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[c.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[je(),R&&c.jsx(se,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:R,children:(L==null?void 0:L.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&dt(),a&&c.jsx(se,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:He,children:"Copy Conversation"}),c.jsx(Wc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(KT,{className:"size-4"}):c.jsx(W1,{className:"size-4"})}),c.jsx(Wc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{H([]),P("dashboard"),U(),oe()},children:c.jsx(Y1,{className:"size-4"})}),c.jsx(Wc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(St,{className:"size-4"})})]})]}),c.jsxs(tl,{"data-role":"dashboard-assistant-scroll-area",ref:Ne,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:xe,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[ge&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(se,{variant:"outline",size:"sm",onClick:me,className:"text-xs",children:["Load ",Math.min(5,he-Ce.length)," ","more messages (",he-Ce.length," ","hidden)"]})}),c.jsx(kJ,{showTools:a,showSystemMessage:u,messages:Ce,onAddToDashboard:le,onQuickReply:qe,disableQuickReplies:F}),!ce&&c.jsx(NJ,{status:B,errorMessage:q})]}),c.jsx(bi,{orientation:"horizontal"})]}),e&&!fe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(se,{onClick:()=>{ie({force:!0}),Oe()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(kr,{className:"h-4 w-4"}),Me&&ke>0&&c.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:ke>9?"9+":ke})]})}),c.jsxs("div",{className:"space-y-3",children:[!L&&yt&&c.jsx(EJ,{onClick:be,placeholders:CXe}),c.jsx("div",{children:yt&&L&&c.jsx(Oee,{seedQuestions:L.seedQuestions||[],handleSeedQuestionClick:De})}),c.jsx(zee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(IA,{ref:y,setInput:K,stop:Y,input:Q,handleInputChange:te,handleSubmit:Ye=>{Fe(),de(Ye),ie({force:!0})},isLoading:F,status:B,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(DA,{incomingSelectedEntities:(V==null?void 0:V.selectedEntities)||[],open:f,onOpenChange:h,dataSource:W||HS,dialogMode:"aiContext"})]});return g&&s?Zn.createPortal(c.jsx("div",{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:c.jsx("div",{className:"flex h-full w-full",children:Ct})}),s):Ct}function jXe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Wt(),o=J(d=>d.dashboard.sheets),a=J(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=J(d=>d.isDashboardEditing),u=J(d=>d.isVisualEditing);C.useEffect(()=>{if(!l||u)return;async function d(m){const p=m.ctrlKey||m.metaKey;p&&m.key==="c"?(await f(),ze.success("Card copied to clipboard"),m.preventDefault()):p&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText();try{const p=JSON.parse(m);if(p!=null&&p.id){const g=NR(p),b=g.cards.findIndex(x=>x.id===g.activeCardId);b!==-1&&(g.cards[b].title=`${g.cards[b].title} (Copy)`),r(a,g),s(g.id),ze.success("Card pasted from clipboard")}}catch(p){console.error("Failed to parse clipboard contents: ",p)}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function NXe(e,t){switch(e.interactionMode){case"drillToDetail":kXe(e,t);break;case"drillThrough":EXe(e,t);break;case"drillToURL":_Xe(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 kXe(e,t){var l;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=((l=t.getCurrentFilters)==null?void 0:l.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 EXe(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))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function _Xe(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 TXe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(Gr,{open:e,onOpenChange:t,children:c.jsxs(zr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Br,{children:[c.jsx(Vr,{children:i||"Insight Detail"}),c.jsx(is,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(YZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(XZ,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function MXe(){const e=Vt(w=>w.interactionStates),t=Vt(w=>w.setInteractionState),n=Vt(w=>w.clearLastInteractionEvent),r=Vt(w=>w.replaceCardWithInsight),s=Vt(w=>w.setPendingDrillThrough),o=Vt(w=>w.pendingDrillThrough),i=Vt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Wt(),{selectDashboard:u}=Cx(),d=J(w=>w.dashboard),f=J(w=>w.filterValues),{data:h,isLoading:m}=F7((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[p,g]=C.useState({open:!1,insightId:""}),b=QZ(p.insightId,{enabled:p.open&&!!p.insightId}),x=C.useRef(new Set),y=C.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:j,contextMode:S})=>{g({open:!0,insightId:w,filters:j,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:S})},replaceCardContent:({cardId:w,insightId:j,filters:S,contextMode:N})=>{r(w,j,S,N)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:j,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:E})=>{const k={sourceCardId:Da,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...ii(),appliedClickFilters:[k],contextMode:j,sourceDashboardId:S,sourceDashboardTitle:N,targetDashboardId:E};t(Da,M)}}),[a,r,f,l,d,s,t]);C.useEffect(()=>{Object.entries(e).forEach(([w,j])=>{if(j!=null&&j.lastInteractionEvent){const S=j.lastInteractionEvent,N=`${w}-${S.interactionMode}-${S.sourceCardId}-${Date.now()}`;if(x.current.has(N))return;x.current.add(N);try{NXe(S,y)}catch(E){console.error("Error executing interaction event:",E)}finally{n(w),setTimeout(()=>{x.current.delete(N)},5e3)}}})},[e,n,y]),C.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(w){console.error("[DrillThrough] Error during automatic navigation:",w),i()}},[o,h,m,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(TXe,{open:p.open,onOpenChange:v,insightId:p.insightId,filters:p.filters,filterDefinitions:p.filterDefinitions,contextMode:p.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border bg-background p-6 shadow-lg",children:[c.jsx(xn,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function DXe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=IXe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function IXe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function RXe(e){return e?`Back to ${e}`:"Back"}function AXe(){var x,y,v,w,j;const e=Vt(S=>S.interactionStates[Da]),t=J(S=>S.actions.goBackFromDrill),n=J(S=>S.actions.clearDrillContext),{selectDashboard:r}=Cx(),[s,o]=C.useState({x:16,y:16}),[i,a]=C.useState(!1),l=C.useRef({x:0,y:0});C.useEffect(()=>{if(!i)return;const S=E=>{o({x:E.clientX-l.current.x,y:E.clientY-l.current.y})},N=()=>{a(!1)};return document.addEventListener("mousemove",S),document.addEventListener("mouseup",N),()=>{document.removeEventListener("mousemove",S),document.removeEventListener("mouseup",N)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((w=(v=(y=(x=e==null?void 0:e.appliedClickFilters)==null?void 0:x[0])==null?void 0:y.filterGroups)==null?void 0:v[0])==null?void 0:w.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||!((j=e.appliedClickFilters)!=null&&j.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(S){console.error("[DrillBack] Error during back navigation:",S)}},p=()=>{n()},g=S=>{S.target.closest("button")||(a(!0),l.current={x:S.clientX-s.x,y:S.clientY-s.y})};DXe(f);const b=RXe(d);return c.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:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:g,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((S,N)=>{const E=S.field.label||S.field.name,_=String(S.value);return c.jsxs(Ve,{variant:"secondary",className:"pointer-events-none text-xs",children:[E," = ",_]},N)})})]}),c.jsx(se,{variant:"ghost",size:"sm",onClick:p,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(St,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(se,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(t8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function Wee(){var ge;const{showAssistant:e,tokenProps:t}=Xe(),{preferences:n,isConsoleMode:r}=Hm(),s=((ge=n==null?void 0:n.cardDisplay)==null?void 0:ge.mode)==="print",o=C.useRef(null),i=C.useRef(null),[a,l]=C.useState(!1),{handleDragStart:u,isDraggingRef:d,getStyle:f,getPositionClasses:h}=L6e({initialPosition:"bottom-right"}),m=Od(he=>he.setFullscreen),p=Od(he=>he.setPanelOpen),g=Od(he=>he.setContainer),b=_q("dashboard"),x=Tq(),y=Mq("dashboard"),v=b.isOpen,w=x==="dashboard",j=J(he=>he.isVisualEditing),S=J(he=>he.themeStyle),N=J(he=>{var me;return(me=he.dashboard)==null?void 0:me.sheets}),E=J(he=>he.showFilters),_=J(he=>he.isDashboardEditing),k=J(he=>he.selectedSheetId),M=J(he=>{var me;return(me=he.dashboard)==null?void 0:me.id}),T=J(he=>he.isDashboardPanelOpen),P=J(he=>he.actions.setIsDashboardPanelOpen),{getDefaultSheetId:O,setDefaultSheetId:I,clearDefaultSheetId:$}=Zz(M),[V,W]=C.useState(null);iC(Ut.DASHBOARD);const{setSelectedSheetId:L,setSheetTitle:R,addSheet:z,setSheets:F}=Wt();jXe(i);const{setActiveAssistantType:A}=WC();C.useEffect(()=>{if(M){const he=O();W(he)}},[M,O]),C.useEffect(()=>{v?A("dashboard"):x==="dashboard"&&m(null)},[v,A,x,m]),C.useEffect(()=>{var he;v||(he=o.current)==null||he.resize(0)},[v]);function H(he){var me,oe;he?((me=o.current)==null||me.resize(40),p("dashboard",!0),A("dashboard")):(p("dashboard",!1),m(null),(oe=o.current)==null||oe.resize(0),A(null))}function B(){const he={id:Rr(),title:"New Sheet"};z(he),L(he.id)}function Y(he,me){if(!M)return;V===he?($(),W(null),ze.success("Default sheet cleared")):(I(he),W(he),ze.success(`"${me}" set as default sheet`))}function q(he){var me;he<1?(p("dashboard",!1),m(null),A(null),(me=o.current)==null||me.resize(0)):(v||p("dashboard",!0),A("dashboard"))}function U(){return(S==null?void 0:S.canvasTheme)==="muted"||!(S!=null&&S.canvasTheme)?"hsl(var(--semaphor-muted))":(S==null?void 0:S.canvasTheme)==="clear"?"":S==null?void 0:S.canvasTheme}const G=(he,me)=>{he.dataTransfer.setData("tabIndex",me.toString())},Z=he=>{he.preventDefault()},Q=(he,me)=>{const oe=he.dataTransfer.getData("tabIndex");if(oe===me.toString())return;const Ne=Array.from(N||[]),[fe]=Ne.splice(parseInt(oe),1);Ne.splice(me,0,fe),F(Ne)},K=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,te=e===!0&&!s&&!v&&!j&&!E;function le(){var he,me;if(N&&N.length>1||_)return c.jsxs(ys,{role:"tab-list",className:"flex h-12 w-0 min-w-full items-center justify-start gap-2 overflow-x-auto rounded-none border-b border-b-muted bg-transparent px-3",children:[r&&K&&c.jsx(se,{style:{borderRadius:S==null?void 0:S.controlInputRadius},variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{P(!T)},className:"h-8 shrink-0 p-2",children:T?c.jsx(i8,{className:"h-4 w-4"}):c.jsx(a8,{className:"h-4 w-4"})}),N==null?void 0:N.map((oe,Ne)=>{const fe=k===oe.id,Me=V===oe.id;return c.jsxs(nn,{draggable:!0,onDragStart:ke=>G(ke,Ne),onDragOver:Z,onDrop:ke=>Q(ke,Ne),style:{borderRadius:S==null?void 0:S.controlInputRadius},onClick:()=>L(oe.id),className:"flex shrink-0 items-center gap-1 border px-2 py-1",value:oe.id,children:[c.jsx(Vb,{enabled:_&&fe,text:oe.title,onSave:ke=>R(oe.id,ke),children:oe.title},oe.id),!_&&fe&&c.jsx("div",{title:Me?"Clear default sheet":"Set as default sheet",children:c.jsx(JT,{className:X("ml-1 size-3 cursor-pointer transition-all",Me?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:ke=>{ke.stopPropagation(),Y(oe.id,oe.title||"Sheet")}})}),_&&fe&&N.length>1&&c.jsx(St,{className:"ml-1 size-3",onClick:()=>l(!0)})]},oe.id)}),_&&c.jsx("div",{style:{borderRadius:(me=(he=S==null?void 0:S.chart)==null?void 0:he.options)==null?void 0:me.borderRadius},className:"flex h-7 shrink-0 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:B,children:c.jsx(Tr,{className:"size-3"})})]})}function de(){return c.jsx("div",{ref:i,style:{},className:"grow",children:N==null?void 0:N.map(he=>c.jsx(pr,{style:{backgroundColor:U()},className:X("mt-0",{}),value:he.id,children:c.jsx(c6e,{sheet:he})},he.id))})}function ce(){var he;return c.jsxs(Os,{"data-role":"dashboard-tabs-container",className:X("relative flex h-full flex-col",S==null?void 0:S.dashboardTabsContainer),onValueChange:me=>{L(me)},value:k||((he=N==null?void 0:N[0])==null?void 0:he.id),children:[le(),c.jsx(tl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:de()}),c.jsx(z6e,{open:a,setOpen:l})]})}const Ce=C.useCallback(he=>{g("dashboard",he)},[g]);return N?c.jsxs(c.Fragment,{children:[c.jsx(MXe,{}),c.jsx(AXe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(aQ,{className:X("flex-1 basis-0 overflow-y-auto transition-opacity",w&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(I_,{children:ce()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx($6e,{open:v,onTabClick:H,withHandle:!0,disabled:!v}),c.jsx(I_,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:q,defaultSize:v?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(SXe,{open:v,setOpen:H,isFullscreen:w,onFullscreenChange:he=>m(he?"dashboard":null),fullscreenContainer:y})})})]})]}),c.jsx("div",{ref:Ce,className:X("absolute inset-0",!w&&"pointer-events-none")}),te&&c.jsx("div",{className:X("absolute z-50 transition-all duration-300 ease-in-out",h().horizontal,h().vertical),style:f(),children:c.jsx(se,{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:()=>{d.current||H(!0)},onMouseDown:u,onTouchStart:u,title:"Open Assistant (drag to move)",children:c.jsx(q1,{className:"h-5 w-5"})})})]})]}):null}function RA({children:e}){return c.jsx(Za,{style:{height:"100%",width:"100%"},children:c.jsx(eoe,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Ln,{delayDuration:0,children:e})})})}function qee({children:e,preferences:t}){const{currentUser:n}=Ps(),r=C.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 c.jsx(m7.Provider,{value:r,children:c.jsx(AR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function PXe(e=2e3,t=500){const n=Toe(),[r,s]=C.useState(!1),[o,i]=C.useState(!1),a=C.useRef(null);return C.useEffect(()=>{const l=setTimeout(()=>s(!0),e);return()=>clearTimeout(l)},[e]),C.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 AA({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=PXe(e,t);return C.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]),c.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 Yee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(rl,{FallbackComponent:gS,children:c.jsxs(PT,{dashboardProps:e,children:[c.jsx(AA,{componentType:"dashboard",componentId:e.id}),c.jsx(RA,{children:c.jsx(qee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(JD,{...e,type:"dashboard",children:c.jsx(Wee,{})})})})})]})})}function g6(e,t){return e.map(n=>({...n,fieldScope:t}))}function OXe(e){const t=new Map;return e.forEach(n=>{const r=`${n.name}-${n.role||"unknown"}`;t.has(r)||t.set(r,n)}),Array.from(t.values())}function b6(e){if(sc(e)||Ux(e))return e.expression}function PA(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=kD(),i=Ae(g=>g.frame.calculatedFields),a=Ae(g=>g.card.config),l=C.useMemo(()=>e.filter(g=>g.fieldScope==="domain"),[e]),u=C.useMemo(()=>e.filter(g=>g.fieldScope!=="domain"),[e]),d=C.useMemo(()=>i!=null&&i.length?g6(i,"dashboard"):[],[i]),f=C.useMemo(()=>{const g=new Map;return d.forEach(b=>{const x=`${b.name}-${b.role||"unknown"}`;g.set(x,b)}),g},[d]),h=C.useMemo(()=>{const g=((a==null?void 0:a.metricColumns)||[]).filter(sc),b=((a==null?void 0:a.groupByColumns)||[]).filter(Ux),y=OXe([...g,...b]).filter(v=>{const w=`${v.name}-${v.role||"unknown"}`,j=f.get(w);if(!j)return!0;const S=b6(v),N=b6(j);return S&&N?S!==N:!0});return g6(y,"card").map(v=>({...v,id:`card-source-${v.id}`}))},[a==null?void 0:a.groupByColumns,a==null?void 0:a.metricColumns,f]),m=C.useMemo(()=>[...l,...d,...h,...u],[h,u,d,l]),p=C.useMemo(()=>t.filter(g=>g.entityId!==pz),[t]);return{columns:e,columnGroups:p,rawColumnGroups:t,columnFields:u,domainCalculatedFields:l,dashboardCalculatedFields:d,cardCalculatedFields:h,scopedFields:m,isLoading:n,hasError:r,error:s,refetch:o}}function OA(e){const{tokenProps:t,authToken:n}=Xe(),r=t==null?void 0:t.apiServiceUrl;return En({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return rr(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 Gee(e,t,n){if(t==="source")return{isValid:!0};const r=yr(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 Kee(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=(t==null?void 0:t.comparisonType)==="none";!o&&i||n(r,{groupByColumns:[],comparisonType:"none"})}const Zee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=OA(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=cr(),h=Ae(I=>I.card.type),m=e==null?void 0:e.id,p=(I,$)=>{if(I.id)return I.id;const V=I.qualifiedEntityName||I.entityName||$;return`${$}-${V}-${I.name}`},g=C.useCallback(I=>{if(!(e!=null&&e.config))return[];switch(I){case"groupBy":return(e.config.groupByColumns||[]).map($=>({...$,id:p($,"groupBy"),label:$.label!==void 0?$.label:$.name}));case"metrics":return(e.config.metricColumns||[]).map($=>({...$,id:p($,"metrics"),label:$.label!==void 0?$.label:$.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map($=>({id:p($,"pivotBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map($=>({id:p($,"sortBy"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,direction:$.direction}));case"detailColumns":return(e.config.detailColumns||[]).map($=>({id:p($,"detailColumns"),name:$.name,dataType:$.dataType,label:$.label!==void 0?$.label:$.name,qualifiedEntityName:$.qualifiedEntityName,entityId:$.entityId,entityName:$.entityName,entityType:$.entityType,dateFormat:$.dateFormat,customFormat:$.customFormat}));case"source":return[];default:return[]}},[e]),b=C.useCallback((I,$)=>{if(m)switch(I){case"groupBy":{r(m,{groupByColumns:$});break}case"metrics":{r(m,{metricColumns:$});break}case"pivotBy":{r(m,{pivotByColumns:$});break}case"sortBy":{r(m,{sortByColumns:$});break}case"detailColumns":{r(m,{detailColumns:$});break}}},[m,r]),x=C.useCallback((I,$,V)=>{if(!m)return;const W=g(I),L=W[$];if(L)switch(I){case"groupBy":s(m,L.id,{label:V});break;case"metrics":o(m,L.id,{label:V});break;case"pivotBy":i(m,L.id,{label:V});break;case"sortBy":a(m,L.id,{label:V});break;case"detailColumns":{const R=W.map((z,F)=>F===$?{...z,label:V}:z);r(m,{detailColumns:R});break}}},[m,g,s,o,i,a,r]),y=C.useCallback((I,$)=>{if(!m)return;const W=g("metrics")[I];W&&o(m,W.id,{aggregate:$,label:IU(W.name,$)})},[m,g,o]),v=C.useCallback((I,$,V,W="groupBy")=>{if(!m)return;const L=g(W),R=L[I];if(!R)return;const z={dateFormat:$,customFormat:$==="custom"&&V?V:void 0};if(W==="detailColumns"){const F=L.map((A,H)=>H===I?{...A,...z}:A);r(m,{detailColumns:F});return}s(m,R.id,z)},[m,g,r,s]),w=C.useCallback((I,$)=>{if(!m)return;const W=g("groupBy")[I];W&&s(m,W.id,{granularity:$})},[m,g,s]),j=C.useCallback((I,$)=>{if(!m)return;const W=g("metrics")[I];W&&o(m,W.id,{aliasTemplate:$})},[m,g,o]),S=C.useCallback((I,$)=>{if(console.log("handleValueAliasesChange",I,$),!m)return;console.log("handleValueAliasesChange",I,$);const W=g("metrics")[I];W&&(console.log("handleValueAliasesChange",$),o(m,W.id,{valueAliases:$}))},[m,g,o]),N=C.useCallback(I=>{if(!m)return;if(g("metrics").length===0){ze.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(m,{comparisonType:I})},[m,r,g]),E=C.useCallback(I=>{m&&r(m,{showTrendline:I})},[m,r]),_=C.useCallback(I=>{m&&r(m,{trendlineWindow:I})},[m,r]),k=C.useCallback(I=>{m&&r(m,{trendlineGranularity:I})},[m,r]),M=C.useCallback(I=>{m&&r(m,{targetValue:I})},[m,r]),T=C.useCallback(async I=>{var A;if(!m)return;const $=[...g("groupBy"),...g("pivotBy"),...g("metrics"),...g("sortBy"),...g("detailColumns")],V=I,W=G1e(V,$,{joinPlan:(A=e==null?void 0:e.config)==null?void 0:A.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!W.isValid){W.showError&&TU();return}const L=X1e(V,$,h);if(!L){ze.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const R=Gee(V,L,h);if(!R.isValid){ze.error("Invalid Field Type",{description:R.reason,position:"top-center",duration:3e3});return}const z=g(L);if(MU(V,z))return;const F=RU(V,L,z);if(F){const H=[...z,F];b(L,H),L==="metrics"&&Kee(h,e==null?void 0:e.config,r,m,H)}},[m,e==null?void 0:e.config,g,b,t,n,h,r]),P=C.useCallback((I,$)=>{if(!m)return;const W=g(I)[$];if(W){if(I!=="sortBy"){const L=g("sortBy"),R=L.filter(z=>!(z.name===W.name&&z.qualifiedEntityName===W.qualifiedEntityName));R.length!==L.length&&r(m,{sortByColumns:R})}switch(I){case"groupBy":l(m,W.id);break;case"metrics":u(m,W.id);break;case"pivotBy":d(m,W.id);break;case"sortBy":f(m,W.id);break;case"detailColumns":{r(m,{detailColumns:(g("detailColumns")||[]).filter((L,R)=>R!==$)});break}}}},[m,g,l,u,d,f,r]);return{getFieldsForContainer:g,setFieldsForContainer:b,updateLabel:x,handleAggregationChange:y,handleDateFormatChange:v,handleGranularityChange:w,handleAliasTemplateChange:j,handleValueAliasesChange:S,removeField:P,handleFieldClick:T,handleKpiComparisonTypeChange:N,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:M,cardType:h}};function YS(e,t){var De,qe,He,Fe,yt;const{tokenProps:n}=Xe(),r=so(),s=Xe().authToken||e,o=Ae(je=>je.selectedConnectionId),i=Ae(je=>je.card),{queryKey:a}=phe(i),l=Ae(je=>je.selectedDatamodelId),u=Ae(je=>je.isDevMode),d=Ae(je=>je.selectedDatabaseName),f=Ae(je=>je.selectedSchemaName),h=Ae(je=>je.selectedTableName),m=Ae(je=>je.actions.setSelectedConnectionId),p=Ae(je=>je.actions.setSelectedDatamodelId),g=Ae(je=>je.actions.setSelectedDatabaseName),b=Ae(je=>je.actions.setSelectedSchemaName),x=Ae(je=>je.actions.setSelectedTableName);Ae(je=>je.actions.setCardSql);const{setQueryConfig:y}=cr();function v(je){var Ct;return o&&je==="API"?!1:o&&je==="S3"?!0:!(!o||!d||d==="NA"||((Ct=_==null?void 0:_.capabilities)==null?void 0:Ct.path.includes("schema"))&&!f)}function w(je){return o&&je?!(je==="API"||je==="S3"):!1}const{refetchConnections:j,connectionsData:S,isConnectionsLoading:N,isConnectionsError:E,selectedConnection:_}=Ci(e),{refetch:k,data:M,isLoading:T,isError:P}=En({queryKey:["models",o],queryFn:()=>rr(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),O=_==null?void 0:_.type,I=(_==null?void 0:_.type)==="API"||(_==null?void 0:_.type)==="S3",{data:$,isLoading:V,isFetching:W,isError:L,refetch:R}=En({queryKey:["databases",o],queryFn:()=>rr(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(O)}),{data:z,isLoading:F,isFetching:A,isError:H,refetch:B}=En({queryKey:["schemas",o,d],queryFn:()=>rr(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&!I&&d!=="NA"}),{data:Y,isLoading:q,isFetching:U,isError:G,refetch:Z}=En({queryKey:["tables",o,d,f],queryFn:()=>rr(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(O)}),{columns:Q,isColumnsLoading:K,isColumnsFetching:te,isColumnsError:le,refetchColumns:de}=AU(e);C.useEffect(()=>{(O==="S3"||O==="API")&&(g(""),b(""),p(""),O==="API"&&x("api"))},[O,x,g,b,p]);const ce=(_==null?void 0:_.type)==="API"?(De=_==null?void 0:_.type)==null?void 0:De.toLowerCase():h||"",Ce=I?"":f||"";function ge(je){x(je),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function he(je){b(je),x("")}function me(je){g(je==="none"?"":je),b(""),x(""),je!=="none"&&je!==""&&p("")}function oe(je){m(je)}function Ne(je){p(je==="none"?"":je),je!=="none"&&je!==""&&g("")}$&&((qe=$==null?void 0:$.databases)==null?void 0:qe.length)>0,z&&((He=z==null?void 0:z.schemas)==null?void 0:He.length)>0;const fe=S==null?void 0:S.connections.map(je=>({id:je.id,name:je.name,type:je.type})),Me=(Fe=M==null?void 0:M.datamodels)==null?void 0:Fe.map(je=>({id:je.id,name:je.name})),ke=$==null?void 0:$.databases.map(je=>({id:je.database_name,name:je.database_name})),ie=z==null?void 0:z.schemas.map(je=>({id:je.schema_name,name:je.schema_name})),xe=Y==null?void 0:Y.tables.map(je=>({id:je.table_name,name:je.table_name})),Oe=(yt=M==null?void 0:M.datamodels.find(je=>je.id===l))==null?void 0:yt.name,be=_!=null&&_.capabilities?qv({schemaName:Ce,tableName:ce,modelName:Oe,databaseName:d||"",capabilities:_.capabilities}):ce;return{connectionItems:fe,selectedConnectionId:o,selectedConnection:_,isConnectionsLoading:N,isConnectionsError:E,modelItems:Me,selectedDatamodelId:l,selectedDatamodelName:Oe,isModelsLoading:T,isModelsError:P,selectedDatabaseName:d,databaseItems:ke,isDatabasesLoadingOrFetching:V||W,isDatabaseError:L,schemaItems:ie,selectedSchemaName:f,isSchemaLoadingOrFetching:F||A,isSchemaError:H,tableItems:xe,selectedTableName:h,isTableLoadingOrFetching:q||U,isTableError:G,columns:Q,isColumnsLoadingOrFetching:K||te,isColumnsError:le,isNonDbConnection:I,connectionType:O,tableName:ce,formattedTableName:be,schemaName:Ce,refetchConnections:j,refetchModels:k,refetchDatabases:R,refetchSchemas:B,refetchTables:Z,refetchColumns:de,handleConnectionChange:oe,handleDatamodelChange:Ne,handleDatabaseChange:me,handleSchemaChange:he,handleTableChange:ge}}function dv(e){return`${e}-${Rr()}`}function x6(e,t){const n=pi(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 FXe(e,t){const n=pi(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function FA(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 Xee(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Qee(){const e=Ae(N=>N.sqlGen),t=Ae(N=>N.isDevMode),n=Ae(N=>N.card.dataSource),r=Ae(N=>{var E,_;return(_=(E=N.card)==null?void 0:E.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=FA(n),a=Xee(n),l=Ae(N=>N.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:p}=cr(),{modelItems:g,selectedDatamodelName:b}=YS(),{selectedConnection:x}=Ci(),y=x==null?void 0:x.capabilities,v=N=>({column_name:N.name,data_type:N.dataType,label:N.label,description:N.description});return{handleDevModeFieldClick:N=>{var _;if(!t)return;const E=v(N);if(t&&a&&s&&y){const k=CT(E,e);m(k);const M=(_=g==null?void 0:g.find(P=>P.id===l))==null?void 0:_.name,T=wT(k,o||"",s,M||"",i||"",y,N.qualifiedEntityName);T&&(f(T),h(!0))}else if(!t){if(yx(E.data_type))if(r&&r.length>0){const k={...E,role:"groupby",id:dv(E.column_name),name:E.column_name,type:E.data_type};d(k)}else{const k={...E,role:"metric",id:dv(E.column_name),name:E.column_name,label:x6(E.column_name,"COUNT"),type:E.data_type,aggregate:"COUNT"};u(k)}if(Ki(E.data_type)){const k={...E,role:"groupby",id:dv(E.column_name),name:E.column_name,type:E.data_type,label:FXe(E.column_name,"month"),granularity:"month"};d(k)}if(Gi(E.data_type)){const k={...E,role:"metric",id:dv(E.column_name),name:E.column_name,label:x6(E.column_name,"SUM"),type:E.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const N=qv({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});p(!1);const _=(x==null?void 0:x.type)==="MSSQL"?`SELECT top 10 * FROM ${N}`:`SELECT * FROM ${N} LIMIT 10`;f(_),h(!0)},handleShowCount:()=>{if(!a||!s||!y){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const N=qv({schemaName:o||"",tableName:s,modelName:b,databaseName:i||"",capabilities:y});f(`SELECT COUNT(*) as count FROM ${N}`),h(!0)},isNumberField:N=>Gi(N.dataType)}}function $Xe(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>ab(o)).join("."),s=ab(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function Jee(){const e=J(a=>a.dashboard.filters)||[],t=J(a=>a.selectedSheetId),n=J(a=>a.actions.addFilter),r=J(a=>a.actions.removeFilter),{removeFilterValues:s}=Wt(),{selectedConnection:o}=Ci();function i(a,l="sheet"){const{qualifiedColumnName:u,qualifiedTableName:d,formattedColumnName:f}=$Xe(a);let h;if(l==="sheet"&&t?h=oke(e,u,d,t):h=e==null?void 0:e.find(m=>wm(m.column)===wm(u)),h)s(h.id),r(h.id);else{const m=Rr(),p=l==="sheet"&&t?[t]:void 0;return n({id:m,location:l,column:u,title:a.label||a.name,dataType:a.dataType,qualifiedTableName:d,connectionId:(o==null?void 0:o.id)||"",operation:"in",applyToSheetIds:p,sql:wK(a.dataType,d,f)}),m}}return{assignFilter:i}}function LXe({column:e}){const[t,n]=C.useState(!1),r=Ae(y=>y.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=FA(r),a=Ae(y=>y.selectedDatamodelId),l=Ae(y=>y.sqlGen),{modelItems:u,selectedConnection:d}=YS(),f=d==null?void 0:d.capabilities,h=Ae(y=>y.actions.setSqlGen),m=Ae(y=>y.actions.setCardSql),p=Ae(y=>y.actions.setRunSql),g=Xee(r);function b(y,v){var E,_;if(!g||!s){console.warn("Cannot generate SQL: missing table metadata");return}const w=CT(y,l,v),j=(E=u==null?void 0:u.find(k=>k.id===a))==null?void 0:E.name;if(h(w),!f){console.warn("Cannot generate SQL: missing connection capabilities");return}const S=(_=y.qualifiedFieldName)==null?void 0:_.split(".").slice(0,-1).join("."),N=wT(w,o||"",s,j||"",i||"",f,S);N&&(m(N),p(!0)),n(!1)}function x(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>b(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>b(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>b(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>b(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>b(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return g?c.jsxs(Wm,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(qm,{asChild:!0,children:c.jsx(Pm,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Mf,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:x()})]}):null}function zXe({field:e,fieldState:t}){return c.jsxs("div",{className:"w-64 bg-background p-0",children:[c.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[c.jsx("h3",{className:"text-sm font-medium text-foreground",children:e.label||e.name}),c.jsx("span",{className:"rounded bg-muted px-2 py-0.5 font-mono text-xs text-muted-foreground",children:e.dataType})]}),e.description&&c.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:e.description}),t&&t.tooltip&&c.jsx("div",{className:"mb-2 rounded bg-muted/50 p-2",children:c.jsx("p",{className:"text-xs text-muted-foreground",children:t.tooltip})}),c.jsx("div",{className:"overflow-x-auto border-t border-border pb-2 pt-2",children:c.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:e.name})})]})}function y6({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o}){const i=Ae(K=>K.isDevMode),a=t==="filter"||t==="inline-filter",l=i||a||(n==null?void 0:n.state)==="unreachable"&&!a,u=J(K=>K.dashboard.filters),d=J(K=>K.selectedSheetId),f=J(K=>K.actions.removeFilter),{removeFilterValues:h}=Wt(),{assignFilter:m}=Jee(),p=t==="filter"?oc(u,d):u,g=t==="filter"?p==null?void 0:p.find(K=>{if(K.title===e.name)return!0;const te=wm(K.column||""),le=wm(e.name);return te.endsWith(`.${le}`)||te===le}):void 0,b=!!g,x=t==="inline-filter"&&(s==null?void 0:s.some(K=>K.column===e.qualifiedFieldName||K.column===e.name)),y=b||x,v=g&&a?u==null?void 0:u.find(K=>K.id===g.id):void 0,w=v&&(v.applyToSheetIds&&v.applyToSheetIds.length>1||v.excludeSheetIds&&v.excludeSheetIds.length>0||!v.applyToSheetIds&&!v.excludeSheetIds&&!v.sheetId);a&&y&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:y,activeFilterOnSheet:g?{id:g.id,title:g.title,column:g.column,applyToSheetIds:g.applyToSheetIds,excludeSheetIds:g.excludeSheetIds}:null,activeFilterForField:v?{id:v.id,title:v.title,column:v.column,applyToSheetIds:v.applyToSheetIds,excludeSheetIds:v.excludeSheetIds}:null,isMultiSheetFilter:w,selectedSheetId:d});const[j,S]=C.useState(!1),[N,E]=C.useState(null),{attributes:_,listeners:k,setNodeRef:M,transform:T,transition:P,isDragging:O}=Ey({id:e.id,disabled:l}),[I,$]=C.useState(!1),V=Ae(K=>K.card),{handleFieldClick:W}=Zee(V),{handleDevModeFieldClick:L,isNumberField:R}=Qee(),z=()=>{v&&(console.log("[SourceField] Removing multi-sheet filter:",v.id),h(v.id),f(v.id)),E(null),S(!1)},F=()=>{if(t==="inline-filter"&&r){r(e);return}t==="filter"?y&&w?(E(e),S(!0)):m(e,"sheet"):i?L(e):W(e)},A={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},H={transform:yi.Transform.toString(T),transition:P},B=()=>{if(!n||a)return{};const te={base:{hoverBorderColor:"hover:border-blue-500/40",hoverBgColor:"hover:bg-blue-50/50 dark:hover:bg-blue-950/20"},draggable:{hoverBorderColor:"hover:border-green-500/40",hoverBgColor:"hover:bg-green-50/30 dark:hover:bg-green-950/20"},indirect:{hoverBorderColor:"hover:border-yellow-500/40",hoverBgColor:"hover:bg-yellow-50/30 dark:hover:bg-yellow-950/20"},unreachable:{borderColor:"border-gray-300/40 dark:border-gray-700/40",bgColor:"bg-gray-50/30 dark:bg-gray-900/20",hoverBgColor:"hover:bg-gray-100/30 dark:hover:bg-gray-800/20",opacity:"opacity-50",cursor:"cursor-not-allowed"}}[n.state]||{};return n.isSelected&&{base:{borderColor:"border-blue-300/30 dark:border-blue-700/30",bgColor:"bg-blue-50/20 dark:bg-blue-950/10",...te},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...te},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...te}}[n.state]||te};function Y(K){return K==="domain"?{label:"Domain",Icon:Sx,className:"border-border bg-muted text-foreground"}:K==="dashboard"?{label:"Dashboard",Icon:qT,className:"border-border bg-muted/70 text-foreground"}:{label:"Card",Icon:S8,className:"border-border bg-muted/40 text-foreground"}}const q=B(),U=e.fieldScope,G=U?Y(U):null,Z=Pw(e),Q=Z&&sc(e);return c.jsxs("div",{ref:M,style:H,...l?{}:_,...l?{}:k,className:X("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",O&&"scale-95 opacity-50",!O&&"border",q.borderColor||"border-transparent",q.bgColor||"",q.hoverBorderColor,q.hoverBgColor||"hover:bg-muted",q.opacity,q.cursor,b&&"border-accent-foreground/20 bg-accent",x&&"border-primary/20 bg-primary/10",{"cursor-pointer":i||a,"cursor-grab active:cursor-grabbing":!l&&!i&&!a}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:F,children:[c.jsxs("div",{className:"relative shrink-0",children:[_m(e.dataType),Z&&c.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",Q?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),c.jsx(Ln,{children:c.jsxs(an,{children:[c.jsx(ln,{asChild:!0,children:c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:`block text-sm text-foreground/80 hover:text-foreground dark:text-muted-foreground ${I?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(dn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(zXe,{field:e,fieldState:n})})]})}),t==="editor"&&G&&c.jsx("span",{title:G.label,className:X("shrink-0 rounded-full border p-1",G.className),children:c.jsx(G.Icon,{className:"h-3.5 w-3.5"})}),i&&!a&&R(e)&&c.jsx("div",{onClick:K=>K.stopPropagation(),children:c.jsx(LXe,{column:A})}),o&&c.jsx("div",{className:"ml-auto flex items-center",onClick:K=>K.stopPropagation(),onPointerDown:K=>K.stopPropagation(),children:o})]}),I&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(Uo,{className:"",children:c.jsxs(Qi,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(j8,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.label||e.name})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(iie,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Ve,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Um,{open:j,onOpenChange:S,children:c.jsxs(Sf,{children:[c.jsxs(jf,{children:[c.jsx(kf,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(Ef,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(Nf,{children:[c.jsx(Tf,{children:"Cancel"}),c.jsx(_f,{onClick:z,children:"Remove Filter"})]})]})})]})}var da="Accordion",BXe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[$A,VXe,HXe]=Ex(da),[GS]=Lr(da,[HXe,gW]),LA=gW(),ete=C.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx($A.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(YXe,{...o,ref:t}):c.jsx(qXe,{...s,ref:t})})});ete.displayName=da;var[tte,UXe]=GS(da),[nte,WXe]=GS(da,{collapsible:!1}),qXe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=ss({prop:n,defaultProp:r??"",onChange:s,caller:da});return c.jsx(tte,{scope:e.__scopeAccordion,value:C.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:C.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(nte,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(rte,{...i,ref:t})})})}),YXe=C.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=ss({prop:n,defaultProp:r??[],onChange:s,caller:da}),l=C.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=C.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(tte,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(nte,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(rte,{...o,ref:t})})})}),[GXe,KS]=GS(da),rte=C.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=C.useRef(null),l=ut(a,t),u=VXe(n),f=bu(s)==="ltr",h=Ie(e.onKeyDown,m=>{var E;if(!BXe.includes(m.key))return;const p=m.target,g=u().filter(_=>{var k;return!((k=_.ref.current)!=null&&k.disabled)}),b=g.findIndex(_=>_.ref.current===p),x=g.length;if(b===-1)return;m.preventDefault();let y=b;const v=0,w=x-1,j=()=>{y=b+1,y>w&&(y=v)},S=()=>{y=b-1,y<v&&(y=w)};switch(m.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?j():S());break;case"ArrowDown":o==="vertical"&&j();break;case"ArrowLeft":o==="horizontal"&&(f?S():j());break;case"ArrowUp":o==="vertical"&&S();break}const N=y%x;(E=g[N].ref.current)==null||E.focus()});return c.jsx(GXe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx($A.Slot,{scope:n,children:c.jsx(Ze.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),E1="AccordionItem",[KXe,zA]=GS(E1),ste=C.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=KS(E1,n),i=UXe(E1,n),a=LA(n),l=xr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(KXe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(yW,{"data-orientation":o.orientation,"data-state":ute(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});ste.displayName=E1;var ote="AccordionHeader",ite=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(da,n),o=zA(ote,n);return c.jsx(Ze.h3,{"data-orientation":s.orientation,"data-state":ute(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});ite.displayName=ote;var rT="AccordionTrigger",ate=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(da,n),o=zA(rT,n),i=WXe(rT,n),a=LA(n);return c.jsx($A.ItemSlot,{scope:n,children:c.jsx(aSe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});ate.displayName=rT;var lte="AccordionContent",cte=C.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(da,n),o=zA(lte,n),i=LA(n);return c.jsx(lSe,{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}})});cte.displayName=lte;function ute(e){return e?"open":"closed"}var ZXe=ete,XXe=ste,QXe=ite,dte=ate,fte=cte;const BA=ZXe,rx=D.forwardRef(({className:e,...t},n)=>c.jsx(XXe,{ref:n,className:X("border-b",e),...t}));rx.displayName="AccordionItem";const sx=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(QXe,{className:"flex",children:c.jsxs(dte,{ref:r,className:X("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,c.jsx(kr,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));sx.displayName=dte.displayName;const ox=D.forwardRef(({className:e,children:t,...n},r)=>c.jsx(fte,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:X("pb-4 pt-0",e),children:t})}));ox.displayName=fte.displayName;let hte=(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 ix=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",requiresTwoInputs:!0},{id:"product",label:"Product (Multiplication)",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",requiresTwoInputs:!0},{id:"scale",label:"Scale (Multiply by Factor)",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],fl=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),Nl=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function v6(e,t,n,r,s,o,i,a,l,u){const d=ix.find(x=>x.id===t);if(!d)throw new Error(`Unknown operation: ${t}`);let f,h=[],m;if(t==="custom"){if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}else if(t==="scale"){if(!n)throw new Error("Metric A is required for scale operation");if(l===void 0||Number.isNaN(l))throw new Error("Constant factor is required for scale operation");f=d.template().replace("{constant}",String(l)),h=[n],m=l}else{if(!n||!r)throw new Error("Metrics A and B are required for standard operations");f=d.template(),h=[n,r]}const p={operation:t,inputFields:h,...m!==void 0&&{constant:m}},g=fl(e);return{id:i||`calc_${hte(10)}`,name:g,label:e,alias:g,qualifiedFieldName:g,dataType:"number",role:"metric",aggregate:"SUM",expression:f,calculatedFormula:p,entityId:o,entityName:cu,entityType:"table",description:`Calculated field: ${e}`}}function JXe(e){var r,s;const t=ix.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 eQe(e,t,n,r,s,o){const i=fl(e);return{id:o||`calc_dim_${hte(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(a=>a.role==="metric"?{...a,role:"metric"}:{...a,role:"groupby"})},entityId:s,entityName:cu,entityType:"table",description:`Calculated field: ${e.trim()}`}}function tQe(){const{domainCalculatedFields:e}=PA(),t=C.useMemo(()=>e.filter(r=>r.role==="metric"),[e]),n=C.useMemo(()=>e.filter(r=>r.role==="groupby"),[e]);return{fields:e,metrics:t,dimensions:n}}function nQe({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(l=>s.includes(l)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return c.jsx(Os,{value:a,onValueChange:l=>t(l),className:"w-full",children:c.jsx(ys,{className:"grid h-9 w-full",style:{gridTemplateColumns:`repeat(${o.length}, minmax(0, 1fr))`},children:o.map(l=>c.jsx(nn,{value:l,disabled:i,className:"text-xs",children:l==="metric"?"Calculated Metric":"Calculated Dimension"},l))})})}function rQe({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,l=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),p=h.toLowerCase();return m.startsWith(`${p}.`)?f.slice(h.length+1):f},d=(f,h)=>{const p=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),g=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const b of g){const x=u(p,b);if(x!==p)return x}return p.includes(".")&&p.split(".").pop()||p};return c.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3 border-r border-border pr-4",children:[a&&c.jsxs("div",{className:"relative",children:[c.jsx(Ko,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(jn,{value:t,onChange:f=>n(f.target.value),placeholder:"Search fields...",className:"pl-10 pr-10"}),t&&c.jsx("button",{type:"button",onClick:()=>n(""),className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",children:c.jsx(St,{className:"size-3.5"})})]}),c.jsx(tl,{className:"min-h-0 flex-1",children:e.length===0?c.jsx("div",{className:"rounded-md border border-dashed border-muted px-3 py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."}):c.jsx(BA,{type:"multiple",defaultValue:l,className:"space-y-2",children:e.map(f=>c.jsxs(rx,{value:f.id,className:"border-none",children:[c.jsx(sx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:f.label}),c.jsx(Ve,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:f.fields.length})]})}),c.jsx(ox,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:f.fields.map(h=>{const m=i.has(h.id),p=!h.isCompatible||o,g=h.isCalculated&&h.role==="metric",b=d(h,f.label);return c.jsxs("button",{type:"button",onClick:()=>h.isCompatible&&!o&&r(h),className:X("group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all",p?"cursor-not-allowed opacity-50":"hover:bg-muted",m&&"border-border bg-muted"),disabled:p,children:[c.jsxs("div",{className:"relative shrink-0",children:[_m(h.dataType),h.isCalculated&&c.jsx("span",{className:X("absolute bottom-0 right-0 translate-x-[30%] translate-y-[35%] rounded-[3px] px-0.5 py-0.5 text-[7px] font-semibold uppercase italic leading-none shadow-sm",g?"bg-emerald-500/90 text-white":"bg-blue-500/90 text-white"),children:"fx"})]}),c.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:c.jsx("span",{className:X("block truncate text-sm text-foreground/80",!p&&"group-hover/container:text-foreground"),children:b})}),m&&c.jsx(Ve,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Selected"})]},h.id)})})})]},f.id))})})]})}function sQe({value:e,onChange:t,allowCustom:n,disabled:r}){const s=ix.filter(l=>n?!0:l.id!=="custom"),i=!s.some(l=>l.id==="custom")&&e==="custom"?[...s,ix.find(l=>l.id==="custom")]:s,a=i.find(l=>l.id===e);return c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ot,{value:e,onValueChange:l=>t(l),disabled:r,children:[c.jsx(nt,{children:c.jsx(at,{})}),c.jsx(rt,{children:c.jsxs(WD,{children:[c.jsx(BC,{children:"OPERATIONS"}),i.map(l=>c.jsx(ve,{value:l.id,children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-mono text-sm",children:l.symbol}),c.jsx("span",{children:l.label})]})},l.id))]})})]}),a&&c.jsx("p",{className:"text-xs text-muted-foreground",children:a.description})]})}const oQe={COUNT:"Count",DISTINCT:"Count Distinct",SUM:"Sum",AVG:"Average",MIN:"Minimum",MAX:"Maximum",MEDIAN:"Median"};function iQe({value:e,onChange:t,disabled:n,fieldDataType:r,allowMedian:s}){const i=(r?yr(r):"number")==="number",a=["SUM","AVG","COUNT","DISTINCT","MIN","MAX"],l=i?s?[...a,"MEDIAN"]:a:["COUNT","DISTINCT"];return c.jsxs(ot,{value:e,onValueChange:u=>t(u),disabled:n,children:[c.jsx(nt,{className:"h-9",children:c.jsx(at,{})}),c.jsx(rt,{children:l.map(u=>c.jsx(ve,{value:u,children:oQe[u]},u))})]})}const aQe=e=>{const n=(e.name||e.baseLabel||e.label||e.tokenLabel||"").trim();return n.includes(".")&&n.split(".").pop()||n};function w6({label:e,input:t,availableFields:n,excludeFieldIds:r,onFieldSelect:s,onAggregateChange:o,onRemove:i,onActivate:a,allowMedian:l,disabled:u}){const d=(t==null?void 0:t.field.id)||"",f=r!=null&&r.length?n.filter(h=>!r.includes(h.id)):n;return c.jsxs("div",{className:X("flex items-center gap-2 rounded-md border border-border px-2 py-2",a&&!u&&"cursor-pointer",u&&"opacity-60"),onClick:u?void 0:a,children:[c.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded bg-muted font-mono text-xs font-semibold",children:e}),c.jsxs("div",{className:"flex flex-1 gap-2",children:[c.jsxs(ot,{value:d,onValueChange:h=>{const m=f.find(p=>p.id===h);m&&s(m)},disabled:u,children:[c.jsx(nt,{className:"h-9 flex-1",children:c.jsx(at,{placeholder:"Select field"})}),c.jsx(rt,{children:f.map(h=>c.jsx(ve,{value:h.id,children:aQe(h)},h.id))})]}),c.jsx("div",{className:"w-36",children:c.jsx(iQe,{value:(t==null?void 0:t.aggregate)||"SUM",onChange:o,disabled:u||(t==null?void 0:t.isCalculatedField),fieldDataType:t==null?void 0:t.field.dataType,allowMedian:l})})]}),t&&c.jsx(se,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:h=>{h.stopPropagation(),i()},disabled:u,children:c.jsx(St,{className:"h-3.5 w-3.5"})})]})}const C6=C.forwardRef(function({value:t,onChange:n,onGenerate:r,showGenerate:s,disabled:o},i){return c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("span",{className:"text-sm font-medium",children:"Expression"}),s&&c.jsxs(se,{type:"button",size:"sm",variant:"outline",onClick:r,disabled:o,className:"h-7 gap-2 text-xs",children:[c.jsx(q1,{className:"h-3.5 w-3.5"}),"Generate with AI"]})]}),c.jsx(Yb,{ref:i,value:t,onChange:a=>n(a.target.value),disabled:o,placeholder:"CASE WHEN {Amount} > 100 THEN 'Large' ELSE 'Small' END",className:"min-h-[140px] font-mono text-xs"})]})});function lQe({result:e}){const t=e.errors.length>0;return c.jsxs("div",{className:X("rounded-md border px-3 py-2 text-xs",t?"border-destructive/40 bg-destructive/10 text-destructive":"border-emerald-500/30 bg-emerald-500/10 text-emerald-700"),children:[c.jsx("div",{className:"font-medium",children:t?"Validation Failed":"Validation Passed"}),e.tokens.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Tokens Found"}),e.tokens.map(n=>c.jsx("div",{children:n.field?`{${n.token}} -> ${n.field.qualifiedFieldName||n.field.name}`:`{${n.token}}`},n.token))]}),e.errors.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Errors"}),e.errors.map((n,r)=>c.jsxs("div",{children:[n.message,n.suggestion?` (${n.suggestion})`:""]},`${n.code}-${r}`))]}),e.warnings.length>0&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Warnings"}),e.warnings.map((n,r)=>c.jsxs("div",{children:[n.message," ",n.suggestion]},`${n.code}-${r}`))]}),e.inferredDataType&&c.jsxs("div",{className:"mt-2 text-[11px] text-muted-foreground",children:["Inferred Output Type: ",e.inferredDataType]})]})}function S6({onValidate:e,isValidating:t,validationResult:n,fallbackResult:r,error:s,showFallback:o,disabled:i}){return c.jsxs("div",{className:"space-y-2",children:[c.jsx(se,{type:"button",variant:"outline",onClick:e,disabled:t||i,className:"h-8",children:t?"Validating...":"Validate Expression"}),s&&c.jsx("div",{className:"text-xs text-destructive",children:s}),(n||o)&&c.jsx(lQe,{result:n||r})]})}function cQe({scope:e,onChange:t,showDashboardScope:n,showDomainScope:r,error:s,disabled:o}){return c.jsxs("div",{className:"space-y-3 border-t border-border pt-4",children:[c.jsx(ae,{children:"Availability"}),c.jsxs(Qs,{value:e,onValueChange:i=>t(i),className:"space-y-2",disabled:o,children:[c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(bn,{id:"scope-card",value:"card"}),c.jsx(ae,{htmlFor:"scope-card",className:"text-sm font-normal",children:"This card only"})]}),n&&c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(bn,{id:"scope-dashboard",value:"dashboard"}),c.jsx(ae,{htmlFor:"scope-dashboard",className:"text-sm font-normal",children:"All cards in this dashboard"})]}),r&&c.jsxs("div",{className:"flex items-center space-x-2",children:[c.jsx(bn,{id:"scope-domain",value:"domain"}),c.jsx(ae,{htmlFor:"scope-domain",className:"text-sm font-normal",children:"Save to domain"})]})]}),s&&c.jsx("p",{className:"text-xs text-red-500",children:s})]})}function uQe({description:e,tags:t,onDescriptionChange:n,onTagsChange:r,descriptionError:s,disabled:o}){return c.jsxs("div",{className:"space-y-3 rounded-md border border-muted bg-muted/30 p-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"domain-description",children:"Description"}),c.jsx(vu,{id:"domain-description",value:e,onChange:i=>n(i.target.value),placeholder:"Explain what this metric represents",className:X("text-sm",s&&"border-red-500"),rows:3,disabled:o}),s&&c.jsx("p",{className:"text-xs text-red-500",children:s})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"domain-tags",children:"Tags (optional)"}),c.jsx(mn,{id:"domain-tags",value:t,onChange:i=>r(i.target.value),placeholder:"profitability, kpi",disabled:o})]}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"This field will be visible to all dashboards using this domain."})]})}function dQe({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=Xe(),[o,i]=C.useState(!1),[a,l]=C.useState(null);return{generateExpression:C.useCallback(async d=>{var f;if(!e)return l("AI generation is not available"),null;if(!d.trim())return l("Describe what you want to calculate"),null;i(!0),l(null);try{const h={type:"calculated-field-expression",context:{userQuery:d,availableFields:t.map(p=>({name:p.tokenLabel,dataType:p.dataType})),fieldType:n},options:{dialect:r}},m=await eo(e,(s==null?void 0:s.accessToken)||"",h);if(!m.success||!((f=m.result)!=null&&f.generated))throw new Error(m.error||"No expression generated");return m.result.generated}catch(h){return l((h==null?void 0:h.error)||(h==null?void 0:h.message)||"AI generation failed"),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),isGenerating:o,error:a}}function fQe({open:e,onOpenChange:t,availableFields:n,fieldType:r,onExpressionGenerated:s,endpoint:o,dialect:i}){const[a,l]=C.useState(""),[u,d]=C.useState(""),[f,h]=C.useState(""),{generateExpression:m,isGenerating:p,error:g}=dQe({endpoint:o,availableFields:n,fieldType:r,dialect:i}),b=C.useMemo(()=>{const S=f.trim().toLowerCase();return S?n.filter(N=>[N.label,N.baseLabel,N.name,N.tokenLabel,N.entityName,N.qualifiedEntityName].filter(Boolean).join(" ").toLowerCase().includes(S)):n},[n,f]),x=S=>{const E=(S.name||S.baseLabel||S.label||S.tokenLabel||"").trim();return E.includes(".")&&E.split(".").pop()||E},y=S=>{const N=S.entityName||S.qualifiedEntityName||"";return N?N==="SEMAPHOR_CALCULATED_FIELD"?"Calculated":N.includes(".")&&N.split(".").pop()||N:"—"},v=async()=>{const S=await m(a.trim());S&&d(S)},w=()=>{u.trim()&&(s(u.trim()),l(""),d(""),t(!1))},j=()=>{l(""),d(""),h(""),t(!1)};return c.jsx(Gr,{open:e,onOpenChange:S=>{S?t(!0):j()},children:c.jsxs(zr,{className:"max-w-3xl",children:[c.jsxs(Br,{children:[c.jsx(Vr,{children:"Generate Expression with AI"}),c.jsx(is,{children:"Describe what you want to calculate and we will draft a SQL expression."})]}),c.jsxs("div",{className:"space-y-6",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"ai-prompt",children:"Describe what you want to calculate"}),c.jsx(Yb,{id:"ai-prompt",value:a,onChange:S=>l(S.target.value),placeholder:"Create a bucket that categorizes orders as 'Large' when amount is greater than 1000",rows:2})]}),c.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs text-muted-foreground",children:[c.jsx("span",{children:"Be specific about conditions, buckets, or math you want to apply."}),c.jsx(se,{size:"sm",onClick:v,disabled:p||!a.trim(),children:p?"Generating...":u?"Regenerate":"Generate"})]}),g&&c.jsx("p",{className:"text-xs text-destructive",children:g})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Available fields"}),c.jsxs("div",{className:"relative",children:[c.jsx(Ko,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),c.jsx(mn,{value:f,onChange:S=>h(S.target.value),placeholder:"Search fields...",className:"pl-9"})]}),c.jsx("div",{className:"overflow-hidden rounded-lg border border-border",children:c.jsx("div",{className:"max-h-48 overflow-y-auto",children:c.jsxs("table",{className:"w-full text-sm",children:[c.jsx("thead",{className:"sticky top-0 z-10 border-b bg-muted",children:c.jsxs("tr",{children:[c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Field"}),c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Type"}),c.jsx("th",{className:"bg-muted/50 px-3 py-2 text-left font-medium",children:"Category"})]})}),c.jsx("tbody",{className:"divide-y",children:b.length===0?c.jsx("tr",{children:c.jsx("td",{colSpan:3,className:"py-6 text-center text-xs text-muted-foreground",children:"No fields match your search."})}):b.map(S=>c.jsxs("tr",{className:"hover:bg-muted/30",children:[c.jsx("td",{className:"px-3 py-1.5 font-mono text-xs",children:x(S)}),c.jsx("td",{className:"px-3 py-1.5",children:c.jsx(Ve,{variant:"secondary",className:"px-1.5 py-0 text-[11px]",children:S.dataType})}),c.jsx("td",{className:"px-3 py-1.5 text-sm text-muted-foreground",children:y(S)})]},S.id))})]})})})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Generated expression"}),c.jsx(Yb,{value:u,readOnly:!0,rows:2,className:"font-mono text-sm"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Review the generated expression before using it."})]})]}),c.jsxs(os,{className:"gap-2",children:[c.jsx(se,{variant:"ghost",onClick:j,children:"Cancel"}),c.jsx(se,{onClick:w,disabled:!u.trim(),children:"Use Expression"})]})]})})}const hQe=/\{([^}]+)\}/g;function ZS(e){return e.trim().toLowerCase()}function _1(e){return Array.from(e.matchAll(hQe)).map(t=>t[1]).filter(Boolean)}function mQe(e){const t=new Set,n=[];return e.forEach(r=>{const s=ZS(r);t.has(s)||(t.add(s),n.push(r))}),n}function VA(e){const t=new Map,n=(r,s)=>{const o=ZS(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 tg(e,t){const n=_1(e),r=mQe(n),s=VA(t),o=r.map(a=>{const l=s.get(ZS(a))||[];return l.length===1?l[0]:null}),i=r.filter((a,l)=>!o[l]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function j6(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${pQe(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function pQe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const gQe=e=>e.entityName===Qh||e.entityName===cu?"Calculated Fields":e.qualifiedEntityName?cb(e.entityName||e.qualifiedEntityName):cb(e.entityName||"Other"),bQe=e=>yr(e.dataType||"")==="number";function xQe(e,t,n){const r=new Set((n||[]).map(s=>Nl(s)));return e.filter(s=>{const o=Nl(s.id);return o&&r.has(o)?!1:t==="dimension"?s.role!=="metric":!0})}function yQe(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==cu?`${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 vQe(e,t,n,r){if(t!=="metric")return e.map(o=>({...o,isCompatible:!0}));if(!n)return e.map(o=>({...o,isCompatible:!0}));const s=n==="COUNT"||n==="DISTINCT";return e.map(o=>{const i=s||bQe(o);return{...o,isCompatible:i}}).filter(o=>r)}function wQe(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 CQe(e){const t=new Map;return e.forEach(n=>{var s;const r=n.qualifiedEntityName||n.entityName||"Other";t.has(r)||t.set(r,{id:r,label:gQe(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function SQe({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=C.useMemo(()=>xQe(e,t,r),[e,t,r]),a=C.useMemo(()=>yQe(i),[i]),l=C.useMemo(()=>i.map(m=>{const p=m.label||m.name,g=m.role==="metric"&&sc(m)||m.role==="groupby"&&Ux(m);return{...m,baseLabel:p,tokenLabel:a.get(m.id)||p,isCalculated:g,isCompatible:!0}}),[i,a]),u=C.useMemo(()=>VA(l),[l]),d=C.useMemo(()=>vQe(l,t,s,o),[l,t,s,o]),f=C.useMemo(()=>wQe(d,n),[d,n]),h=C.useMemo(()=>CQe(f),[f]);return{allFields:l,filteredFields:f,groups:h,tokenCandidates:u}}const jQe=e=>{let t=0;for(const n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0},NQe=(e,t)=>{const n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return 0;if(!n.length)return r.length;if(!r.length)return n.length;const s=[];for(let o=0;o<=r.length;o+=1)s[o]=[o];for(let o=0;o<=n.length;o+=1)s[0][o]=o;for(let o=1;o<=r.length;o+=1)for(let i=1;i<=n.length;i+=1)r.charAt(o-1)===n.charAt(i-1)?s[o][i]=s[o-1][i-1]:s[o][i]=Math.min(s[o-1][i-1]+1,s[o][i-1]+1,s[o-1][i]+1);return s[r.length][n.length]},kQe=(e,t)=>t.map(r=>({candidate:r,distance:NQe(e,r)})).filter(r=>r.distance>0&&r.distance<=3).sort((r,s)=>r.distance-s.distance).slice(0,3).map(r=>r.candidate),EQe=(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){const s=((r=t[0])==null?void 0:r.dataType)||"";if(/date|timestamp/i.test(s))return"date";if(/int|decimal|float|double|num|real/i.test(s))return"number";if(/boolean/i.test(s))return"boolean"}return"string"}},_Qe=e=>e.map(t=>({id:t.id,name:t.name,label:t.tokenLabel,dataType:t.dataType,entityName:t.entityName,role:t.role}));function TQe({expression:e,availableFields:t,excludeFieldIds:n,validationEndpoint:r,connectionId:s,dialect:o}){const{authToken:i}=Xe(),[a,l]=C.useState(null),[u,d]=C.useState(!1),[f,h]=C.useState(null),m=C.useMemo(()=>VA(t),[t]),p=C.useMemo(()=>{const x=[],y=[],v=e.trim();v||x.push({code:"SYNTAX_ERROR",message:"Expression is required"}),v&&!jQe(v)&&x.push({code:"SYNTAX_ERROR",message:"Unbalanced parentheses in expression"});const j=_1(e).map(N=>{const E=m.get(ZS(N))||[];if(!E.length){const M=Array.from(m.keys()),T=kQe(N,M),P=T.length?`Did you mean {${T[0]}}?`:void 0;return x.push({code:"UNKNOWN_TOKEN",message:`Unknown field token: {${N}}`,suggestion:P}),{token:N,field:null,error:"Unknown token"}}if(E.length>1)return x.push({code:"UNKNOWN_TOKEN",message:`Token {${N}} matches multiple fields. Use a disambiguated label.`}),{token:N,field:null,error:"Ambiguous token"};const _=E[0];return(n||[]).map(Nl).includes(Nl(_.id))?(x.push({code:"SELF_REFERENCE",message:"Cannot reference the field being edited"}),{token:N,field:null,error:"Self reference"}):{token:N,field:_}});/\bCASE\b/i.test(e)&&!/\bELSE\b/i.test(e)&&y.push({code:"MISSING_ELSE",message:"CASE expression missing ELSE clause",suggestion:"Add an ELSE branch to handle default values."}),/\//.test(e)&&!/NULLIF\s*\(/i.test(e)&&y.push({code:"DIVISION_BY_ZERO",message:"Division may result in divide-by-zero errors",suggestion:"Wrap the denominator in NULLIF(..., 0)."});const S=j.map(N=>N.field).filter(Boolean);return{isValid:x.length===0,tokens:j,errors:x,warnings:y,inferredDataType:EQe(e,S)}},[e,n,m]),g=C.useCallback(async()=>{var v;if(h(null),!r||!p.isValid)return l(p),p;const x=r,y={type:"calculated-field-expression",value:e,context:{availableFields:_Qe(t),connectionId:s,excludeFieldIds:n,dialect:o}};d(!0);try{const w=await eo(x,(i==null?void 0:i.accessToken)||"",y),j=w.errors||[],S=w.warnings||[],N={...p,isValid:w.valid&&j.length===0,errors:j,warnings:S,inferredDataType:((v=w.metadata)==null?void 0:v.inferredType)||p.inferredDataType};return l(N),N}catch(w){return h((w==null?void 0:w.error)||"Validation failed"),l(p),p}finally{d(!1)}},[r,p,e,t,s,n,o,i==null?void 0:i.accessToken]),b=C.useCallback(()=>{l(null),h(null)},[]);return{clientResult:p,validationResult:a,isValidating:u,serverError:f,validateExpression:g,resetValidation:b}}const N6=[{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"}],G2=e=>{if(!e)return"";const t=e.field.tokenLabel||e.field.label||e.field.name,n=e.aggregate;return n==="DISTINCT"?`COUNT(DISTINCT ${t})`:n==="COUNT"?`COUNT(${t})`:`${n}(${t})`},mte=e=>yr(e.dataType||"")==="number",uh=e=>mte(e)?"SUM":"COUNT",K2=(e,t)=>mte(e)||t==="COUNT"||t==="DISTINCT"?t:uh(e);function Z2(e,t){if(e.role==="metric"){const n=e;return sc(n)?n:{...n,aggregate:t}}return{...e,id:`${e.id}_${t.toLowerCase()}`,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`,entityName:e.entityName,entityId:e.entityId,qualifiedEntityName:e.qualifiedEntityName}}function rh(e,t){const n=e.role==="metric"&&sc(e);return{field:e,aggregate:n&&e.aggregate||t,isCalculatedField:n}}function pte({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToDashboard:i,onPromoteMetricToDomain:a,onPromoteDimensionToDomain:l,cardId:u,domainId:d,initialFieldType:f="metric",allowedFieldTypes:h}){var zf;const{tokenProps:m}=Xe(),{selectedConnection:p}=EU(),g=(p==null?void 0:p.dialect)==="bigquery"||(p==null?void 0:p.dialect)==="snowflake",[b,x]=C.useState(f),[y,v]=C.useState(""),[w,j]=C.useState("ratio"),[S,N]=C.useState(null),[E,_]=C.useState(null),[k,M]=C.useState(1),[T,P]=C.useState(""),[O,I]=C.useState(null),[$,V]=C.useState("card"),[W,L]=C.useState(""),[R,z]=C.useState(""),[F,A]=C.useState({}),[H,B]=C.useState("A"),[Y,q]=C.useState(""),[U,G]=C.useState(!1),[Z,Q]=C.useState(null),[K,te]=C.useState(!1),[le,de]=C.useState(!1),[ce,Ce]=C.useState(!1),ge=C.useRef(null),he=C.useRef(!1),me=C.useRef(null),{userContext:oe}=Ps(),{metrics:Ne,dimensions:fe}=tQe(),Me=(oe==null?void 0:oe.type)==="organization",ke=!Me,ie=!!d&&Me,xe=ie&&!!a,Oe=ie&&!!l,be=!!(i||xe||Oe),De=!!i,qe=b==="metric"?xe:Oe,He=(zf=m==null?void 0:m.apiServiceUrl)==null?void 0:zf.replace(/\/$/,""),Fe=He?`${He}/v1/validate`:"/v1/validate",yt=He?`${He}/v1/ai/generate`:"/v1/ai/generate",je=C.useMemo(()=>{var Mt;const Se=[...n];return(((Mt=r==null?void 0:r.calculatedFormula)==null?void 0:Mt.inputFields)||[]).forEach(vn=>{Se.some(qn=>qn.id===vn.id||qn.qualifiedFieldName===vn.qualifiedFieldName||qn.name===vn.name)||Se.push(vn)}),Se},[n,r]),dt=H==="A"?S:E,Ct=b==="metric"&&w!=="custom"?dt==null?void 0:dt.aggregate:void 0,{allFields:Ye,groups:Yt}=SQe({fields:je,mode:b,searchTerm:Y,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:Ct,showIncompatible:!0}),Ge=Ye,{clientResult:et,validationResult:Be,validateExpression:Ke,isValidating:kt,serverError:pe,resetValidation:Re}=TQe({expression:T,availableFields:Ge,excludeFieldIds:r?[r.id]:void 0,validationEndpoint:Fe,connectionId:p==null?void 0:p.id,dialect:p==null?void 0:p.dialect}),re=(Be==null?void 0:Be.inferredDataType)||et.inferredDataType,_e=O||re||"string",We=ix.find(Se=>Se.id===w),it=C.useMemo(()=>{if(!y.trim())return!1;const Se=fl(y),lt=s==="domain"&&(r!=null&&r.name)?fl(r.name):null;return(b==="metric"?Ne:fe).some(vn=>{const Qt=fl(vn.name);return lt&&Qt===lt?!1:Qt===Se})},[fe,Ne,r,s,b,y]),zt=C.useMemo(()=>{if(b==="metric"&&w==="custom"){const{orderedFields:lt}=tg(T,Ge);return lt.filter(Mt=>!!Mt).map(Mt=>Mt.id)}const Se=[];return S!=null&&S.field.id&&Se.push(S.field.id),E!=null&&E.field.id&&Se.push(E.field.id),Se},[Ge,T,b,S,E,w]),un=Se=>{ke||(x(Se),Se==="dimension"&&$==="domain"&&!Oe&&V("card"),Se==="metric"&&$==="domain"&&!xe&&V("card"))},Dn=Se=>{ke||(j(Se),Se==="scale"&&_(null),Se==="custom"&&(N(null),_(null)))},Kr=()=>{v(""),j("ratio"),N(null),_(null),M(1),P(""),I(null),V("card"),L(""),z(""),A({}),q(""),G(!1),Q(null),te(!1),Ce(!1),Re(),t(!1)},Hr=C.useCallback(Se=>je.find(lt=>lt.qualifiedFieldName===Se.qualifiedFieldName||lt.name===Se.name)||Se,[je]),zs=C.useCallback(Se=>{if(!Se.calculatedFormula)return;const lt=Se.calculatedFormula;if(j(lt.operation),P(""),lt.operation==="scale"){const Qt=lt.inputFields[0];Qt&&N(rh(Hr(Qt),Qt.aggregate||"SUM")),M(lt.constant===void 0?1:lt.constant);return}if(lt.operation==="custom"){P(Ni(Se.expression||"",lt.inputFields||[])),N(null),_(null);return}const[Mt,vn]=lt.inputFields;Mt&&N(rh(Hr(Mt),Mt.aggregate||"SUM")),vn&&_(rh(Hr(vn),vn.aggregate||"SUM"))},[Hr]),Ni=C.useCallback((Se,lt)=>Se.replace(/\{field_(\d+)\}/g,(Mt,vn)=>{var Cr;const Qt=lt[Number(vn)];return Qt?`{${((Cr=Ge.find(ki=>ki.id===Qt.id))==null?void 0:Cr.tokenLabel)||Qt.label||Qt.name}}`:Mt}),[Ge]);C.useEffect(()=>{var Mt;if(!e){he.current=!1,me.current=null;return}const Se=r?`${r.role}-${r.id||r.name}`:"new";if(he.current&&me.current===Se)return;if(he.current=!0,me.current=Se,A({}),q(""),Ce(!1),Re(),r){const vn=r.tags||[];if(r.role==="metric"){x("metric"),v(r.label||r.name),V(s||"card"),L(r.description||""),z(vn.join(", ")),zs(r);return}x("dimension");const Qt=r;v(Qt.label||Qt.name),V(s||"card"),P(Ni(Qt.expression||"",((Mt=Qt.calculatedFormula)==null?void 0:Mt.inputFields)||[]));const qn=N6.some(Cr=>Cr.value===Qt.dataType)?Qt.dataType:"string";I(qn),L(Qt.description||""),z(vn.join(", "));return}const lt=h&&h.length>0?h.includes(f)?f:h[0]:f;x(lt),v(""),j("ratio"),N(null),_(null),M(1),P(""),I(null),V("card"),L(""),z("")},[e,r,s,f,h,zs,Ni,Re]);const Fu=Se=>{const lt=`{${Se}}`,Mt=ge.current;if(!Mt){P(Cr=>Cr+lt);return}const vn=Mt.selectionStart||0,Qt=Mt.selectionEnd||0,qn=`${T.slice(0,vn)}${lt}${T.slice(Qt)}`;P(qn),requestAnimationFrame(()=>{Mt.focus();const Cr=vn+lt.length;Mt.setSelectionRange(Cr,Cr)})},JS=Se=>{if(ke)return;if(b==="dimension"||w==="custom"){Fu(Se.tokenLabel||Se.label||Se.name);return}const lt=K2(Se,H==="A"?(S==null?void 0:S.aggregate)||uh(Se):(E==null?void 0:E.aggregate)||uh(Se)),Mt=rh(Se,lt);if(H==="A"){N(Mt),E||B("B");return}_(Mt),S||B("A")},Oy=(Se,lt)=>{if(!ke){if(Se==="A"&&S){N({...S,aggregate:lt});return}Se==="B"&&E&&_({...E,aggregate:lt})}},uc=async()=>{const Se={};if(y.trim()||(Se.name="Name is required"),w==="custom")T.trim()||(Se.expression="Expression is required"),_1(T).length===0&&(Se.expression=Se.expression||"Expression must include field tokens"),tg(T,Ge).unresolvedTokens.length>0&&(Se.expression=Se.expression||"Expression contains unknown or ambiguous tokens"),Se.expression||(await Ke()).isValid||(Se.expression="Fix validation errors before saving");else if(w==="scale")S||(Se.inputA="Please select a metric for input A"),Number.isNaN(k)&&(Se.constant="Please enter a valid multiplication factor");else{if(S||(Se.inputA="Please select a metric for input A"),E||(Se.inputB="Please select a metric for input B"),S&&E){const lt=S.field.id===E.field.id,Mt=S.aggregate===E.aggregate;lt&&Mt&&(Se.inputs="Inputs A and B must be different metrics")}if(r&&r.role==="metric"){const lt=Nl(r.id);(Nl(S==null?void 0:S.field.id)===lt||Nl(E==null?void 0:E.field.id)===lt)&&(Se.inputs="Cannot reference the field being edited")}}return be&&($==="domain"&&!xe&&(Se.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(Se.description="Description is required for domain fields"),$==="domain"&&it&&(Se.name="A domain field with this name already exists")),A(Se),Object.keys(Se).length===0},ej=async()=>{const Se={};return y.trim()||(Se.name="Name is required"),T.trim()||(Se.expression="Expression is required"),_1(T).length===0&&(Se.expression=Se.expression||"Expression must include field tokens"),tg(T,Ge).unresolvedTokens.length>0&&(Se.expression=Se.expression||"Expression contains unknown or ambiguous tokens"),Se.expression||(await Ke()).isValid||(Se.expression="Fix validation errors before saving"),be&&($==="domain"&&!Oe&&(Se.scope="You do not have permission to save to domain"),$==="domain"&&!W.trim()&&(Se.description="Description is required for domain fields"),$==="domain"&&it&&(Se.name="A domain field with this name already exists")),A(Se),Object.keys(Se).length===0},tj=()=>{const{orderedTokens:Se,orderedFields:lt}=tg(T,Ge),Mt=lt.filter(qn=>!!qn),vn=j6(T,Se),Qt=eQe(y,vn,Mt,_e,u,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...Qt}:Qt},nj=()=>{var vn;if(w==="custom"){const{orderedTokens:Qt,orderedFields:qn}=tg(T,Ge),Cr=qn.filter(Ot=>!!Ot),ki=(r==null?void 0:r.role)==="metric"?((vn=r.calculatedFormula)==null?void 0:vn.inputFields)||[]:[],No=new Map;ki.forEach(Ot=>{const dr=Nl(Ot.id);dr&&No.set(dr,Ot),Ot.qualifiedFieldName&&No.set(Ot.qualifiedFieldName,Ot),Ot.name&&No.set(Ot.name,Ot)});const dc=Cr.map(Ot=>{const dr=Nl(Ot.id),Ei=dr&&No.get(dr)||Ot.qualifiedFieldName&&No.get(Ot.qualifiedFieldName)||No.get(Ot.name),oj=((Ei==null?void 0:Ei.role)==="metric"?Ei.aggregate:void 0)||(Ot.role==="metric"?Ot.aggregate:void 0)||uh(Ot);return Z2(Ot,oj)}),Jn=j6(T,Qt),rn=v6(y,w,null,null,{},u,r==null?void 0:r.id,Jn,void 0,dc);return r&&r.role==="metric"?{...r,...rn}:rn}const Se=S?Z2(S.field,S.aggregate):null,lt=E?Z2(E.field,E.aggregate):null,Mt=v6(y,w,Se,lt,{},u,r==null?void 0:r.id,void 0,w==="scale"?k:void 0);return r&&r.role==="metric"?{...r,...Mt}:Mt},Fy=async Se=>{var Mt,vn,Qt;if(b==="dimension"){const qn=tj();if(Se==="dashboard"){if(!i){A(Cr=>({...Cr,scope:"Dashboard scope is not available"}));return}i(qn),Kr();return}if(Se==="domain"){if(!l){A(rn=>({...rn,scope:"Domain scope is not available"}));return}const Cr=((Mt=qn.calculatedFormula)==null?void 0:Mt.inputFields)||[],ki=new Map,No=Cr.map(rn=>{const Ot=fl(rn.label||rn.name),dr=ki.get(Ot)||0;return ki.set(Ot,dr+1),dr===0?Ot:`${Ot}_${dr+1}`}),dc=((vn=qn.expression)==null?void 0:vn.replace(/\{field_(\d+)\}/g,(rn,Ot)=>`{${No[Number(Ot)]||Ot}}`))||"",Jn=No.reduce((rn,Ot,dr)=>{const Ei=Cr[dr];return Ux(Ei)?rn[Ot]={dimension:Ei.name}:rn[Ot]={dataset:Ei.entityName,field:Ei.name},rn},{});try{await l({name:fl(y),label:y.trim(),description:W.trim(),expression:dc,inputs:Jn,dataType:_e,tags:R.split(",").map(rn=>rn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(rn){A(Ot=>({...Ot,scope:(rn==null?void 0:rn.message)||"Failed to save to domain"}));return}Kr();return}o(qn),Kr();return}const lt=nj();if(Se==="dashboard"){if(!i){A(qn=>({...qn,scope:"Dashboard scope is not available"}));return}i(lt),Kr();return}if(Se==="domain"){if(!a){A(Jn=>({...Jn,scope:"Domain scope is not available"}));return}if(!lt.calculatedFormula){A(Jn=>({...Jn,scope:"Calculated formula missing"}));return}const qn=lt.calculatedFormula.inputFields,Cr=new Map,ki=qn.map(Jn=>{const rn=fl(Jn.label||Jn.name),Ot=Cr.get(rn)||0;return Cr.set(rn,Ot+1),Ot===0?rn:`${rn}_${Ot+1}`}),No=((Qt=lt.expression)==null?void 0:Qt.replace(/\{field_(\d+)\}/g,(Jn,rn)=>`{${ki[Number(rn)]||rn}}`))||"",dc=ki.reduce((Jn,rn,Ot)=>{const dr=qn[Ot];return dr.role==="metric"?sc(dr)?Jn[rn]={metric:dr.name}:Jn[rn]={dataset:dr.entityName,field:dr.name,aggregate:dr.aggregate}:Jn[rn]={dataset:dr.entityName,field:dr.name},Jn},{});try{await a({name:fl(y),label:y.trim(),description:W.trim(),expression:No,inputs:dc,tags:R.split(",").map(Jn=>Jn.trim()).filter(Boolean),overwrite:s==="domain",previousName:s==="domain"?r==null?void 0:r.name:void 0})}catch(Jn){A(rn=>({...rn,scope:(Jn==null?void 0:Jn.message)||"Failed to save to domain"}));return}Kr();return}o(lt),Kr()},rj=async()=>{if(ke)return;if(A({}),b==="metric"){if(!await uc())return}else if(!await ej())return;const Se=be?$:s||"card";if(b==="metric"&&Se!=="domain"&&it&&!r){Q(Se),te(!0);return}de(!0);try{await Fy(Se)}finally{de(!1)}},sj=C.useMemo(()=>{if(!We||w==="custom")return"";if(w==="scale"){const Se=Number.isFinite(k)?k:1;return`${G2(S)} x ${Se}`}return`${G2(S)||"A"} ${We.symbol} ${G2(E)||"B"}`},[We,w,S,E,k]);return c.jsxs(c.Fragment,{children:[c.jsxs(Gr,{modal:!1,open:e,onOpenChange:Se=>{Se?t(!0):Kr()},children:[e&&c.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),c.jsxs(zr,{className:"max-w-5xl max-h-[90vh] overflow-hidden",onInteractOutside:Se=>{Se.preventDefault()},children:[c.jsxs(Br,{children:[c.jsxs(Vr,{children:[r?"Edit":"Create"," Calculated Field"]}),c.jsx(is,{children:"Build calculated metrics and dimensions using expressions."})]}),c.jsxs("div",{className:"grid h-[70vh] min-h-0 grid-cols-[320px_1fr] gap-6",children:[c.jsx(rQe,{groups:Yt,searchTerm:Y,onSearchTermChange:q,onFieldClick:JS,selectedFieldIds:zt,disabled:ke}),c.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-4 overflow-y-auto pr-2",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Field Type"}),c.jsx(nQe,{value:b,onChange:un,disabled:ke||!!r,options:h||["metric","dimension"]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"calculated-name",children:"Name"}),c.jsx(mn,{id:"calculated-name",value:y,onChange:Se=>v(Se.target.value),placeholder:"e.g., Profit Margin",className:F.name?"border-red-500":"",disabled:ke}),F.name&&c.jsx("p",{className:"text-xs text-red-500",children:F.name})]}),b==="metric"&&c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Operation"}),c.jsx(sQe,{value:w,onChange:Dn,allowCustom:!0,disabled:ke}),F.operation&&c.jsx("p",{className:"text-xs text-red-500",children:F.operation})]}),w==="custom"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(C6,{ref:ge,value:T,onChange:Se=>{P(Se),Ce(!1)},onGenerate:()=>G(!0),showGenerate:!!yt&&!ke,disabled:ke}),c.jsx(S6,{onValidate:async()=>{Ce(!0),await Ke()},isValidating:kt,validationResult:Be,fallbackResult:et,error:pe,showFallback:ce,disabled:ke}),F.expression&&c.jsx("p",{className:"text-xs text-red-500",children:F.expression})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx(ae,{children:"Inputs"}),c.jsx(w6,{label:"A",input:S,availableFields:Ge,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:Se=>{const lt=K2(Se,(S==null?void 0:S.aggregate)||uh(Se));N(rh(Se,lt))},onAggregateChange:Se=>Oy("A",Se),onRemove:()=>N(null),onActivate:()=>B("A"),allowMedian:g,disabled:ke}),F.inputA&&c.jsx("p",{className:"text-xs text-red-500",children:F.inputA}),w!=="scale"&&c.jsxs(c.Fragment,{children:[c.jsx(w6,{label:"B",input:E,availableFields:Ge,excludeFieldIds:r?[r.id]:void 0,onFieldSelect:Se=>{const lt=K2(Se,(E==null?void 0:E.aggregate)||uh(Se));_(rh(Se,lt))},onAggregateChange:Se=>Oy("B",Se),onRemove:()=>_(null),onActivate:()=>B("B"),allowMedian:g,disabled:ke}),F.inputB&&c.jsx("p",{className:"text-xs text-red-500",children:F.inputB})]}),w==="scale"&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{htmlFor:"constantFactor",children:"Multiplication Factor"}),c.jsx(mn,{id:"constantFactor",type:"number",step:"any",value:Number.isNaN(k)?"":k,onChange:Se=>M(Se.target.value===""?Number.NaN:Number(Se.target.value)),className:F.constant?"border-red-500":"",placeholder:"e.g., 0.15",disabled:ke}),F.constant&&c.jsx("p",{className:"text-xs text-red-500",children:F.constant})]}),c.jsx("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm font-mono",children:sj||"Select inputs to preview formula"}),F.inputs&&c.jsxs(kI,{variant:"destructive",children:[c.jsx(Yl,{className:"h-4 w-4"}),c.jsx(EI,{children:F.inputs})]})]})]}),b==="dimension"&&c.jsxs("div",{className:"space-y-4",children:[c.jsx(C6,{ref:ge,value:T,onChange:Se=>{P(Se),Ce(!1)},onGenerate:()=>G(!0),showGenerate:!!yt&&!ke,disabled:ke}),c.jsx(S6,{onValidate:async()=>{Ce(!0),await Ke()},isValidating:kt,validationResult:Be,fallbackResult:et,error:pe,showFallback:ce,disabled:ke}),F.expression&&c.jsx("p",{className:"text-xs text-red-500",children:F.expression}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ae,{children:"Output Type"}),c.jsxs(ot,{value:_e,onValueChange:Se=>I(Se),disabled:ke,children:[c.jsx(nt,{className:"h-9 w-full",children:c.jsx(at,{placeholder:"Select output type"})}),c.jsx(rt,{children:N6.map(Se=>c.jsx(ve,{value:Se.value,children:Se.label},Se.value))})]}),re&&!O&&c.jsxs("p",{className:"text-xs text-muted-foreground",children:["Suggested type: ",re]})]})]}),be&&(De||qe)&&c.jsxs("div",{className:"space-y-3",children:[c.jsx(cQe,{scope:$,onChange:V,showDashboardScope:De,showDomainScope:qe,error:F.scope,disabled:ke}),$==="domain"&&c.jsx(uQe,{description:W,tags:R,onDescriptionChange:L,onTagsChange:z,descriptionError:F.description,disabled:ke})]})]})]}),c.jsxs(os,{children:[c.jsx(se,{variant:"outline",onClick:Kr,children:"Cancel"}),c.jsxs(se,{onClick:rj,disabled:le||ke,children:[r?"Update":"Create"," ",b==="metric"?"Metric":"Dimension"]})]})]})]}),c.jsx(fQe,{open:U,onOpenChange:G,availableFields:Ge,fieldType:b,onExpressionGenerated:async Se=>{P(Se),Ce(!1),Re()},endpoint:yt,dialect:p==null?void 0:p.dialect}),c.jsx(Um,{open:K,onOpenChange:te,children:c.jsxs(Sf,{children:[c.jsxs(jf,{children:[c.jsx(kf,{children:"Name Conflict"}),c.jsxs(Ef,{children:['A domain metric named "',y.trim(),'" already exists. Your local version will override it in this'," ",Z==="dashboard"?"dashboard":"card",". Continue?"]})]}),c.jsxs(Nf,{children:[c.jsx(Tf,{onClick:()=>{Q(null)},children:"Choose Different Name"}),c.jsx(_f,{onClick:async()=>{if(Z){te(!1),de(!0);try{await Fy(Z)}finally{de(!1),Q(null)}}},children:"Continue"})]})]})})]})}function gte({domainId:e}){const{authToken:t,tokenProps:n}=Xe(),[r,s]=C.useState(!1),[o,i]=C.useState(null),a=C.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-metrics`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),l=C.useMemo(()=>{var m;if(!e)return null;const f=(m=n==null?void 0:n.apiServiceUrl)==null?void 0:m.replace(/\/$/,""),h=`/v1/domains/${e}/calculated-dimensions`;return f?`${f}${h}`:h},[e,n==null?void 0:n.apiServiceUrl]),u=C.useCallback(async f=>{if(!a){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await eo(a,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[a,t==null?void 0:t.accessToken]),d=C.useCallback(async f=>{if(!l){const h="Domain promotion is not available";throw i(h),new Error(h)}if(!(t!=null&&t.accessToken)){const h="Missing authentication token";throw i(h),new Error(h)}s(!0),i(null);try{return await eo(l,t.accessToken,f)}catch(h){const m=(h==null?void 0:h.error)||(h==null?void 0:h.message)||"Failed to save to domain";throw i(m),new Error(m)}finally{s(!1)}},[l,t==null?void 0:t.accessToken]);return{promoteMetric:u,promoteDimension:d,isPromoting:r,error:o}}const bte=C.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Ke,kt,pe,Re;const[s,o]=C.useState(""),[i,a]=C.useState("all"),[l,u]=C.useState(!1),[d,f]=C.useState(null),[h,m]=C.useState("card"),[p,g]=C.useState("metric");Ae(re=>re.isDevMode);const b=Ae(re=>re.card.dataSource),x=Ae(re=>re.card.config),y=Ae(re=>re.card),v=Ae(re=>re.frame),w=Ae(re=>re.actions.updateCardConfig),j=Ae(re=>re.actions.updateFrame),{userContext:S}=Ps(),{autoJoinMetadata:N}=Ha(y),{columns:E,rawColumnGroups:_,scopedFields:k,dashboardCalculatedFields:M,cardCalculatedFields:T,isLoading:P,error:O,refetch:I}=PA(),$=(b==null?void 0:b.mode)==="semanticDomain"?b.semanticDomainId:void 0,{data:V}=OA($),{promoteMetric:W,promoteDimension:L}=gte({domainId:$}),R=C.useMemo(()=>[...(x==null?void 0:x.groupByColumns)||[],...(x==null?void 0:x.metricColumns)||[],...(x==null?void 0:x.detailColumns)||[]],[x==null?void 0:x.groupByColumns,x==null?void 0:x.metricColumns,x==null?void 0:x.detailColumns]);(kt=(Ke=x==null?void 0:x.joinPlan)==null?void 0:Ke.baseEntity)==null||kt.name,(Re=(pe=N==null?void 0:N.resolvedJoinPlan)==null?void 0:pe.baseEntity)==null||Re.name,Qee();const z=t==="editor",F=(S==null?void 0:S.type)==="organization",A=z?k:E,H=_,B=s.toLowerCase(),Y=(x==null?void 0:x.metricColumns)||[],q=(x==null?void 0:x.groupByColumns)||[],U=C.useCallback(async re=>{await W(re),I()},[W,I]),G=C.useCallback(async re=>{await L(re),I()},[L,I]),Z=re=>re.name.toLowerCase().includes(B)||re.dataType.toLowerCase().includes(B)||re.label&&re.label.toLowerCase().includes(B)||re.qualifiedEntityName&&re.qualifiedEntityName.toLowerCase().includes(B),Q=A.filter(Z),K=re=>{if(re.role==="metric"&&sc(re)||re.role==="groupby"&&re.expression)return"calculated";if(re.dataType==="number"||re.dataType==="integer"||re.dataType==="float"||re.dataType==="decimal"||re.dataType==="currency")return"metrics";const _e=yr(re.dataType);return["date","string","boolean"].includes(_e)?"dimensions":_e==="number"?"metrics":"dimensions"},te=re=>{const _e=re.filter(Z);return i==="all"?_e:_e.filter(We=>K(We)===i)},le=i==="all"?Q:Q.filter(re=>K(re)===i),de=z?[...M,...T]:[],ce=z?te(de):[],ge=te(E).reduce((re,_e)=>{const We=_e.qualifiedEntityName||"Other Fields";return re[We]||(re[We]={label:cb(_e.entityName),fields:[]}),re[We].fields.push(_e),re},{}),he=re=>re.id||`${re.entityName}-${re.qualifiedEntityName}-${re.name}-${re.role||"field"}`,me=C.useMemo(()=>{const re=new Map;return(z?k:E).forEach(We=>{re.set(he(We),ED(We,{joinabilityMap:(V==null?void 0:V.joinabilityMap)||null,selectedFields:R,cardConfig:x,autoJoinMetadata:N}))}),re},[z,k,E,V==null?void 0:V.joinabilityMap,R,x,N]),oe=z?[{key:"scope-calculated",label:"Calculated Fields",fields:ce}].filter(re=>re.fields.length>0):[],fe=[...oe.map(re=>re.key),...Object.keys(ge)],Me=Q.filter(re=>K(re)==="dimensions").length,ke=Q.filter(re=>K(re)==="metrics").length,ie=Q.filter(re=>K(re)==="calculated").length,xe=Q.length>0&&t!=="inline-filter",Oe=t==="inline-filter"?"w-full":"w-[290px]";if(P)return c.jsx("div",{className:X("flex h-full flex-col items-center justify-center py-8",Oe),children:c.jsx(fu,{size:"md",color:"muted","aria-label":"Loading data"})});if(O)return c.jsxs("div",{className:X("flex h-full flex-col items-center justify-center py-8",Oe),children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:O.message||"Failed to load column data"})]});if(!b||!b.selectedEntities||b.selectedEntities.length===0)return c.jsxs("div",{className:X("flex flex-col items-center justify-center py-8 text-center",Oe),children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-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 be=t==="inline-filter"?"px-3 pb-3":"px-6 pb-6",De=t==="inline-filter"?"overflow-hidden":"",qe=re=>re!=null&&re.startsWith("card-source-")?re.replace("card-source-",""):re,He=(re,_e,We)=>{const it=qe(re.id),zt=qe(_e.id);return it&&zt&&it===zt?!0:!it||!zt||We!=null&&We.allowNameFallback?re.name===_e.name&&re.role===_e.role:!1},Fe=(re,_e,We)=>re.findIndex(it=>He(it,_e,We)),yt=re=>{if(!v)return re;const _e=v.calculatedFields||[],We=Fe(_e,re),it=We>=0&&_e[We].id!==re.id?{...re,id:_e[We].id}:re,zt=We>=0?_e.map((un,Dn)=>Dn===We?it:un):[..._e,it];return j({calculatedFields:zt}),it},je=(re,_e,We,it)=>{var un;const zt=Fe(re,We||_e,it);if(zt>=0){const Dn=(un=re[zt])==null?void 0:un.id,Kr=Dn&&Dn!==_e.id?{..._e,id:Dn}:_e;return re.map((Hr,zs)=>zs===zt?Kr:Hr)}return[...re,_e]},dt=re=>{if(re.role==="metric")return Y.find(_e=>He(_e,re));if(re.role==="groupby")return q.find(_e=>He(_e,re))},Ct=re=>{var _e;return(_e=v==null?void 0:v.calculatedFields)==null?void 0:_e.find(We=>He(We,re))},Ye=re=>{if(re.role==="metric"){w(y.id,{metricColumns:Y.filter(_e=>!He(_e,re,{allowNameFallback:re.fieldScope==="dashboard"}))});return}re.role==="groupby"&&w(y.id,{groupByColumns:q.filter(_e=>!He(_e,re,{allowNameFallback:re.fieldScope==="dashboard"}))})},Yt=re=>{if(!v)return;const _e=(v.calculatedFields||[]).filter(We=>!He(We,re));j({calculatedFields:_e})},Ge=re=>{if(!F)return;if(re.fieldScope==="domain"){f(re),m("domain"),g(re.role==="metric"?"metric":"dimension"),u(!0);return}if(re.fieldScope==="dashboard"){const We=Ct(re);if(!We)return;f(We),m("dashboard"),g(We.role==="metric"?"metric":"dimension"),u(!0);return}const _e=dt(re);_e&&(f(_e),m("card"),g(_e.role==="metric"?"metric":"dimension"),u(!0))},et=re=>{if(F&&re.fieldScope!=="domain"){if(re.fieldScope==="dashboard"){Yt(re),Ye(re);return}Ye(re)}},Be=re=>{if(!F)return null;const _e=re.fieldScope==="domain";return c.jsxs(wf,{children:[c.jsx(Cf,{asChild:!0,children:c.jsx(se,{variant:"ghost",size:"icon",className:"h-6 w-6","aria-label":"Calculated field actions",children:c.jsx(f8,{className:"h-4 w-4"})})}),c.jsxs(yu,{align:"end",className:"w-40",children:[c.jsx(po,{onClick:()=>Ge(re),children:"Edit"}),c.jsx(po,{disabled:_e,onClick:()=>et(re),children:"Delete"})]})]})};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:X("mt-2 flex h-full w-full grow flex-col gap-2",be,De),children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[A.length>0&&c.jsxs("div",{className:"relative",children:[c.jsx(Ko,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(jn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:s,onChange:re=>o(re.target.value)}),s&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>o(""),type:"button",children:c.jsx(St,{className:"size-3.5"})})]}),xe&&c.jsx(Os,{defaultValue:"all",value:i,onValueChange:re=>a(re),className:"mb-4",children:c.jsxs(ys,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(nn,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:Q.length})]}),c.jsxs(nn,{value:"dimensions",className:"text-xs",children:[c.jsx(U1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:Me})]}),c.jsxs(nn,{value:"metrics",className:"text-xs",children:[c.jsx(Am,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:ke})]}),c.jsxs(nn,{value:"calculated",className:"text-xs",children:[c.jsx(OT,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:ie})]})]})}),t==="editor"&&i==="calculated"&&F&&c.jsx("div",{className:"flex items-center justify-end gap-2",children:c.jsxs(se,{size:"sm",variant:"outline",className:"w-full",onClick:()=>{f(null),m("card"),g("dimension"),u(!0)},children:[c.jsx(Tr,{className:"mr-2 h-3.5 w-3.5"}),"Add calculated field"]})})]}),c.jsxs(tl,{className:"min-h-0 flex-1",children:[c.jsxs(BA,{type:"multiple",defaultValue:fe,className:"space-y-2",children:[oe.map(re=>c.jsxs(rx,{value:re.key,className:"border-none",children:[c.jsx(sx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:re.label}),c.jsx(Ve,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:re.fields.length})]})}),c.jsx(ox,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:re.fields.map(_e=>{const We=me.get(he(_e)),it=t==="editor"&&i==="calculated";return c.jsx(y6,{field:_e,context:t,fieldState:We,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0,actions:it?Be(_e):void 0},_e.id)})})})]},re.key)),Object.entries(ge).map(([re,_e])=>{const We=H.find(zt=>zt.entityName===re)||{entityName:re,label:_e.label},it=re===Qh?"Domain Calculated Fields":We.label||We.entityName;return c.jsxs(rx,{value:re,className:"border-none",children:[c.jsx(sx,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:it,className:"flex items-center gap-2",children:[c.jsx("span",{className:"max-w-[190px] truncate text-ellipsis whitespace-nowrap text-sm font-medium text-primary",children:it}),c.jsx(Ve,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:_e.fields.length})]})}),c.jsx(ox,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:_e.fields.map(zt=>{const un=me.get(he(zt));return c.jsx(y6,{field:zt,context:t,fieldState:un,onFieldSelect:n,inlineFilters:t==="inline-filter"?r:void 0},zt.id)})})})]},re)})]}),A.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.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"})]}),A.length>0&&le.length===0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(bi,{orientation:"horizontal"}),c.jsx(bi,{orientation:"vertical"})]})]}),c.jsx(pte,{open:l,onOpenChange:re=>{u(re),re||(f(null),m("card"))},availableFields:k,existingField:d??void 0,existingFieldScope:h,initialFieldType:p,onSave:re=>{if(re.role==="metric"){if(d&&h==="card"){w(y.id,{metricColumns:je(Y,re,d)});return}w(y.id,{metricColumns:je(Y,re)});return}if(d&&h==="card"){w(y.id,{groupByColumns:je(q,re,d)});return}w(y.id,{groupByColumns:je(q,re)})},onSaveToDashboard:re=>{const _e=!!(d&&h==="dashboard"),We=_e?d:void 0;if(re.role==="metric"){const zt=yt(re);w(y.id,{metricColumns:je(Y,zt,We,{allowNameFallback:_e})});return}const it=yt(re);w(y.id,{groupByColumns:je(q,it,We,{allowNameFallback:_e})})},cardId:y.id,onPromoteMetricToDomain:$?U:void 0,onPromoteDimensionToDomain:$?G:void 0,domainId:$})]})}),xte=C.memo(function({context:t="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(bte,{context:t})," "]})});function yte(){const e=Ae(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=cr();C.useEffect(()=>{var m;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=FA(e),d=(m=e.selectedEntities)==null?void 0:m[0],h=(d==null?void 0:d.type)==="model"&&"id"in d?d.id:"";t(u||""),n(l||""),r(a||""),s(i||""),o(h)},[e,t,n,r,s,o])}function MQe(){yte();const e=J(l=>l.selectedSheetId),t=J(l=>l.selectedFrameId),n=J(l=>l.dashboard),r=J(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Wt(),{setCard:o}=cr(),i=Ae(l=>l.card.dataSource);return C.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(m=>m.id===e),h=(d=f==null?void 0:f.frames)==null?void 0:d[0];h&&(s(h.id),l=h)}if(l){const f=l.cards.find(h=>h.id===l.activeCardId);f&&o(f)}},[r,e,t,n,s,o]),{hasEntities:!!(i!=null&&i.selectedEntities&&i.selectedEntities.length>0)}}function DQe(){const e=J(o=>o.dashboard.filterLayout),{setFilterLayout:t}=Wt(),n=(e==null?void 0:e.displayMode)||"canvas",r=(e==null?void 0:e.toolbarWrap)??!1,s=(e==null?void 0:e.showDownloadButton)??!1;return c.jsxs(ms,{children:[c.jsx(ps,{asChild:!0,children:c.jsx(se,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0","aria-label":"Filter display settings",children:c.jsx(Ll,{className:"h-4 w-4"})})}),c.jsx(gs,{className:"w-[280px]",align:"end",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{children:[c.jsx("h4",{className:"mb-3 text-sm font-medium",children:"Filter Display"}),c.jsxs(Qs,{value:n,onValueChange:o=>t({displayMode:o}),className:"space-y-2",children:[c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(bn,{value:"canvas",id:"canvas",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(ae,{htmlFor:"canvas",className:"cursor-pointer font-normal",children:"Canvas Cards"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Filters as draggable, resizable cards on the dashboard"})]})]}),c.jsxs("div",{className:"flex items-start space-x-3",children:[c.jsx(bn,{value:"toolbar",id:"toolbar",className:"mt-0.5"}),c.jsxs("div",{className:"grid gap-0.5",children:[c.jsx(ae,{htmlFor:"toolbar",className:"cursor-pointer font-normal",children:"Toolbar"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Compact horizontal toolbar below dashboard controls"})]})]})]})]}),n==="toolbar"&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center space-x-2 border-t pt-4",children:[c.jsx(cn,{id:"wrap",checked:r,onCheckedChange:o=>t({toolbarWrap:o===!0})}),c.jsx(ae,{htmlFor:"wrap",className:"cursor-pointer text-sm font-normal",children:"Wrap filters to multiple lines"})]}),c.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[c.jsx(cn,{id:"download",checked:s,onCheckedChange:o=>t({showDownloadButton:o===!0})}),c.jsx(ae,{htmlFor:"download",className:"cursor-pointer text-sm font-normal",children:"Show download button"})]})]}),c.jsx("p",{className:"border-t pt-3 text-xs text-muted-foreground",children:"Individual filters can override this setting in their configuration."})]})})]})}function IQe(){const e=J(n=>n.actions.setShowFilters),{hasEntities:t}=MQe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col overflow-hidden border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(ae,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(DQe,{}),c.jsx(se,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(eX,{})})]})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx($l,{className:"mb-4 h-12 w-12 text-muted-foreground/50"}),c.jsx("h3",{className:"mb-2 text-sm font-medium text-foreground",children:"No fields configured"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Please configure a data source for this card to enable filtering"})]}),t&&c.jsx("div",{className:"flex grow overflow-y-auto",children:c.jsx(Ny,{collisionDetection:Cy,children:c.jsx(ky,{items:[],strategy:WR,children:c.jsx(xte,{context:"filter"})})})})]})}function RQe(){const e=J(r=>r.dashboard.filters),t=J(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:X("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=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx($R,{filter:r}),c.jsx(Sp,{filter:r})]},r.id))}):null}function AQe(){const e=J(r=>r.showFilters),t=J(r=>r.isVisualEditing),n=J(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:X("",{"max-h-0 overflow-hidden":t,"flex grow overflow-hidden":!t}),children:[c.jsxs("section",{className:"flex grow flex-col overflow-y-auto",children:[n&&c.jsx(RQe,{}),c.jsx(Wee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(IQe,{})})]})}const PQe=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-DZ3RdkPp.js"))),OQe=C.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-DyvG8L5y.js"))),FQe=C.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-CBLwtP5m.js"))),$Qe=C.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-DNffk7G6.js")).then(e=>({default:e.ResourceManagementPanel})));function LQe({showControls:e=!1,showFooter:t=!0,...n}){const r=J(l=>l.isDashboardPanelOpen),s=J(l=>l.isVisualEditing),o=J(l=>l.showDashboardJSON),i=J(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(rl,{FallbackComponent:gS,children:c.jsxs(PT,{dashboardProps:n,children:[c.jsx(tde,{}),c.jsx(AA,{componentType:"surfboard",componentId:n.id}),c.jsx(RA,{children:c.jsxs(qee,{preferences:a,children:[o&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(FQe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(PQe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(C.Suspense,{fallback:null,children:c.jsx($Qe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(JD,{...n,type:"dashboard",children:[s&&c.jsx(C.Suspense,{fallback:null,children:c.jsx(OQe,{})}),c.jsx(AQe,{})]})})]})]})]})})]})})}var zQe=Object.defineProperty,BQe=(e,t,n)=>t in e?zQe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,fv=(e,t,n)=>BQe(e,typeof t!="symbol"?t+"":t,n);const VQe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},HQe={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}},UQe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function WQe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function vte(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const qQe={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=vte(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},YQe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},GQe={stringify:e=>e,parse:e=>e},X2={string:GQe,number:YQe,boolean:VQe,function:HQe,method:qQe,json:UQe},ng=Symbol.for("r2wc.render"),hv=Symbol.for("r2wc.connected"),Ku=Symbol.for("r2wc.context"),To=Symbol.for("r2wc.props");function KQe(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),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const p=WQe(m);d[m]=p,f[p]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),fv(this,o,!0),fv(this,s),fv(this,r,{}),fv(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[To].container=this.container;for(const p of i){const g=d[p],b=this.getAttribute(g),x=l[p],y=x?X2[x]:null;if(x==="method"){const v=vte(g);Object.defineProperty(this[To].container,v,{enumerable:!0,configurable:!0,get(){return this[To][v]},set(w){this[To][v]=w,this[ng]()}}),this[To][p]=y.parse(b,g,this)}y!=null&&y.parse&&b&&(this[To][p]=y.parse(b,g,this))}for(const p of a)this[To][p]=g=>{const b=p.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[p]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[hv]=!0,this[ng]()}disconnectedCallback(){this[hv]=!1,this[Ku]&&n.unmount(this[Ku]),delete this[Ku]}attributeChangedCallback(p,g,b){const x=f[p],y=l[x],v=y?X2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[To][x]=v.parse(b,p,this),this[ng]())}[(o=hv,s=Ku,r=To,ng)](){this[hv]&&(this[Ku]?n.update(this[Ku],this[To]):this[Ku]=n.mount(this.container,e,this[To]))}}for(const m of i){const p=d[m],g=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[To][m]},set(b){this[To][m]=b;const x=g?X2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,p,this);this.getAttribute(p)!==y&&this.setAttribute(p,y)}else this[ng]()}})}return h}function ZQe(e,t,n){const r=vne.createRoot(e),s=C.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function XQe({root:e,ReactComponent:t},n){const r=C.createElement(t,n);e.render(r)}function QQe({root:e}){e.unmount()}function JQe(e,t={}){return KQe(e,t,{mount:ZQe,update:XQe,unmount:QQe})}const eJe={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",currentTheme:"string",customCards:"json",customStyle:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},tJe=JQe(Yee,{props:eJe});function k6(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function nJe(e){if(Array.isArray(e))return e}function rJe(e,t,n){return(t=uJe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function sJe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,s,o,i,a=[],l=!0,u=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==t);l=!0);}catch(d){u=!0,s=d}finally{try{if(!l&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(u)throw s}}return a}}function oJe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1078
1078
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function E6(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function _6(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?E6(Object(n),!0).forEach(function(r){rJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):E6(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function iJe(e,t){if(e==null)return{};var n,r,s=aJe(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function aJe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function lJe(e,t){return nJe(e)||sJe(e,t)||dJe(e,t)||oJe()}function cJe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function uJe(e){var t=cJe(e,"string");return typeof t=="symbol"?t:t+""}function dJe(e,t){if(e){if(typeof e=="string")return k6(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?k6(e,t):void 0}}function fJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function T6(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function M6(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?T6(Object(n),!0).forEach(function(r){fJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):T6(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function hJe(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(s,o){return o(s)},r)}}function Tg(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function T1(e){return{}.toString.call(e).includes("Object")}function mJe(e){return!Object.keys(e).length}function ax(e){return typeof e=="function"}function pJe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function gJe(e,t){return T1(t)||eu("changeType"),Object.keys(t).some(function(n){return!pJe(e,n)})&&eu("changeField"),t}function bJe(e){ax(e)||eu("selectorType")}function xJe(e){ax(e)||T1(e)||eu("handlerType"),T1(e)&&Object.values(e).some(function(t){return!ax(t)})&&eu("handlersType")}function yJe(e){e||eu("initialIsRequired"),T1(e)||eu("initialType"),mJe(e)&&eu("initialContent")}function vJe(e,t){throw new Error(e[t]||e.default)}var wJe={initialIsRequired:"initial state is required",initialType:"initial state should be an object",initialContent:"initial state shouldn't be an empty object",handlerType:"handler should be an object or a function",handlersType:"all handlers should be a functions",selectorType:"selector should be a function",changeType:"provided value of changes should be an object",changeField:'it seams you want to change a field in the state which is not specified in the "initial" state',default:"an unknown error accured in `state-local` package"},eu=Tg(vJe)(wJe),mv={changes:gJe,selector:bJe,handler:xJe,initial:yJe};function CJe(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};mv.initial(e),mv.handler(t);var n={current:e},r=Tg(NJe)(n,t),s=Tg(jJe)(n),o=Tg(mv.changes)(e),i=Tg(SJe)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return mv.selector(u),u(n.current)}function l(u){hJe(r,s,o,i)(u)}return[a,l]}function SJe(e,t){return ax(t)?t(e.current):t}function jJe(e,t){return e.current=M6(M6({},e.current),t),t}function NJe(e,t,n){return ax(t)?t(e.current):Object.keys(n).forEach(function(r){var s;return(s=t[r])===null||s===void 0?void 0:s.call(t,e.current[r])}),n}var kJe={create:CJe},EJe={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs"}};function _Je(e){return function t(){for(var n=this,r=arguments.length,s=new Array(r),o=0;o<r;o++)s[o]=arguments[o];return s.length>=e.length?e.apply(this,s):function(){for(var i=arguments.length,a=new Array(i),l=0;l<i;l++)a[l]=arguments[l];return t.apply(n,[].concat(s,a))}}}function TJe(e){return{}.toString.call(e).includes("Object")}function MJe(e){return e||D6("configIsRequired"),TJe(e)||D6("configType"),e.urls?(DJe(),{paths:{vs:e.urls.monacoBase}}):e}function DJe(){console.warn(wte.deprecation)}function IJe(e,t){throw new Error(e[t]||e.default)}var wte={configIsRequired:"the configuration object is required",configType:"the configuration object should be an object",default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
|
|
1079
1079
|
You are using deprecated way of configuration.
|
|
1080
1080
|
|