react-semaphor 0.1.120 → 0.1.121
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/{dashboard-controls-B5XFI-ju.js → dashboard-controls-CyhTMpZ2.js} +3 -3
- package/dist/chunks/{dashboard-controls-DPZpVj3x.js → dashboard-controls-CzcAbxpr.js} +1 -1
- package/dist/chunks/{dashboard-json-B-mczKaU.js → dashboard-json-BQPFtG3z.js} +1 -1
- package/dist/chunks/{dashboard-json-CrCyQFFX.js → dashboard-json-BcB9WzEx.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-C4Y8Nrrb.js → edit-dashboard-visual-CLdMn0FN.js} +3 -3
- package/dist/chunks/{edit-dashboard-visual-DcHh-xOS.js → edit-dashboard-visual-D6KBQgRc.js} +1 -1
- package/dist/chunks/{editor-action-buttons-DPz-ne1B.js → editor-action-buttons-CEzZTeqn.js} +2 -2
- package/dist/chunks/{editor-action-buttons-Dz6D47bO.js → editor-action-buttons-D8lG5LwM.js} +1 -1
- package/dist/chunks/{index-D1TkQNmD.js → index-CJrseB0V.js} +2 -2
- package/dist/chunks/{index-BPICAMRJ.js → index-Cyic0UlN.js} +5 -5
- package/dist/chunks/{resource-management-panel-CNgGS6ct.js → resource-management-panel-BNDpfKQl.js} +1 -1
- package/dist/chunks/{resource-management-panel-CCv1oyai.js → resource-management-panel-DDLB-UWe.js} +2 -2
- package/dist/chunks/{schedule-dashboard-D7lKgd4M.js → schedule-dashboard-BEV7hj7t.js} +3 -3
- package/dist/chunks/{schedule-dashboard-BuBTC1B2.js → schedule-dashboard-CqFcuP5E.js} +1 -1
- package/dist/chunks/{use-visual-utils-BTHTcuQs.js → use-visual-utils-BzfETcB4.js} +1 -1
- package/dist/chunks/{use-visual-utils-BAxIkIVN.js → use-visual-utils-GI2MN0MK.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 +4 -4
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -760,7 +760,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/alert-
|
|
|
760
760
|
*/class obe{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=fV.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 Ra=new obe;const dO="transparent",ibe={boolean(e,t,n){return n>.5?t:e},color(e,t,n){const r=tO(e||dO),s=r.valid&&tO(t||dO);return s&&s.valid?s.mix(r,n).hexString():t},number(e,t,n){return e+(t-e)*n}};let abe=class{constructor(t,n,r,s){const o=n[r];s=Rn([t.to,s,o,t.from]);const i=Rn([t.from,o,s]);this._active=!0,this._fn=t.fn||ibe[t.type||typeof i],this._easing=Jm[t.easing]||Jm.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=Rn([t.to,n,s,t.from]),this._from=Rn([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 DV{constructor(t,n){this._chart=t,this._properties=new Map,this.configure(n)}configure(t){if(!_t(t))return;const n=Object.keys(Pn.animation),r=this._properties;Object.getOwnPropertyNames(t).forEach(s=>{const o=t[s];if(!_t(o))return;const i={};for(const a of n)i[a]=o[a];(yn(o.properties)&&o.properties||[s]).forEach(a=>{(a===s||!r.has(a))&&r.set(a,i)})})}_animateOptions(t,n){const r=n.options,s=cbe(t,r);if(!s)return[];const o=this._createAnimations(s,r);return r.$shared&&lbe(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 abe(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 Ra.add(this._chart,r),!0}}function lbe(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 cbe(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 fO(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 ube(e,t,n){if(n===!1)return!1;const r=fO(e,n),s=fO(t,n);return{top:s.end,right:r.end,bottom:s.start,left:r.start}}function dbe(e){let t,n,r,s;return _t(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 MV(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 hO(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],tr(u)&&(o||t===0||oa(t)===oa(u))&&(t+=u)}return!d&&!r.all?0:t}function fbe(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 tN(e,t){const n=e&&e.options.stacked;return n||n===void 0&&t.stack!==void 0}function hbe(e,t,n){return`${e.id}.${t.id}.${n.stack||n.type}`}function pbe(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 mbe(e,t,n){const r=e[t]||(e[t]={});return r[n]||(r[n]={})}function pO(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 mO(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=hbe(o,i,r),f=t.length;let h;for(let p=0;p<f;++p){const m=t[p],{[l]:g,[u]:b}=m,x=m._stacks||(m._stacks={});h=x[u]=mbe(s,d,g),h[a]=b,h._top=pO(h,i,!0,r.type),h._bottom=pO(h,i,!1,r.type);const y=h._visualValues||(h._visualValues={});y[a]=b}}function nN(e,t){const n=e.scales;return Object.keys(n).filter(r=>n[r].axis===t).shift()}function gbe(e,t){return Hc(e,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function bbe(e,t,n){return Hc(e,{active:!1,dataIndex:t,parsed:void 0,raw:void 0,element:n,index:t,mode:"default",type:"data"})}function lm(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 rN=e=>e==="reset"||e==="none",gO=(e,t)=>t?e:Object.assign({},e),xbe=(e,t,n)=>e&&!t.hidden&&t._stacked&&{keys:MV(n,!0),values:null};class Gs{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=tN(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&&lm(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,n=this._cachedMeta,r=this.getDataset(),s=(f,h,p,m)=>f==="x"?h:f==="r"?m:p,o=n.xAxisID=ct(r.xAxisID,nN(t,"x")),i=n.yAxisID=ct(r.yAxisID,nN(t,"y")),a=n.rAxisID=ct(r.rAxisID,nN(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&&QP(this._data,this),t._stacked&&lm(t)}_dataCheck(){const t=this.getDataset(),n=t.data||(t.data=[]),r=this._data;if(_t(n)){const s=this._cachedMeta;this._data=fbe(n,s)}else if(r!==n){if(r){QP(r,this);const s=this._cachedMeta;lm(s),s._parsed=[]}n&&Object.isExtensible(n)&&rge(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=tN(n.vScale,n),n.stack!==r.stack&&(s=!0,lm(n),n.stack=r.stack),this._resyncElements(t),(s||o!==n._stacked)&&(mO(this,n._parsed),n._stacked=tN(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{yn(s[t])?h=this.parseArrayData(r,s,t,n):_t(s[t])?h=this.parseObjectData(r,s,t,n):h=this.parsePrimitiveData(r,s,t,n);const p=()=>f[a]===null||u&&f[a]<u[a];for(d=0;d<n;++d)r._parsed[d+t]=f=h[d],l&&(p()&&(l=!1),u=f);r._sorted=l}i&&mO(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,p,m;for(h=0,p=s;h<p;++h)m=h+r,f[h]={[a]:d||o.parse(u[m],m),[l]:i.parse(n[m],m)};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,p;for(d=0,f=s;d<f;++d)h=d+r,p=n[h],u[d]={x:o.parse(Sc(p,a),h),y:i.parse(Sc(p,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:MV(s,!0),values:n._stacks[t.axis]._visualValues};return hO(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=hO(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=xbe(n,r,this.chart),u={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:d,max:f}=pbe(a);let h,p;function m(){p=s[h];const g=p[a.axis];return!tr(p[t.axis])||d>g||f<g}for(h=0;h<i&&!(!m()&&(this.updateRangeFromParsed(u,t,p,l),o));++h);if(o){for(h=i-1;h>=0;--h)if(!m()){this.updateRangeFromParsed(u,t,p,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],tr(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=dbe(ct(this.options.clip,ube(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=bbe(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=gbe(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&&Rh(r);if(a)return gO(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),p=Object.keys(Pn.elements[t]),m=()=>this.getContext(r,s,n),g=u.resolveNamedOptions(h,p,m,f);return g.$shared&&(g.$shared=l,o[i]=Object.freeze(gO(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 DV(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||rN(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){rN(s)?Object.assign(t,r):this._resolveAnimations(n,s).update(t,r)}updateSharedOptions(t,n,r){t&&!rN(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&&lm(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])}}Ae(Gs,"defaults",{}),Ae(Gs,"datasetElementType",null),Ae(Gs,"dataElementType",null);function ybe(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=dV(r.sort((s,o)=>s-o))}return e._cache.$bar}function vbe(e){const t=e.iScale,n=ybe(t,e.type);let r=t._length,s,o,i,a;const l=()=>{i===32767||i===-32768||(Rh(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 wbe(e,t,n,r){const s=n.barThickness;let o,i;return St(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 Sbe(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 Cbe(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 TV(e,t,n,r){return yn(e)?Cbe(e,t,n,r):t[n.axis]=n.parse(e,r),t}function bO(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(TV(h,f,o,u));return l}function sN(e){return e&&e.barStart!==void 0&&e.barEnd!==void 0}function Nbe(e,t,n){return e!==0?oa(e):(t.isHorizontal()?1:-1)*(t.min>=n?1:-1)}function jbe(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 kbe(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}=jbe(e);s==="middle"&&n&&(e.enableBorderRadius=!0,(n._top||0)===r?s=u:(n._bottom||0)===r?s=d:(o[xO(d,i,a,l)]=!0,s=u)),o[xO(s,i,a,l)]=!0,e.borderSkipped=o}function xO(e,t,n,r){return r?(e=Ebe(e,t,n),e=yO(e,n,t)):e=yO(e,t,n),e}function Ebe(e,t,n){return e===t?n:e===n?t:e}function yO(e,t,n){return e==="start"?t:e==="end"?n:e}function _be(e,{inflateAmount:t},n){e.inflateAmount=t==="auto"?n===1?.33:0:t}class ed extends Gs{parsePrimitiveData(t,n,r,s){return bO(t,n,r,s)}parseArrayData(t,n,r,s){return bO(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,p,m,g;for(h=r,p=r+s;h<p;++h)g=n[h],m={},m[o.axis]=o.parse(Sc(g,u),h),f.push(TV(Sc(g,d),m,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=sN(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 p=n;p<n+r;p++){const m=this.getParsed(p),g=o||St(m[a.axis])?{base:l,head:l}:this._calculateBarValuePixels(p),b=this._calculateBarIndexPixels(p,d),x=(m._stacks||{})[a.axis],y={horizontal:u,base:g.base,enableBorderRadius:!x||sN(m._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(p,t[p].active?"active":s));const v=y.options||t[p].options;kbe(y,v,x,i),_be(y,v,d.ratio),this.updateElement(t[p],p,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(p=>p[r.axis]===l),h=f&&f[d.vScale.axis];if(St(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}_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||vbe(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=sN(u);let f=l[n.axis],h=0,p=r?this.applyStack(n,l,r):f,m,g;p!==f&&(h=p-f,p=f),d&&(f=u.barStart,p=u.barEnd-u.barStart,f!==0&&oa(f)!==oa(u.barEnd)&&(h=0),h+=f);const b=!St(o)&&!d?o:h;let x=n.getPixelForValue(b);if(this.chart.getDataVisibility(t)?m=n.getPixelForValue(h+p):m=x,g=m-x,Math.abs(g)<i){g=Nbe(g,n,a)*i,f===a&&(x-=g/2);const y=n.getPixelForDecimal(0),v=n.getPixelForDecimal(1),w=Math.min(y,v),S=Math.max(y,v);x=Math.max(Math.min(x,S),w),m=x+g,r&&!d&&(l._stacks[n.axis]._visualValues[s]=n.getValueForPixel(m)-n.getValueForPixel(x))}if(x===n.getPixelForValue(a)){const y=oa(g)*n.getLineWidthForValue(a)/2;x+=y,g-=y}return{size:g,base:x,head:m,center:m+g/2}}_calculateBarIndexPixels(t,n){const r=n.scale,s=this.options,o=s.skipNull,i=ct(s.maxBarThickness,1/0);let a,l;if(n.grouped){const u=o?this._getStackCount(t):n.stackCount,d=s.barThickness==="flex"?Sbe(t,n,s,u):wbe(t,n,s,u),f=this._getStackIndex(this.index,this._cachedMeta.stack,o?t:void 0);a=d.start+d.chunk*f+d.chunk/2,l=Math.min(i,d.chunk*d.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)}}Ae(ed,"id","bar"),Ae(ed,"defaults",{datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}}),Ae(ed,"overrides",{scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}});class Ty extends Gs{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=ct(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=ct(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 p=t[h],m=!o&&this.getParsed(h),g={},b=g[d]=o?i.getPixelForDecimal(.5):i.getPixelForValue(m[d]),x=g[f]=o?a.getBasePixel():a.getPixelForValue(m[f]);g.skip=isNaN(b)||isNaN(x),u&&(g.options=l||this.resolveDataElementOptions(h,p.active?"active":s),o&&(g.options.radius=0)),this.updateElement(p,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+=ct(r&&r._custom,o),s}}Ae(Ty,"id","bubble"),Ae(Ty,"defaults",{datasetElementType:!1,dataElementType:"point",animations:{numbers:{type:"number",properties:["x","y","borderWidth","radius"]}}}),Ae(Ty,"overrides",{scales:{x:{type:"linear"},y:{type:"linear"}}});function Dbe(e,t,n){let r=1,s=1,o=0,i=0;if(t<An){const a=e,l=a+t,u=Math.cos(a),d=Math.sin(a),f=Math.cos(l),h=Math.sin(l),p=(v,w,S)=>$g(v,a,l,!0)?1:Math.max(w,w*n,S,S*n),m=(v,w,S)=>$g(v,a,l,!0)?-1:Math.min(w,w*n,S,S*n),g=p(0,u,f),b=p(cr,d,h),x=m(Fn,u,f),y=m(Fn+cr,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 Iu extends Gs{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(_t(r[t])){const{key:l="value"}=this._parsing;o=u=>+Sc(r[u],l)}let i,a;for(i=t,a=t+n;i<a;++i)s._parsed[i]=o(i)}}_getRotation(){return pi(this.options.rotation-90)}_getCircumference(){return pi(this.options.circumference)}_getRotationExtents(){let t=An,n=-An;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(Vme(this.options.cutout,a),1),u=this._getRingWeight(this.index),{circumference:d,rotation:f}=this._getRotationExtents(),{ratioX:h,ratioY:p,offsetX:m,offsetY:g}=Dbe(f,d,l),b=(r.width-i)/h,x=(r.height-i)/p,y=Math.max(Math.min(b,x)/2,0),v=iV(this.options.radius,y),w=Math.max(v*l,0),S=(v-w)/this._getVisibleDatasetWeightTotal();this.offsetX=m*v,this.offsetY=g*v,s.total=this.calculateTotal(),this.outerRadius=v-S*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-S*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/An)}updateElements(t,n,r,s){const o=s==="reset",i=this.chart,a=i.chartArea,u=i.options.animation,d=(a.left+a.right)/2,f=(a.top+a.bottom)/2,h=o&&u.animateScale,p=h?0:this.innerRadius,m=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],S={x:d+this.offsetX,y:f+this.offsetY,startAngle:x,endAngle:x+v,circumference:v,outerRadius:m,innerRadius:p};b&&(S.options=g||this.resolveDataElementOptions(y,w.active?"active":s)),x+=v,this.updateElement(w,y,S,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)?An*(Math.abs(t)/n):0}getLabelAndValue(t){const n=this._cachedMeta,r=this.chart,s=r.data.labels||[],o=Kb(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(ct(this.chart.data.datasets[t].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}Ae(Iu,"id","doughnut"),Ae(Iu,"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"}),Ae(Iu,"descriptors",{_scriptable:t=>t!=="spacing",_indexable:t=>t!=="spacing"&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")}),Ae(Iu,"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()}}}});class Ry extends Gs{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}=pV(n,s,i);this._drawStart=a,this._drawCount=l,mV(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,p=a.axis,{spanGaps:m,segment:g}=this.options,b=jd(m)?m: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 S=0;S<v;++S){const C=t[S],j=x?C:{};if(S<n||S>=y){j.skip=!0;continue}const D=this.getParsed(S),k=St(D[p]),_=j[h]=i.getPixelForValue(D[h],S),M=j[p]=o||k?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,D,l):D[p],S);j.skip=isNaN(_)||isNaN(M)||k,j.stop=S>0&&Math.abs(D[h]-w[h])>b,g&&(j.parsed=D,j.raw=u.data[S]),f&&(j.options=d||this.resolveDataElementOptions(S,C.active?"active":s)),x||this.updateElement(C,S,j,s),w=D}}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()}}Ae(Ry,"id","line"),Ae(Ry,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),Ae(Ry,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});class tg extends Gs{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=Kb(n._parsed[t].r,r.options.locale);return{label:s[t]||"",value:o}}parseObjectData(t,n,r,s){return SV.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*Fn;let p=h,m;const g=360/this.countVisibleElements();for(m=0;m<n;++m)p+=this._computeAngle(m,s,g);for(m=n;m<n+r;m++){const b=t[m];let x=p,y=p+this._computeAngle(m,s,g),v=i.getDataVisibility(m)?u.getDistanceFromCenterForValue(this.getParsed(m).r):0;p=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(m,b.active?"active":s)};this.updateElement(b,m,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)?pi(this.resolveDataElementOptions(t,n).angle||r):0}}Ae(tg,"id","polarArea"),Ae(tg,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),Ae(tg,"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 gk extends Iu{}Ae(gk,"id","pie"),Ae(gk,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});class Iy extends Gs{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 SV.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,p={x:f,y:h,angle:d.angle,skip:isNaN(f)||isNaN(h),options:u};this.updateElement(l,a,p,s)}}}Ae(Iy,"id","radar"),Ae(Iy,"defaults",{datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}}),Ae(Iy,"overrides",{aspectRatio:1,scales:{r:{type:"radialLinear"}}});class Ay extends Gs{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}=pV(n,r,s);if(this._drawStart=o,this._drawCount=i,mV(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),p=i.axis,m=a.axis,{spanGaps:g,segment:b}=this.options,x=jd(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 S=t[w],C=this.getParsed(w),j=y?S:{},D=St(C[m]),k=j[p]=i.getPixelForValue(C[p],w),_=j[m]=o||D?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,C,l):C[m],w);j.skip=isNaN(k)||isNaN(_)||D,j.stop=w>0&&Math.abs(C[p]-v[p])>x,b&&(j.parsed=C,j.raw=u.data[w]),h&&(j.options=f||this.resolveDataElementOptions(w,S.active?"active":s)),y||this.updateElement(S,w,j,s),v=C}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}}Ae(Ay,"id","scatter"),Ae(Ay,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),Ae(Ay,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});var Mbe=Object.freeze({__proto__:null,BarController:ed,BubbleController:Ty,DoughnutController:Iu,LineController:Ry,PieController:gk,PolarAreaController:tg,RadarController:Iy,ScatterController:Ay});function cu(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class pM{constructor(t){Ae(this,"options");this.options=t||{}}static override(t){Object.assign(pM.prototype,t)}init(){}formats(){return cu()}parse(){return cu()}format(){return cu()}add(){return cu()}diff(){return cu()}startOf(){return cu()}endOf(){return cu()}}var Tbe={_date:pM};function Rbe(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?tge:Ga;if(r){if(s._sharedOptions){const d=o[0],f=typeof d.getRange=="function"&&d.getRange(t);if(f){const h=u(o,t,n-f),p=u(o,t,n+f);return{lo:h.lo,hi:p.hi}}}}else{const d=u(o,t,n);if(l){const{vScale:f}=s._cachedMeta,{_parsed:h}=e,p=h.slice(0,d.lo+1).reverse().findIndex(g=>!St(g[f.axis]));d.lo-=Math.max(0,p);const m=h.slice(d.hi).findIndex(g=>!St(g[f.axis]));d.hi+=Math.max(0,m)}return d}}return{lo:0,hi:o.length-1}}function T1(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}=Rbe(o[a],t,i,s);for(let p=f;p<=h;++p){const m=d[p];m.skip||r(m,u,p)}}}function Ibe(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 oN(e,t,n,r,s){const o=[];return!s&&!e.isPointInArea(t)||T1(e,n,t,function(a,l,u){!s&&!Ka(a,e.chartArea,0)||a.inRange(t.x,t.y,r)&&o.push({element:a,datasetIndex:l,index:u})},!0),o}function Abe(e,t,n,r){let s=[];function o(i,a,l){const{startAngle:u,endAngle:d}=i.getProps(["startAngle","endAngle"],r),{angle:f}=cV(i,{x:t.x,y:t.y});$g(f,u,d)&&s.push({element:i,datasetIndex:a,index:l})}return T1(e,n,t,o),s}function Pbe(e,t,n,r,s,o){let i=[];const a=Ibe(n);let l=Number.POSITIVE_INFINITY;function u(d,f,h){const p=d.inRange(t.x,t.y,s);if(r&&!p)return;const m=d.getCenterPoint(s);if(!(!!o||e.isPointInArea(m))&&!p)return;const b=a(t,m);b<l?(i=[{element:d,datasetIndex:f,index:h}],l=b):b===l&&i.push({element:d,datasetIndex:f,index:h})}return T1(e,n,t,u),i}function iN(e,t,n,r,s,o){return!o&&!e.isPointInArea(t)?[]:n==="r"&&!r?Abe(e,t,n,s):Pbe(e,t,n,r,s,o)}function vO(e,t,n,r,s){const o=[],i=n==="x"?"inXRange":"inYRange";let a=!1;return T1(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 Obe={modes:{index(e,t,n,r){const s=yu(t,e),o=n.axis||"x",i=n.includeInvisible||!1,a=n.intersect?oN(e,s,o,r,i):iN(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=yu(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;let a=n.intersect?oN(e,s,o,r,i):iN(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=yu(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;return oN(e,s,o,r,i)},nearest(e,t,n,r){const s=yu(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;return iN(e,s,o,n.intersect,r,i)},x(e,t,n,r){const s=yu(t,e);return vO(e,s,"x",n.intersect,r)},y(e,t,n,r){const s=yu(t,e);return vO(e,s,"y",n.intersect,r)}}};const RV=["left","top","right","bottom"];function cm(e,t){return e.filter(n=>n.pos===t)}function wO(e,t){return e.filter(n=>RV.indexOf(n.pos)===-1&&n.box.axis===t)}function um(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 Fbe(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 $be(e){const t={};for(const n of e){const{stack:r,pos:s,stackWeight:o}=n;if(!r||!RV.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 Lbe(e,t){const n=$be(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 zbe(e){const t=Fbe(e),n=um(t.filter(u=>u.box.fullSize),!0),r=um(cm(t,"left"),!0),s=um(cm(t,"right")),o=um(cm(t,"top"),!0),i=um(cm(t,"bottom")),a=wO(t,"x"),l=wO(t,"y");return{fullSize:n,leftAndTop:r.concat(o),rightAndBottom:s.concat(l).concat(i).concat(a),chartArea:cm(t,"chartArea"),vertical:r.concat(s).concat(l),horizontal:o.concat(i).concat(a)}}function SO(e,t,n,r){return Math.max(e[n],t[n])+Math.max(e[r],t[r])}function IV(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 Bbe(e,t,n,r){const{pos:s,box:o}=n,i=e.maxPadding;if(!_t(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&&IV(i,o.getPadding());const a=Math.max(0,t.outerWidth-SO(i,e,"left","right")),l=Math.max(0,t.outerHeight-SO(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 Vbe(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 Hbe(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 Dm(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,Hbe(a.horizontal,t));const{same:f,other:h}=Bbe(t,n,a,r);u|=f&&s.length,d=d||h,l.fullSize||s.push(a)}return u&&Dm(s,t,n,r)||d}function p0(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 CO(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;Rh(u.start)&&(i=u.start),l.fullSize?p0(l,s.left,i,n.outerWidth-s.right-s.left,h):p0(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;Rh(u.start)&&(o=u.start),l.fullSize?p0(l,o,s.top,h,n.outerHeight-s.bottom-s.top):p0(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=zr(e.options.layout.padding),o=Math.max(t-s.width,0),i=Math.max(n-s.height,0),a=zbe(e.boxes),l=a.vertical,u=a.horizontal;sn(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);IV(h,zr(r));const p=Object.assign({maxPadding:h,w:o,h:i,x:s.left,y:s.top},s),m=Lbe(l.concat(u),f);Dm(a.fullSize,p,f,m),Dm(l,p,f,m),Dm(u,p,f,m)&&Dm(l,p,f,m),Vbe(p),CO(a.leftAndTop,p,f,m),p.x+=p.w,p.y+=p.h,CO(a.rightAndBottom,p,f,m),e.chartArea={left:p.left,top:p.top,right:p.left+p.w,bottom:p.top+p.h,height:p.h,width:p.w},sn(a.chartArea,g=>{const b=g.box;Object.assign(b,e.chartArea),b.update(p.w,p.h,{left:0,top:0,right:0,bottom:0})})}};class AV{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 Ube extends AV{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const Py="$chartjs",Wbe={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},NO=e=>e===null||e==="";function qbe(e,t){const n=e.style,r=e.getAttribute("height"),s=e.getAttribute("width");if(e[Py]={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",NO(s)){const o=aO(e,"width");o!==void 0&&(e.width=o)}if(NO(r))if(e.style.height==="")e.height=e.width/(t||2);else{const o=aO(e,"height");o!==void 0&&(e.height=o)}return e}const PV=Gge?{passive:!0}:!1;function Ybe(e,t,n){e&&e.addEventListener(t,n,PV)}function Gbe(e,t,n){e&&e.canvas&&e.canvas.removeEventListener(t,n,PV)}function Kbe(e,t){const n=Wbe[e.type]||e.type,{x:r,y:s}=yu(e,t);return{type:n,chart:t,native:e,x:r!==void 0?r:null,y:s!==void 0?s:null}}function _v(e,t){for(const n of e)if(n===t||n.contains(t))return!0}function Zbe(e,t,n){const r=e.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||_v(a.addedNodes,r),i=i&&!_v(a.removedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}function Xbe(e,t,n){const r=e.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||_v(a.removedNodes,r),i=i&&!_v(a.addedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}const Lg=new Map;let jO=0;function OV(){const e=window.devicePixelRatio;e!==jO&&(jO=e,Lg.forEach((t,n)=>{n.currentDevicePixelRatio!==e&&t()}))}function Qbe(e,t){Lg.size||window.addEventListener("resize",OV),Lg.set(e,t)}function Jbe(e){Lg.delete(e),Lg.size||window.removeEventListener("resize",OV)}function exe(e,t,n){const r=e.canvas,s=r&&hM(r);if(!s)return;const o=hV((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),Qbe(e,o),i}function aN(e,t,n){n&&n.disconnect(),t==="resize"&&Jbe(e)}function txe(e,t,n){const r=e.canvas,s=hV(o=>{e.ctx!==null&&n(Kbe(o,e))},e);return Ybe(r,t,s),s}class nxe extends AV{acquireContext(t,n){const r=t&&t.getContext&&t.getContext("2d");return r&&r.canvas===t?(qbe(t,n),r):null}releaseContext(t){const n=t.canvas;if(!n[Py])return!1;const r=n[Py].initial;["height","width"].forEach(o=>{const i=r[o];St(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[Py],!0}addEventListener(t,n,r){this.removeEventListener(t,n);const s=t.$proxies||(t.$proxies={}),i={attach:Zbe,detach:Xbe,resize:exe}[n]||txe;s[n]=i(t,n,r)}removeEventListener(t,n){const r=t.$proxies||(t.$proxies={}),s=r[n];if(!s)return;({attach:aN,detach:aN,resize:aN}[n]||Gbe)(t,n,s),r[n]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,n,r,s){return Yge(t,n,r,s)}isAttached(t){const n=t&&hM(t);return!!(n&&n.isConnected)}}function rxe(e){return!fM()||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas?Ube:nxe}var Sy;let Qo=(Sy=class{constructor(){Ae(this,"x");Ae(this,"y");Ae(this,"active",!1);Ae(this,"options");Ae(this,"$animations")}tooltipPosition(t){const{x:n,y:r}=this.getProps(["x","y"],t);return{x:n,y:r}}hasValue(){return jd(this.x)&&jd(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}},Ae(Sy,"defaults",{}),Ae(Sy,"defaultRoutes"),Sy);function sxe(e,t){const n=e.options.ticks,r=oxe(e),s=Math.min(n.maxTicksLimit||r,r),o=n.major.enabled?axe(t):[],i=o.length,a=o[0],l=o[i-1],u=[];if(i>s)return lxe(t,u,o,i/s),u;const d=ixe(o,t,s);if(i>0){let f,h;const p=i>1?Math.round((l-a)/(i-1)):null;for(m0(t,u,d,St(p)?0:a-p,a),f=0,h=i-1;f<h;f++)m0(t,u,d,o[f],o[f+1]);return m0(t,u,d,l,St(p)?t.length:l+p),u}return m0(t,u,d),u}function oxe(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 ixe(e,t,n){const r=cxe(e),s=t.length/n;if(!r)return Math.max(s,1);const o=Zme(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 axe(e){const t=[];let n,r;for(n=0,r=e.length;n<r;n++)e[n].major&&t.push(n);return t}function lxe(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 m0(e,t,n,r,s){const o=ct(r,0),i=Math.min(ct(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 cxe(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 uxe=e=>e==="left"?"right":e==="right"?"left":e,kO=(e,t,n)=>t==="top"||t==="left"?e[t]+n:e[t]-n,EO=(e,t)=>Math.min(t||e,e);function _O(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 dxe(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 fxe(e,t){sn(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 dm(e){return e.drawTicks?e.tickLength:0}function DO(e,t){if(!e.display)return 0;const n=_n(e.font,t),r=zr(e.padding);return(yn(e.text)?e.text.length:1)*n.lineHeight+r.height}function hxe(e,t){return Hc(e,{scale:t,type:"scale"})}function pxe(e,t,n){return Hc(e,{tick:n,index:t,type:"tick"})}function mxe(e,t,n){let r=oM(e);return(n&&t!=="right"||!n&&t==="right")&&(r=uxe(r)),r}function gxe(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,p,m;const g=i-s,b=a-o;if(e.isHorizontal()){if(p=Xr(r,o,a),_t(n)){const x=Object.keys(n)[0],y=n[x];m=d[x].getPixelForValue(y)+g-t}else n==="center"?m=(u.bottom+u.top)/2+g-t:m=kO(e,n,t);h=a-o}else{if(_t(n)){const x=Object.keys(n)[0],y=n[x];p=d[x].getPixelForValue(y)-b+t}else n==="center"?p=(u.left+u.right)/2-b+t:p=kO(e,n,t);m=Xr(r,i,s),f=n==="left"?-cr:cr}return{titleX:p,titleY:m,maxWidth:h,rotation:f}}class Uc extends Qo{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=so(t,Number.POSITIVE_INFINITY),n=so(n,Number.NEGATIVE_INFINITY),r=so(r,Number.POSITIVE_INFINITY),s=so(s,Number.NEGATIVE_INFINITY),{min:so(t,r),max:so(n,s),minDefined:tr(t),maxDefined:tr(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:so(n,so(r,n)),max:so(r,so(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(){pn(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=jge(this,o,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const l=a<this.ticks.length;this._convertTicksToLabels(l?_O(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),i.display&&(i.autoSkip||i.source==="auto")&&(this.ticks=sxe(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(){pn(this.options.afterUpdate,[this])}beforeSetDimensions(){pn(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(){pn(this.options.afterSetDimensions,[this])}_callHooks(t){this.chart.notifyPlugins(t,this.getContext()),pn(this.options[t],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){pn(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=pn(n.callback,[o.value,r,t],this)}afterTickToLabelConversion(){pn(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){pn(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const t=this.options,n=t.ticks,r=EO(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,p=Ir(this.chart.width-f,0,this.maxWidth);a=t.offset?this.maxWidth/r:p/(r-1),f+6>a&&(a=p/(r-(t.offset?.5:1)),l=this.maxHeight-dm(t.grid)-n.padding-DO(t.title,this.chart.options.font),u=Math.sqrt(f*f+h*h),i=rM(Math.min(Math.asin(Ir((d.highest.height+6)/a,-1,1)),Math.asin(Ir(l/u,-1,1))-Math.asin(Ir(h/u,-1,1)))),i=Math.max(s,Math.min(o,i))),this.labelRotation=i}afterCalculateLabelRotation(){pn(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){pn(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=DO(s,n.options.font);if(a?(t.width=this.maxWidth,t.height=dm(o)+l):(t.height=this.maxHeight,t.width=dm(o)+l),r.display&&this.ticks.length){const{first:u,last:d,widest:f,highest:h}=this._getLabelSizes(),p=r.padding*2,m=pi(this.labelRotation),g=Math.cos(m),b=Math.sin(m);if(a){const x=r.mirror?0:b*f.width+g*h.height;t.height=Math.min(this.maxHeight,t.height+x+p)}else{const x=r.mirror?0:g*f.width+b*h.height;t.width=Math.min(this.maxWidth,t.width+x+p)}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,p=0;l?u?(h=s*t.width,p=r*n.height):(h=r*t.height,p=s*n.width):o==="start"?p=n.width:o==="end"?h=t.width:o!=="inner"&&(h=t.width/2,p=n.width/2),this.paddingLeft=Math.max((h-d+i)*this.width/(this.width-d),0),this.paddingRight=Math.max((p-f+i)*this.width/(this.width-f),0)}else{let d=n.height/2,f=t.height/2;o==="start"?(d=0,f=t.height):o==="end"&&(d=n.height,f=0),this.paddingTop=d+i,this.paddingBottom=f+i}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){pn(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++)St(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=_O(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/EO(n,r));let u=0,d=0,f,h,p,m,g,b,x,y,v,w,S;for(f=0;f<n;f+=l){if(m=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,!St(m)&&!yn(m))v=jv(s,x.data,x.gc,v,m),w=y;else if(yn(m))for(h=0,p=m.length;h<p;++h)S=m[h],!St(S)&&!yn(S)&&(v=jv(s,x.data,x.gc,v,S),w+=y);i.push(v),a.push(w),u=Math.max(v,u),d=Math.max(w,d)}fxe(o,n);const C=i.indexOf(u),j=a.indexOf(d),D=k=>({width:i[k]||0,height:a[k]||0});return{first:D(0),last:D(n-1),widest:D(C),highest:D(j),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 ege(this._alignToPixels?lu(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=pxe(this.getContext(),t,r))}return this.$context||(this.$context=hxe(this.chart.getContext(),this))}_tickSize(){const t=this.options.ticks,n=pi(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=dm(o),p=[],m=a.setContext(this.getContext()),g=m.display?m.width:0,b=g/2,x=function(F){return lu(r,F,g)};let y,v,w,S,C,j,D,k,_,M,R,O;if(i==="top")y=x(this.bottom),j=this.bottom-h,k=y-b,M=x(t.top)+b,O=t.bottom;else if(i==="bottom")y=x(this.top),M=t.top,O=x(t.bottom)-b,j=y+b,k=this.top+h;else if(i==="left")y=x(this.right),C=this.right-h,D=y-b,_=x(t.left)+b,R=t.right;else if(i==="right")y=x(this.left),_=t.left,R=x(t.right)-b,C=y+b,D=this.left+h;else if(n==="x"){if(i==="center")y=x((t.top+t.bottom)/2+.5);else if(_t(i)){const F=Object.keys(i)[0],z=i[F];y=x(this.chart.scales[F].getPixelForValue(z))}M=t.top,O=t.bottom,j=y+b,k=j+h}else if(n==="y"){if(i==="center")y=x((t.left+t.right)/2);else if(_t(i)){const F=Object.keys(i)[0],z=i[F];y=x(this.chart.scales[F].getPixelForValue(z))}C=y-b,D=C-h,_=t.left,R=t.right}const T=ct(s.ticks.maxTicksLimit,f),I=Math.max(1,Math.ceil(f/T));for(v=0;v<f;v+=I){const F=this.getContext(v),z=o.setContext(F),B=a.setContext(F),$=z.lineWidth,P=z.color,V=B.dash||[],L=B.dashOffset,A=z.tickWidth,W=z.tickColor,U=z.tickBorderDash||[],Y=z.tickBorderDashOffset;w=dxe(this,v,l),w!==void 0&&(S=lu(r,w,$),u?C=D=_=R=S:j=k=M=O=S,p.push({tx1:C,ty1:j,tx2:D,ty2:k,x1:_,y1:M,x2:R,y2:O,width:$,color:P,borderDash:V,borderDashOffset:L,tickWidth:A,tickColor:W,tickBorderDash:U,tickBorderDashOffset:Y}))}return this._ticksLength=f,this._borderValue=y,p}_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=dm(r.grid),p=h+d,m=f?-d:p,g=-pi(this.labelRotation),b=[];let x,y,v,w,S,C,j,D,k,_,M,R,O="middle";if(s==="top")C=this.bottom-m,j=this._getXAxisLabelAlignment();else if(s==="bottom")C=this.top+m,j=this._getXAxisLabelAlignment();else if(s==="left"){const I=this._getYAxisLabelAlignment(h);j=I.textAlign,S=I.x}else if(s==="right"){const I=this._getYAxisLabelAlignment(h);j=I.textAlign,S=I.x}else if(n==="x"){if(s==="center")C=(t.top+t.bottom)/2+p;else if(_t(s)){const I=Object.keys(s)[0],F=s[I];C=this.chart.scales[I].getPixelForValue(F)+p}j=this._getXAxisLabelAlignment()}else if(n==="y"){if(s==="center")S=(t.left+t.right)/2-p;else if(_t(s)){const I=Object.keys(s)[0],F=s[I];S=this.chart.scales[I].getPixelForValue(F)}j=this._getYAxisLabelAlignment(h).textAlign}n==="y"&&(l==="start"?O="top":l==="end"&&(O="bottom"));const T=this._getLabelSizes();for(x=0,y=a.length;x<y;++x){v=a[x],w=v.label;const I=o.setContext(this.getContext(x));D=this.getPixelForTick(x)+o.labelOffset,k=this._resolveTickFontOptions(x),_=k.lineHeight,M=yn(w)?w.length:1;const F=M/2,z=I.color,B=I.textStrokeColor,$=I.textStrokeWidth;let P=j;i?(S=D,j==="inner"&&(x===y-1?P=this.options.reverse?"left":"right":x===0?P=this.options.reverse?"right":"left":P="center"),s==="top"?u==="near"||g!==0?R=-M*_+_/2:u==="center"?R=-T.highest.height/2-F*_+_:R=-T.highest.height+_/2:u==="near"||g!==0?R=_/2:u==="center"?R=T.highest.height/2-F*_:R=T.highest.height-M*_,f&&(R*=-1),g!==0&&!I.showLabelBackdrop&&(S+=_/2*Math.sin(g))):(C=D,R=(1-M)*_/2);let V;if(I.showLabelBackdrop){const L=zr(I.backdropPadding),A=T.heights[x],W=T.widths[x];let U=R-L.top,Y=0-L.left;switch(O){case"middle":U-=A/2;break;case"bottom":U-=A;break}switch(j){case"center":Y-=W/2;break;case"right":Y-=W;break;case"inner":x===y-1?Y-=W:x>0&&(Y-=W/2);break}V={left:Y,top:U,width:W+L.width,height:A+L.height,color:I.backdropColor}}b.push({label:w,font:k,textOffset:R,options:{rotation:g,color:z,strokeColor:B,strokeWidth:$,textAlign:P,textBaseline:O,translation:[S,C],backdrop:V}})}return b}_getXAxisLabelAlignment(){const{position:t,ticks:n}=this.options;if(-pi(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=lu(t,this.left,i)-i/2,d=lu(t,this.right,a)+a/2,f=h=l):(f=lu(t,this.top,i)-i/2,h=lu(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&&dc(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;Ed(r,u,0,d,l,a)}s&&fc(r)}drawTitle(){const{ctx:t,options:{position:n,title:r,reverse:s}}=this;if(!r.display)return;const o=_n(r.font),i=zr(r.padding),a=r.align;let l=o.lineHeight/2;n==="bottom"||n==="center"||_t(n)?(l+=i.bottom,yn(r.text)&&(l+=o.lineHeight*(r.text.length-1))):l+=i.top;const{titleX:u,titleY:d,maxWidth:f,rotation:h}=gxe(this,l,n,a);Ed(t,r.text,0,0,o,{color:r.color,maxWidth:f,rotation:h,textAlign:mxe(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=ct(t.grid&&t.grid.z,-1),s=ct(t.border&&t.border.z,0);return!this._isVisible()||this.draw!==Uc.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 _n(n.font)}_maxDigits(){const t=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/t}}class g0{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;yxe(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,bxe(t,i,r),this.override&&Pn.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 Pn[s]&&(delete Pn[s][r],this.override&&delete kd[r])}}function bxe(e,t,n){const r=vr(Object.create(null),[n?Pn.get(n):{},Pn.get(t),e.defaults]);Pn.set(t,r),e.defaultRoutes&&xxe(t,e.defaultRoutes),e.descriptors&&Pn.describe(t,e.descriptors)}function xxe(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(".");Pn.route(o,s,l,a)})}function yxe(e){return"id"in e&&"defaults"in e}class vxe{constructor(){this.controllers=new g0(Gs,"datasets",!0),this.elements=new g0(Qo,"elements"),this.plugins=new g0(Object,"plugins"),this.scales=new g0(Uc,"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):sn(s,i=>{const a=r||this._getRegistryForType(i);this._exec(t,a,i)})})}_exec(t,n,r){const s=nM(t);pn(r["before"+s],[],r),n[t](r),pn(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 Qn=new vxe;class wxe{constructor(){this._init=[]}notify(t,n,r,s){n==="beforeInit"&&(this._init=this._createDescriptors(t,!0),this._notify(this._init,t,"install"));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")),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(pn(a,l,i)===!1&&s.cancelable)return!1}return!0}invalidate(){St(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=ct(r.options&&r.options.plugins,{}),o=Sxe(r);return s===!1&&!n?[]:Nxe(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 Sxe(e){const t={},n=[],r=Object.keys(Qn.plugins.items);for(let o=0;o<r.length;o++)n.push(Qn.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 Cxe(e,t){return!t&&e===!1?null:e===!0?{}:e}function Nxe(e,{plugins:t,localIds:n},r,s){const o=[],i=e.getContext();for(const a of t){const l=a.id,u=Cxe(r[l],s);u!==null&&o.push({plugin:a,options:jxe(e.config,{plugin:a,local:n[l]},u,i)})}return o}function jxe(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 bk(e,t){const n=Pn.datasets[e]||{};return((t.datasets||{})[e]||{}).indexAxis||t.indexAxis||n.indexAxis||"x"}function kxe(e,t){let n=e;return e==="_index_"?n=t:e==="_value_"&&(n=t==="x"?"y":"x"),n}function Exe(e,t){return e===t?"_index_":"_value_"}function MO(e){if(e==="x"||e==="y"||e==="r")return e}function _xe(e){if(e==="top"||e==="bottom")return"x";if(e==="left"||e==="right")return"y"}function xk(e,...t){if(MO(e))return e;for(const n of t){const r=n.axis||_xe(n.position)||e.length>1&&MO(e[0].toLowerCase());if(r)return r}throw new Error(`Cannot determine type of '${e}' axis. Please provide 'axis' or 'position' option.`)}function TO(e,t,n){if(n[t+"AxisID"]===e)return{axis:t}}function Dxe(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 TO(e,"x",n[0])||TO(e,"y",n[0])}return{}}function Mxe(e,t){const n=kd[e.type]||{scales:{}},r=t.scales||{},s=bk(e.type,t),o=Object.create(null);return Object.keys(r).forEach(i=>{const a=r[i];if(!_t(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=xk(i,a,Dxe(i,e),Pn.scales[a.type]),u=Exe(l,s),d=n.scales||{};o[i]=Xm(Object.create(null),[{axis:l},a,d[l],d[u]])}),e.data.datasets.forEach(i=>{const a=i.type||e.type,l=i.indexAxis||bk(a,t),d=(kd[a]||{}).scales||{};Object.keys(d).forEach(f=>{const h=kxe(f,l),p=i[h+"AxisID"]||h;o[p]=o[p]||Object.create(null),Xm(o[p],[{axis:h},r[p],d[f]])})}),Object.keys(o).forEach(i=>{const a=o[i];Xm(a,[Pn.scales[a.type],Pn.scale])}),o}function FV(e){const t=e.options||(e.options={});t.plugins=ct(t.plugins,{}),t.scales=Mxe(e,t)}function $V(e){return e=e||{},e.datasets=e.datasets||[],e.labels=e.labels||[],e}function Txe(e){return e=e||{},e.data=$V(e.data),FV(e),e}const RO=new Map,LV=new Set;function b0(e,t){let n=RO.get(e);return n||(n=t(),RO.set(e,n),LV.add(n)),n}const fm=(e,t,n)=>{const r=Sc(t,n);r!==void 0&&e.add(r)};class Rxe{constructor(t){this._config=Txe(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=$V(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(),FV(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return b0(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,n){return b0(`${t}.transition.${n}`,()=>[[`datasets.${t}.transitions.${n}`,`transitions.${n}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,n){return b0(`${t}-${n}`,()=>[[`datasets.${t}.elements.${n}`,`datasets.${t}`,`elements.${n}`,""]])}pluginScopeKeys(t){const n=t.id,r=this.type;return b0(`${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=>fm(l,t,f))),d.forEach(f=>fm(l,s,f)),d.forEach(f=>fm(l,kd[o]||{},f)),d.forEach(f=>fm(l,Pn,f)),d.forEach(f=>fm(l,mk,f))});const u=Array.from(l);return u.length===0&&u.push(Object.create(null)),LV.has(n)&&i.set(n,u),u}chartOptionScopes(){const{options:t,type:n}=this;return[t,kd[n]||{},Pn.datasets[n]||{},{type:n},Pn,mk]}resolveNamedOptions(t,n,r,s=[""]){const o={$shared:!0},{resolver:i,subPrefixes:a}=IO(this._resolverCache,t,s);let l=i;if(Axe(i,n)){o.$shared=!1,r=Cc(r)?r():r;const u=this.createResolver(t,r,a);l=Ih(i,r,u)}for(const u of n)o[u]=l[u];return o}createResolver(t,n,r=[""],s){const{resolver:o}=IO(this._resolverCache,t,r);return _t(n)?Ih(o,n,void 0,s):o}}function IO(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:cM(t,n),subPrefixes:n.filter(a=>!a.toLowerCase().includes("hover"))},r.set(s,o)),o}const Ixe=e=>_t(e)&&Object.getOwnPropertyNames(e).some(t=>Cc(e[t]));function Axe(e,t){const{isScriptable:n,isIndexable:r}=xV(e);for(const s of t){const o=n(s),i=r(s),a=(i||o)&&e[s];if(o&&(Cc(a)||Ixe(a))||i&&yn(a))return!0}return!1}var Pxe="4.4.8";const Oxe=["top","bottom","left","right","chartArea"];function AO(e,t){return e==="top"||e==="bottom"||Oxe.indexOf(e)===-1&&t==="x"}function PO(e,t){return function(n,r){return n[e]===r[e]?n[t]-r[t]:n[e]-r[e]}}function OO(e){const t=e.chart,n=t.options.animation;t.notifyPlugins("afterRender"),pn(n&&n.onComplete,[e],t)}function Fxe(e){const t=e.chart,n=t.options.animation;pn(n&&n.onProgress,[e],t)}function zV(e){return fM()&&typeof e=="string"?e=document.getElementById(e):e&&e.length&&(e=e[0]),e&&e.canvas&&(e=e.canvas),e}const Oy={},FO=e=>{const t=zV(e);return Object.values(Oy).filter(n=>n.canvas===t).pop()};function $xe(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 Lxe(e,t,n,r){return!n||e.type==="mouseout"?null:r?t:e}function x0(e,t,n){return e.options.clip?e[n]:t[n]}function zxe(e,t){const{xScale:n,yScale:r}=e;return n&&r?{left:x0(n,t,"left"),right:x0(n,t,"right"),top:x0(r,t,"top"),bottom:x0(r,t,"bottom")}:t}class Kt{static register(...t){Qn.add(...t),$O()}static unregister(...t){Qn.remove(...t),$O()}constructor(t,n){const r=this.config=new Rxe(n),s=zV(t),o=FO(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||rxe(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=Bme(),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 wxe,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=sge(f=>this.update(f),i.resizeDelay||0),this._dataChanges=[],Oy[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}Ra.listen(this,"complete",OO),Ra.listen(this,"progress",Fxe),this._initialize(),this.attached&&this.update()}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:n},width:r,height:s,_aspectRatio:o}=this;return St(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 Qn}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():iO(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return rO(this.canvas,this.ctx),this}stop(){return Ra.stop(this),this}resize(t,n){Ra.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,iO(this,a,!0)&&(this.notifyPlugins("resize",{size:i}),pn(r.onResize,[this,i],this),this.attached&&this._doResize(l)&&this.render())}ensureScalesHaveIDs(){const n=this.options.scales||{};sn(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=xk(i,a),u=l==="r",d=l==="x";return{options:a,dposition:u?"chartArea":d?"bottom":"left",dtype:u?"radialLinear":d?"category":"linear"}}))),sn(o,i=>{const a=i.options,l=a.id,u=xk(l,a),d=ct(a.type,i.dtype);(a.position===void 0||AO(a.position,u)!==AO(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=Qn.getScale(d);f=new h({id:l,type:d,ctx:this.ctx,chart:this}),r[f.id]=f}f.init(a,t)}),sn(s,(i,a)=>{i||delete r[a]}),sn(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(PO("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||bk(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=Qn.getController(a),{datasetElementType:u,dataElementType:d}=Pn.datasets[a];Object.assign(l,{dataElementType:Qn.getElement(d),datasetElementType:u&&Qn.getElement(u)}),i.controller=new l(this,r),t.push(i.controller)}}return this._updateMetasets(),t}_resetElements(){sn(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||sn(o,u=>{u.reset()}),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(PO("z","_idx"));const{_active:a,_lastEvent:l}=this;l?this._eventHandler(l,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){sn(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);(!GP(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;$xe(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(!GP(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=[],sn(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,Cc(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&&(Ra.has(this)?this.attached&&!Ra.running(this)&&Ra.start(this):(this.draw(),OO({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=t._clip,s=!r.disabled,o=zxe(t,this.chartArea),i={meta:t,index:t.index,cancelable:!0};this.notifyPlugins("beforeDatasetDraw",i)!==!1&&(s&&dc(n,{left:r.left===!1?0:o.left-r.left,right:r.right===!1?this.width:o.right+r.right,top:r.top===!1?0:o.top-r.top,bottom:r.bottom===!1?this.height:o.bottom+r.bottom}),t.controller.draw(),s&&fc(n),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return Ka(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,n,r,s){const o=Obe.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=Hc(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);Rh(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(),Ra.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(),rO(t,n),this.platform.releaseContext(n),this.canvas=null,this.ctx=null),delete Oy[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)};sn(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(){sn(this._listeners,(t,n)=>{this.platform.removeEventListener(this,n,t)}),this._listeners={},sn(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}});!Sv(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=Yme(t),u=Lxe(t,this._lastEvent,r,l);r&&(this._lastEvent=null,pn(o.onHover,[t,a,this],this),l&&pn(o.onClick,[t,a,this],this));const d=!Sv(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)}}Ae(Kt,"defaults",Pn),Ae(Kt,"instances",Oy),Ae(Kt,"overrides",kd),Ae(Kt,"registry",Qn),Ae(Kt,"version",Pxe),Ae(Kt,"getChart",FO);function $O(){return sn(Kt.instances,e=>e._plugins.invalidate())}function Bxe(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+cr,r-cr),e.closePath(),e.clip()}function Vxe(e){return aM(e,["outerStart","outerEnd","innerStart","innerEnd"])}function Hxe(e,t,n,r){const s=Vxe(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 Ir(l,0,Math.min(o,u))};return{outerStart:a(s.outerStart),outerEnd:a(s.outerEnd),innerStart:Ir(s.innerStart,0,i),innerEnd:Ir(s.innerEnd,0,i)}}function pf(e,t,n,r){return{x:n+e*Math.cos(t),y:r+e*Math.sin(t)}}function Dv(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 p=0;const m=s-l;if(r){const I=d>0?d-r:0,F=f>0?f-r:0,z=(I+F)/2,B=z!==0?m*z/(z+r):m;p=(m-B)/2}const g=Math.max(.001,m*f-n/Fn)/f,b=(m-g)/2,x=l+b+p,y=s-b-p,{outerStart:v,outerEnd:w,innerStart:S,innerEnd:C}=Hxe(t,h,f,y-x),j=f-v,D=f-w,k=x+v/j,_=y-w/D,M=h+S,R=h+C,O=x+S/M,T=y-C/R;if(e.beginPath(),o){const I=(k+_)/2;if(e.arc(i,a,f,k,I),e.arc(i,a,f,I,_),w>0){const $=pf(D,_,i,a);e.arc($.x,$.y,w,_,y+cr)}const F=pf(R,y,i,a);if(e.lineTo(F.x,F.y),C>0){const $=pf(R,T,i,a);e.arc($.x,$.y,C,y+cr,T+Math.PI)}const z=(y-C/h+(x+S/h))/2;if(e.arc(i,a,h,y-C/h,z,!0),e.arc(i,a,h,z,x+S/h,!0),S>0){const $=pf(M,O,i,a);e.arc($.x,$.y,S,O+Math.PI,x-cr)}const B=pf(j,x,i,a);if(e.lineTo(B.x,B.y),v>0){const $=pf(j,k,i,a);e.arc($.x,$.y,v,x-cr,k)}}else{e.moveTo(i,a);const I=Math.cos(k)*f+i,F=Math.sin(k)*f+a;e.lineTo(I,F);const z=Math.cos(_)*f+i,B=Math.sin(_)*f+a;e.lineTo(z,B)}e.closePath()}function Uxe(e,t,n,r,s){const{fullCircles:o,startAngle:i,circumference:a}=t;let l=t.endAngle;if(o){Dv(e,t,n,r,l,s);for(let u=0;u<o;++u)e.fill();isNaN(a)||(l=i+(a%An||An))}return Dv(e,t,n,r,l,s),e.fill(),l}function Wxe(e,t,n,r,s){const{fullCircles:o,startAngle:i,circumference:a,options:l}=t,{borderWidth:u,borderJoinStyle:d,borderDash:f,borderDashOffset:h}=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 m=t.endAngle;if(o){Dv(e,t,n,r,m,s);for(let g=0;g<o;++g)e.stroke();isNaN(a)||(m=i+(a%An||An))}p&&Bxe(e,t,m),o||(Dv(e,t,n,r,m,s),e.stroke())}class Pf extends Qo{constructor(n){super();Ae(this,"circumference");Ae(this,"endAngle");Ae(this,"fullCircles");Ae(this,"innerRadius");Ae(this,"outerRadius");Ae(this,"pixelMargin");Ae(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}=cV(o,{x:n,y:r}),{startAngle:l,endAngle:u,innerRadius:d,outerRadius:f,circumference:h}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],s),p=(this.options.spacing+this.options.borderWidth)/2,m=ct(h,u-l),g=$g(i,l,u)&&l!==u,b=m>=An||g,x=Ya(a,d+p,f+p);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>An?Math.floor(s/An):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(Fn,s||0)),d=o*u;n.fillStyle=r.backgroundColor,n.strokeStyle=r.borderColor,Uxe(n,this,d,i,a),Wxe(n,this,d,i,a),n.restore()}}Ae(Pf,"id","arc"),Ae(Pf,"defaults",{borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0}),Ae(Pf,"defaultRoutes",{backgroundColor:"backgroundColor"}),Ae(Pf,"descriptors",{_scriptable:!0,_indexable:n=>n!=="borderDash"});function BV(e,t,n=t){e.lineCap=ct(n.borderCapStyle,t.borderCapStyle),e.setLineDash(ct(n.borderDash,t.borderDash)),e.lineDashOffset=ct(n.borderDashOffset,t.borderDashOffset),e.lineJoin=ct(n.borderJoinStyle,t.borderJoinStyle),e.lineWidth=ct(n.borderWidth,t.borderWidth),e.strokeStyle=ct(n.borderColor,t.borderColor)}function qxe(e,t,n){e.lineTo(n.x,n.y)}function Yxe(e){return e.stepped?gge:e.tension||e.cubicInterpolationMode==="monotone"?bge:qxe}function VV(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 Gxe(e,t,n,r){const{points:s,options:o}=t,{count:i,start:a,loop:l,ilen:u}=VV(s,n,r),d=Yxe(o);let{move:f=!0,reverse:h}=r||{},p,m,g;for(p=0;p<=u;++p)m=s[(a+(h?u-p:p))%i],!m.skip&&(f?(e.moveTo(m.x,m.y),f=!1):d(e,g,m,h,o.stepped),g=m);return l&&(m=s[(a+(h?u:0))%i],d(e,g,m,h,o.stepped)),!!l}function Kxe(e,t,n,r){const s=t.points,{count:o,start:i,ilen:a}=VV(s,n,r),{move:l=!0,reverse:u}=r||{};let d=0,f=0,h,p,m,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&&(p=s[y(0)],e.moveTo(p.x,p.y)),h=0;h<=a;++h){if(p=s[y(h)],p.skip)continue;const w=p.x,S=p.y,C=w|0;C===m?(S<g?g=S:S>b&&(b=S),d=(f*d+w)/++f):(v(),e.lineTo(w,S),m=C,f=0,g=b=S),x=S}v()}function yk(e){const t=e.options,n=t.borderDash&&t.borderDash.length;return!e._decimated&&!e._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!n?Kxe:Gxe}function Zxe(e){return e.stepped?Kge:e.tension||e.cubicInterpolationMode==="monotone"?Zge:vu}function Xxe(e,t,n,r){let s=t._path;s||(s=t._path=new Path2D,t.path(s,n,r)&&s.closePath()),BV(e,t.options),e.stroke(s)}function Qxe(e,t,n,r){const{segments:s,options:o}=t,i=yk(t);for(const a of s)BV(e,o,a.style),e.beginPath(),i(e,t,a,{start:n,end:n+r-1})&&e.closePath(),e.stroke()}const Jxe=typeof Path2D=="function";function e0e(e,t,n,r){Jxe&&!t.options.segment?Xxe(e,t,n,r):Qxe(e,t,n,r)}class rc extends Qo{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;Bge(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=nbe(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=_V(this,{property:n,start:s,end:s});if(!i.length)return;const a=[],l=Zxe(r);let u,d;for(u=0,d=i.length;u<d;++u){const{start:f,end:h}=i[u],p=o[f],m=o[h];if(p===m){a.push(p);continue}const g=Math.abs((s-p[n])/(m[n]-p[n])),b=l(p,m,g,r.stepped);b[n]=t[n],a.push(b)}return a.length===1?a[0]:a}pathSegment(t,n,r){return yk(this)(t,this,n,r)}path(t,n,r){const s=this.segments,o=yk(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(),e0e(t,this,r,s),t.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}Ae(rc,"id","line"),Ae(rc,"defaults",{borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0}),Ae(rc,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"}),Ae(rc,"descriptors",{_scriptable:!0,_indexable:t=>t!=="borderDash"&&t!=="fill"});function LO(e,t,n,r){const s=e.options,{[n]:o}=e.getProps([n],r);return Math.abs(t-o)<s.radius+s.hitRadius}class td extends Qo{constructor(n){super();Ae(this,"parsed");Ae(this,"skip");Ae(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 LO(this,n,"x",r)}inYRange(n,r){return LO(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||!Ka(this,r,this.size(s)/2)||(n.strokeStyle=s.borderColor,n.lineWidth=s.borderWidth,n.fillStyle=s.backgroundColor,kv(n,s,this.x,this.y))}getRange(){const n=this.options||{};return n.radius+n.hitRadius}}Ae(td,"id","point"),Ae(td,"defaults",{borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0}),Ae(td,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});function HV(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 sc(e,t,n,r){return e?0:Ir(t,n,r)}function t0e(e,t,n){const r=e.options.borderWidth,s=e.borderSkipped,o=lM(r);return{t:sc(s.top,o.top,0,n),r:sc(s.right,o.right,0,t),b:sc(s.bottom,o.bottom,0,n),l:sc(s.left,o.left,0,t)}}function n0e(e,t,n){const{enableBorderRadius:r}=e.getProps(["enableBorderRadius"]),s=e.options.borderRadius,o=ol(s),i=Math.min(t,n),a=e.borderSkipped,l=r||_t(s);return{topLeft:sc(!l||a.top||a.left,o.topLeft,0,i),topRight:sc(!l||a.top||a.right,o.topRight,0,i),bottomLeft:sc(!l||a.bottom||a.left,o.bottomLeft,0,i),bottomRight:sc(!l||a.bottom||a.right,o.bottomRight,0,i)}}function r0e(e){const t=HV(e),n=t.right-t.left,r=t.bottom-t.top,s=t0e(e,n/2,r/2),o=n0e(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 lN(e,t,n,r){const s=t===null,o=n===null,a=e&&!(s&&o)&&HV(e,r);return a&&(s||Ya(t,a.left,a.right))&&(o||Ya(n,a.top,a.bottom))}function s0e(e){return e.topLeft||e.topRight||e.bottomLeft||e.bottomRight}function o0e(e,t){e.rect(t.x,t.y,t.w,t.h)}function cN(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 ia extends Qo{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}=r0e(this),a=s0e(i.radius)?sl:o0e;t.save(),(i.w!==o.w||i.h!==o.h)&&(t.beginPath(),a(t,cN(i,n,o)),t.clip(),a(t,cN(o,-n,i)),t.fillStyle=r,t.fill("evenodd")),t.beginPath(),a(t,cN(o,n)),t.fillStyle=s,t.fill(),t.restore()}inRange(t,n,r){return lN(this,t,n,r)}inXRange(t,n){return lN(this,t,null,n)}inYRange(t,n){return lN(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}}Ae(ia,"id","bar"),Ae(ia,"defaults",{borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0}),Ae(ia,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});var i0e=Object.freeze({__proto__:null,ArcElement:Pf,BarElement:ia,LineElement:rc,PointElement:td});const vk=["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)"],zO=vk.map(e=>e.replace("rgb(","rgba(").replace(")",", 0.5)"));function UV(e){return vk[e%vk.length]}function WV(e){return zO[e%zO.length]}function a0e(e,t){return e.borderColor=UV(t),e.backgroundColor=WV(t),++t}function l0e(e,t){return e.backgroundColor=e.data.map(()=>UV(t++)),t}function c0e(e,t){return e.backgroundColor=e.data.map(()=>WV(t++)),t}function u0e(e){let t=0;return(n,r)=>{const s=e.getDatasetMeta(r).controller;s instanceof Iu?t=l0e(n,t):s instanceof tg?t=c0e(n,t):s&&(t=a0e(n,t))}}function BO(e){let t;for(t in e)if(e[t].borderColor||e[t].backgroundColor)return!0;return!1}function d0e(e){return e&&(e.borderColor||e.backgroundColor)}function f0e(){return Pn.borderColor!=="rgba(0,0,0,0.1)"||Pn.backgroundColor!=="rgba(0,0,0,0.1)"}var h0e={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=BO(r)||d0e(s)||o&&BO(o)||f0e();if(!n.forceOverride&&i)return;const a=u0e(e);r.forEach(a)}};function p0e(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,p,m,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,S=w-v;for(y=v;y<w;y++)b+=e[y].x,x+=e[y].y;b/=S,x/=S;const C=Math.floor(f*a)+1+t,j=Math.min(Math.floor((f+1)*a)+1,n)+t,{x:D,y:k}=e[d];for(p=m=-1,y=C;y<j;y++)m=.5*Math.abs((D-b)*(e[y].y-k)-(D-e[y].x)*(x-k)),m>p&&(p=m,h=e[y],g=y);i[l++]=h,d=g}return i[l++]=e[u],i}function m0e(e,t,n,r){let s=0,o=0,i,a,l,u,d,f,h,p,m,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 S=l|0;if(S===d)u<m?(m=u,f=i):u>g&&(g=u,h=i),s=(o*s+a.x)/++o;else{const C=i-1;if(!St(f)&&!St(h)){const j=Math.min(f,h),D=Math.max(f,h);j!==p&&j!==C&&b.push({...e[j],x:s}),D!==p&&D!==C&&b.push({...e[D],x:s})}i>0&&C!==p&&b.push(e[C]),b.push(a),d=S,o=0,m=g=u,f=h=p=i}}return b}function qV(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 VO(e){e.data.datasets.forEach(t=>{qV(t)})}function g0e(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=Ir(Ga(t,o.axis,i).lo,0,n-1)),u?s=Ir(Ga(t,o.axis,a).hi+1,r,n)-r:s=n-r,{start:r,count:s}}var b0e={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(e,t,n)=>{if(!n.enabled){VO(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(Rn([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}=g0e(l,u);const p=n.threshold||4*r;if(h<=p){qV(s);return}St(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 m;switch(n.algorithm){case"lttb":m=p0e(u,f,h,r,n);break;case"min-max":m=m0e(u,f,h,r);break;default:throw new Error(`Unsupported decimation algorithm '${n.algorithm}'`)}s._decimated=m})},destroy(e){VO(e)}};function x0e(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=mM(l,u,s);const d=wk(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=_V(t,d);for(const h of f){const p=wk(n,o[h.start],o[h.end],h.loop),m=EV(a,s,p);for(const g of m)i.push({source:g,target:h,start:{[n]:HO(d,p,"start",Math.max)},end:{[n]:HO(d,p,"end",Math.min)}})}}return i}function wk(e,t,n,r){if(r)return;let s=t[e],o=n[e];return e==="angle"&&(s=lo(s),o=lo(o)),{property:e,start:s,end:o}}function y0e(e,t){const{x:n=null,y:r=null}=e||{},s=t.points,o=[];return t.segments.forEach(({start:i,end:a})=>{a=mM(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 mM(e,t,n){for(;t>e;t--){const r=n[t];if(!isNaN(r.x)&&!isNaN(r.y))break}return t}function HO(e,t,n,r){return e&&t?r(e[n],t[n]):e?e[n]:t?t[n]:0}function YV(e,t){let n=[],r=!1;return yn(e)?(r=!0,n=e):n=y0e(e,t),n.length?new rc({points:n,options:{tension:0},_loop:r,_fullLoop:r}):null}function UO(e){return e&&e.fill!==!1}function v0e(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(!tr(s))return s;if(i=e[s],!i)return!1;if(i.visible)return s;o.push(s),s=i.fill}return!1}function w0e(e,t,n){const r=j0e(e);if(_t(r))return isNaN(r.value)?!1:r;let s=parseFloat(r);return tr(s)&&Math.floor(s)===s?S0e(r[0],t,s,n):["origin","start","end","stack","shape"].indexOf(r)>=0&&r}function S0e(e,t,n,r){return(e==="-"||e==="+")&&(n=t+n),n===t||n<0||n>=r?!1:n}function C0e(e,t){let n=null;return e==="start"?n=t.bottom:e==="end"?n=t.top:_t(e)?n=t.getPixelForValue(e.value):t.getBasePixel&&(n=t.getBasePixel()),n}function N0e(e,t,n){let r;return e==="start"?r=n:e==="end"?r=t.options.reverse?t.min:t.max:_t(e)?r=e.value:r=t.getBaseValue(),r}function j0e(e){const t=e.options,n=t.fill;let r=ct(n&&n.target,n);return r===void 0&&(r=!!t.backgroundColor),r===!1||r===null?!1:r===!0?"origin":r}function k0e(e){const{scale:t,index:n,line:r}=e,s=[],o=r.segments,i=r.points,a=E0e(t,n);a.push(YV({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++)_0e(s,i[d],a)}return new rc({points:s,options:{}})}function E0e(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 _0e(e,t,n){const r=[];for(let s=0;s<n.length;s++){const o=n[s],{first:i,last:a,point:l}=D0e(o,t,"x");if(!(!l||i&&a)){if(i)r.unshift(l);else if(e.push(l),!a)break}}e.push(...r)}function D0e(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(Ya(s,f,h)){a=s===f,l=s===h;break}}return{first:a,last:l,point:r}}class GV{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:An},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 M0e(e){const{chart:t,fill:n,line:r}=e;if(tr(n))return T0e(t,n);if(n==="stack")return k0e(e);if(n==="shape")return!0;const s=R0e(e);return s instanceof GV?s:YV(s,r)}function T0e(e,t){const n=e.getDatasetMeta(t);return n&&e.isDatasetVisible(t)?n.dataset:null}function R0e(e){return(e.scale||{}).getPointPositionForValue?A0e(e):I0e(e)}function I0e(e){const{scale:t={},fill:n}=e,r=C0e(n,t);if(tr(r)){const s=t.isHorizontal();return{x:s?r:null,y:s?null:r}}return null}function A0e(e){const{scale:t,fill:n}=e,r=t.options,s=t.getLabels().length,o=r.reverse?t.max:t.min,i=N0e(n,t,o),a=[];if(r.grid.circular){const l=t.getPointPositionForValue(0,o);return new GV({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 uN(e,t,n){const r=M0e(t),{line:s,scale:o,axis:i}=t,a=s.options,l=a.fill,u=a.backgroundColor,{above:d=u,below:f=u}=l||{};r&&s.points.length&&(dc(e,n),P0e(e,{line:s,target:r,above:d,below:f,area:n,scale:o,axis:i}),fc(e))}function P0e(e,t){const{line:n,target:r,above:s,below:o,area:i,scale:a}=t,l=n._loop?"angle":t.axis;e.save(),l==="x"&&o!==s&&(WO(e,r,i.top),qO(e,{line:n,target:r,color:s,scale:a,property:l}),e.restore(),e.save(),WO(e,r,i.bottom)),qO(e,{line:n,target:r,color:o,scale:a,property:l}),e.restore()}function WO(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[mM(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 qO(e,t){const{line:n,target:r,property:s,color:o,scale:i}=t,a=x0e(n,r,s);for(const{source:l,target:u,start:d,end:f}of a){const{style:{backgroundColor:h=o}={}}=l,p=r!==!0;e.save(),e.fillStyle=h,O0e(e,i,p&&wk(s,d,f)),e.beginPath();const m=!!n.pathSegment(e,l);let g;if(p){m?e.closePath():YO(e,r,f,s);const b=!!r.pathSegment(e,u,{move:m,reverse:!0});g=m&&b,g||YO(e,r,d,s)}e.closePath(),e.fill(g?"evenodd":"nonzero"),e.restore()}}function O0e(e,t,n){const{top:r,bottom:s}=t.chart.chartArea,{property:o,start:i,end:a}=n||{};o==="x"&&(e.beginPath(),e.rect(i,r,a-i,s-r),e.clip())}function YO(e,t,n,r){const s=t.interpolate(n,r);s&&e.lineTo(s.x,s.y)}var F0e={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 rc&&(l={visible:e.isDatasetVisible(i),index:i,fill:w0e(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=v0e(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&&uN(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;UO(o)&&uN(e.ctx,o,e.chartArea)}},beforeDatasetDraw(e,t,n){const r=t.meta.$filler;!UO(r)||n.drawTime!=="beforeDatasetDraw"||uN(e.ctx,r,e.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const GO=(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)}},$0e=(e,t)=>e!==null&&t!==null&&e.datasetIndex===t.datasetIndex&&e.index===t.index;class KO extends Qo{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=pn(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=_n(r.font),o=s.size,i=this._computeTitleHeight(),{boxWidth:a,itemHeight:l}=GO(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,p=-d;return this.legendItems.forEach((m,g)=>{const b=r+n/2+o.measureText(m.text).width;(g===0||u[u.length-1]+b+2*a>i)&&(f+=d,u[u.length-(g>0?0:1)]=0,p+=d,h++),l[g]={left:0,top:p,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,p=0,m=0,g=0;return this.legendItems.forEach((b,x)=>{const{itemWidth:y,itemHeight:v}=L0e(r,n,o,b,s);x>0&&p+v+2*a>d&&(f+=h+a,u.push({width:h,height:p}),m+=h+a,g++,h=p=0),l[x]={left:m,top:p,col:g,width:y,height:v},h=Math.max(h,y),p+=v+a}),f+=h,u.push({width:h,height:p}),f}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:n,options:{align:r,labels:{padding:s},rtl:o}}=this,i=Jf(o,this.left,this.width);if(this.isHorizontal()){let a=0,l=Xr(r,this.left+s,this.right-this.lineWidths[a]);for(const u of n)a!==u.row&&(a=u.row,l=Xr(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=Xr(r,this.top+t+s,this.bottom-this.columnSizes[a].height);for(const u of n)u.col!==a&&(a=u.col,l=Xr(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;dc(t,this),this._draw(),fc(t)}}_draw(){const{options:t,columnSizes:n,lineWidths:r,ctx:s}=this,{align:o,labels:i}=t,a=Pn.color,l=Jf(t.rtl,this.left,this.width),u=_n(i.font),{padding:d}=i,f=u.size,h=f/2;let p;this.drawTitle(),s.textAlign=l.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=u.string;const{boxWidth:m,boxHeight:g,itemHeight:b}=GO(i,f),x=function(C,j,D){if(isNaN(m)||m<=0||isNaN(g)||g<0)return;s.save();const k=ct(D.lineWidth,1);if(s.fillStyle=ct(D.fillStyle,a),s.lineCap=ct(D.lineCap,"butt"),s.lineDashOffset=ct(D.lineDashOffset,0),s.lineJoin=ct(D.lineJoin,"miter"),s.lineWidth=k,s.strokeStyle=ct(D.strokeStyle,a),s.setLineDash(ct(D.lineDash,[])),i.usePointStyle){const _={radius:g*Math.SQRT2/2,pointStyle:D.pointStyle,rotation:D.rotation,borderWidth:k},M=l.xPlus(C,m/2),R=j+h;bV(s,_,M,R,i.pointStyleWidth&&m)}else{const _=j+Math.max((f-g)/2,0),M=l.leftForLtr(C,m),R=ol(D.borderRadius);s.beginPath(),Object.values(R).some(O=>O!==0)?sl(s,{x:M,y:_,w:m,h:g,radius:R}):s.rect(M,_,m,g),s.fill(),k!==0&&s.stroke()}s.restore()},y=function(C,j,D){Ed(s,D.text,C,j+b/2,u,{strikethrough:D.hidden,textAlign:l.textAlign(D.textAlign)})},v=this.isHorizontal(),w=this._computeTitleHeight();v?p={x:Xr(o,this.left+d,this.right-r[0]),y:this.top+d+w,line:0}:p={x:this.left+d,y:Xr(o,this.top+w+d,this.bottom-n[0].height),line:0},NV(this.ctx,t.textDirection);const S=b+d;this.legendItems.forEach((C,j)=>{s.strokeStyle=C.fontColor,s.fillStyle=C.fontColor;const D=s.measureText(C.text).width,k=l.textAlign(C.textAlign||(C.textAlign=i.textAlign)),_=m+h+D;let M=p.x,R=p.y;l.setWidth(this.width),v?j>0&&M+_+d>this.right&&(R=p.y+=S,p.line++,M=p.x=Xr(o,this.left+d,this.right-r[p.line])):j>0&&R+S>this.bottom&&(M=p.x=M+n[p.line].width+d,p.line++,R=p.y=Xr(o,this.top+w+d,this.bottom-n[p.line].height));const O=l.x(M);if(x(O,R,C),M=oge(k,M+m+h,v?M+_:this.right,t.rtl),y(l.x(M),R,C),v)p.x+=_+d;else if(typeof C.text!="string"){const T=u.lineHeight;p.y+=KV(C,T)+d}else p.y+=S}),jV(this.ctx,t.textDirection)}drawTitle(){const t=this.options,n=t.title,r=_n(n.font),s=zr(n.padding);if(!n.display)return;const o=Jf(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=Xr(t.align,f,this.right-h);else{const m=this.columnSizes.reduce((g,b)=>Math.max(g,b.height),0);d=u+Xr(t.align,this.top,this.bottom-m-t.labels.padding-this._computeTitleHeight())}const p=Xr(a,f,f+h);i.textAlign=o.textAlign(oM(a)),i.textBaseline="middle",i.strokeStyle=n.color,i.fillStyle=n.color,i.font=r.string,Ed(i,n.text,p,d,r)}_computeTitleHeight(){const t=this.options.title,n=_n(t.font),r=zr(t.padding);return t.display?n.lineHeight+r.height:0}_getLegendItemAt(t,n){let r,s,o;if(Ya(t,this.left,this.right)&&Ya(n,this.top,this.bottom)){for(o=this.legendHitBoxes,r=0;r<o.length;++r)if(s=o[r],Ya(t,s.left,s.left+s.width)&&Ya(n,s.top,s.top+s.height))return this.legendItems[r]}return null}handleEvent(t){const n=this.options;if(!V0e(t.type,n))return;const r=this._getLegendItemAt(t.x,t.y);if(t.type==="mousemove"||t.type==="mouseout"){const s=this._hoveredItem,o=$0e(s,r);s&&!o&&pn(n.onLeave,[t,s,this],this),this._hoveredItem=r,r&&!o&&pn(n.onHover,[t,r,this],this)}else r&&pn(n.onClick,[t,r,this],this)}}function L0e(e,t,n,r,s){const o=z0e(r,e,t,n),i=B0e(s,r,t.lineHeight);return{itemWidth:o,itemHeight:i}}function z0e(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 B0e(e,t,n){let r=e;return typeof t.text!="string"&&(r=KV(t,n)),r}function KV(e,t){const n=e.text?e.text.length:0;return t*n}function V0e(e,t){return!!((e==="mousemove"||e==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(e==="click"||e==="mouseup"))}var H0e={id:"legend",_element:KO,start(e,t,n){const r=e.legend=new KO({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=zr(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 gM extends Qo{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=yn(r.text)?r.text.length:1;this._padding=zr(r.padding);const o=s*_n(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=Xr(a,r,o),f=n+t,u=o-r):(i.position==="left"?(d=r+t,f=Xr(a,s,n),l=Fn*-.5):(d=o-t,f=Xr(a,n,s),l=Fn*.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=_n(n.font),o=r.lineHeight/2+this._padding.top,{titleX:i,titleY:a,maxWidth:l,rotation:u}=this._drawArgs(o);Ed(t,n.text,0,0,r,{color:n.color,maxWidth:l,rotation:u,textAlign:oM(n.align),textBaseline:"middle",translation:[i,a]})}}function U0e(e,t){const n=new gM({ctx:e.ctx,options:t,chart:e});ts.configure(e,n,t),ts.addBox(e,n),e.titleBlock=n}var W0e={id:"title",_element:gM,start(e,t,n){U0e(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 y0=new WeakMap;var q0e={id:"subtitle",start(e,t,n){const r=new gM({ctx:e.ctx,options:n,chart:e});ts.configure(e,r,n),ts.addBox(e,r),y0.set(e,r)},stop(e){ts.removeBox(e,y0.get(e)),y0.delete(e)},beforeUpdate(e,t,n){const r=y0.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 Mm={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=pk(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 $i(e,t){return t&&(yn(t)?Array.prototype.push.apply(e,t):e.push(t)),e}function Ia(e){return(typeof e=="string"||e instanceof String)&&e.indexOf(`
|
|
761
761
|
`)>-1?e.split(`
|
|
762
762
|
`):e}function Y0e(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 ZO(e,t){const n=e.chart.ctx,{body:r,footer:s,title:o}=e,{boxWidth:i,boxHeight:a}=t,l=_n(t.bodyFont),u=_n(t.titleFont),d=_n(t.footerFont),f=o.length,h=s.length,p=r.length,m=zr(t.padding);let g=m.height,b=0,x=r.reduce((w,S)=>w+S.before.length+S.lines.length+S.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+=p*w+(x-p)*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,sn(e.title,v),n.font=l.string,sn(e.beforeBody.concat(e.afterBody),v),y=t.displayColors?i+2+t.boxPadding:0,sn(r,w=>{sn(w.before,v),sn(w.lines,v),sn(w.after,v)}),y=0,n.font=d.string,sn(e.footer,v),n.restore(),b+=m.width,{width:b,height:g}}function G0e(e,t){const{y:n,height:r}=t;return n<r/2?"top":n>e.height-r/2?"bottom":"center"}function K0e(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 Z0e(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"),K0e(u,e,t,n)&&(u="center"),u}function XO(e,t,n){const r=n.yAlign||t.yAlign||G0e(e,n);return{xAlign:n.xAlign||t.xAlign||Z0e(e,t,n,r),yAlign:r}}function X0e(e,t){let{x:n,width:r}=e;return t==="right"?n-=r:t==="center"&&(n-=r/2),n}function Q0e(e,t,n){let{y:r,height:s}=e;return t==="top"?r+=n:t==="bottom"?r-=s+n:r-=s/2,r}function QO(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:p}=ol(i);let m=X0e(t,a);const g=Q0e(t,l,u);return l==="center"?a==="left"?m+=u:a==="right"&&(m-=u):a==="left"?m-=Math.max(d,h)+s:a==="right"&&(m+=Math.max(f,p)+s),{x:Ir(m,0,r.width-t.width),y:Ir(g,0,r.height-t.height)}}function v0(e,t,n){const r=zr(n.padding);return t==="center"?e.x+e.width/2:t==="right"?e.x+e.width-r.right:e.x+r.left}function JO(e){return $i([],Ia(e))}function J0e(e,t,n){return Hc(e,{tooltip:t,tooltipItems:n,type:"tooltip"})}function eF(e,t){const n=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return n?e.override(n):e}const ZV={beforeTitle:_a,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:_a,beforeBody:_a,beforeLabel:_a,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 St(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:_a,afterBody:_a,beforeFooter:_a,footer:_a,afterFooter:_a};function As(e,t,n,r){const s=e[t].call(n,r);return typeof s>"u"?ZV[t].call(n,r):s}class Sk extends Qo{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 DV(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(o)),o}getContext(){return this.$context||(this.$context=J0e(this.chart.getContext(),this,this._tooltipItems))}getTitle(t,n){const{callbacks:r}=n,s=As(r,"beforeTitle",this,t),o=As(r,"title",this,t),i=As(r,"afterTitle",this,t);let a=[];return a=$i(a,Ia(s)),a=$i(a,Ia(o)),a=$i(a,Ia(i)),a}getBeforeBody(t,n){return JO(As(n.callbacks,"beforeBody",this,t))}getBody(t,n){const{callbacks:r}=n,s=[];return sn(t,o=>{const i={before:[],lines:[],after:[]},a=eF(r,o);$i(i.before,Ia(As(a,"beforeLabel",this,o))),$i(i.lines,As(a,"label",this,o)),$i(i.after,Ia(As(a,"afterLabel",this,o))),s.push(i)}),s}getAfterBody(t,n){return JO(As(n.callbacks,"afterBody",this,t))}getFooter(t,n){const{callbacks:r}=n,s=As(r,"beforeFooter",this,t),o=As(r,"footer",this,t),i=As(r,"afterFooter",this,t);let a=[];return a=$i(a,Ia(s)),a=$i(a,Ia(o)),a=$i(a,Ia(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(Y0e(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))),sn(a,d=>{const f=eF(t.callbacks,d);s.push(As(f,"labelColor",this,d)),o.push(As(f,"labelPointStyle",this,d)),i.push(As(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=Mm[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=ZO(this,r),u=Object.assign({},a,l),d=XO(this.chart,r,u),f=QO(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}=ol(a),{x:h,y:p}=t,{width:m,height:g}=n;let b,x,y,v,w,S;return o==="center"?(w=p+g/2,s==="left"?(b=h,x=b-i,v=w+i,S=w-i):(b=h+m,x=b+i,v=w-i,S=w+i),y=b):(s==="left"?x=h+Math.max(l,d)+i:s==="right"?x=h+m-Math.max(u,f)-i:x=this.caretX,o==="top"?(v=p,w=v-i,b=x-i,y=x+i):(v=p+g,w=v+i,b=x+i,y=x-i),S=v),{x1:b,x2:x,x3:y,y1:v,y2:w,y3:S}}drawTitle(t,n,r){const s=this.title,o=s.length;let i,a,l;if(o){const u=Jf(r.rtl,this.x,this.width);for(t.x=v0(this,r.titleAlign,r),n.textAlign=u.textAlign(r.titleAlign),n.textBaseline="middle",i=_n(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=_n(o.bodyFont),f=v0(this,"left",o),h=s.x(f),p=l<d.lineHeight?(d.lineHeight-l)/2:0,m=n.y+p;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=m+l/2;t.strokeStyle=o.multiKeyBackground,t.fillStyle=o.multiKeyBackground,kv(t,g,b,x),t.strokeStyle=i.borderColor,t.fillStyle=i.backgroundColor,kv(t,g,b,x)}else{t.lineWidth=_t(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=ol(i.borderRadius);Object.values(x).some(y=>y!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,sl(t,{x:g,y:m,w:u,h:l,radius:x}),t.fill(),t.stroke(),t.fillStyle=i.backgroundColor,t.beginPath(),sl(t,{x:b,y:m+1,w:u-2,h:l-2,radius:x}),t.fill()):(t.fillStyle=o.multiKeyBackground,t.fillRect(g,m,u,l),t.strokeRect(g,m,u,l),t.fillStyle=i.backgroundColor,t.fillRect(b,m+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=_n(r.bodyFont);let h=f.lineHeight,p=0;const m=Jf(r.rtl,this.x,this.width),g=function(D){n.fillText(D,m.x(t.x+p),t.y+h/2),t.y+=h+o},b=m.textAlign(i);let x,y,v,w,S,C,j;for(n.textAlign=i,n.textBaseline="middle",n.font=f.string,t.x=v0(this,b,r),n.fillStyle=r.bodyColor,sn(this.beforeBody,g),p=a&&b!=="right"?i==="center"?u/2+d:u+2+d:0,w=0,C=s.length;w<C;++w){for(x=s[w],y=this.labelTextColors[w],n.fillStyle=y,sn(x.before,g),v=x.lines,a&&v.length&&(this._drawColorBox(n,t,w,m,r),h=Math.max(f.lineHeight,l)),S=0,j=v.length;S<j;++S)g(v[S]),h=f.lineHeight;sn(x.after,g)}p=0,h=f.lineHeight,sn(this.afterBody,g),t.y-=o}drawFooter(t,n,r){const s=this.footer,o=s.length;let i,a;if(o){const l=Jf(r.rtl,this.x,this.width);for(t.x=v0(this,r.footerAlign,r),t.y+=r.footerMarginTop,n.textAlign=l.textAlign(r.footerAlign),n.textBaseline="middle",i=_n(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:p,bottomRight:m}=ol(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-m),n.quadraticCurveTo(a+u,l+d,a+u-m,l+d),i==="bottom"&&this.drawCaret(t,n,r,s),n.lineTo(a+p,l+d),n.quadraticCurveTo(a,l+d,a,l+d-p),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=Mm[t.position].call(this,this._active,this._eventPosition);if(!i)return;const a=this._size=ZO(this,t),l=Object.assign({},i,this._size),u=XO(n,t,l),d=QO(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=zr(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),NV(t,n.textDirection),o.y+=i.top,this.drawTitle(o,t,n),this.drawBody(o,t,n),this.drawFooter(o,t,n),jV(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=!Sv(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||!Sv(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=Mm[o.position].call(this,t,n);return i!==!1&&(r!==i.x||s!==i.y)}}Ae(Sk,"positioners",Mm);var XV={id:"tooltip",_element:Sk,positioners:Mm,afterInit(e,t,n){n&&(e.tooltip=new Sk({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:ZV},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"]},eye=Object.freeze({__proto__:null,Colors:h0e,Decimation:b0e,Filler:F0e,Legend:H0e,SubTitle:q0e,Title:W0e,Tooltip:XV});const tye=(e,t,n,r)=>(typeof t=="string"?(n=e.push(t)-1,r.unshift({index:n,label:t})):isNaN(t)&&(n=null),n);function nye(e,t,n,r){const s=e.indexOf(t);if(s===-1)return tye(e,t,n,r);const o=e.lastIndexOf(t);return s!==o?n:s}const rye=(e,t)=>e===null?null:Ir(Math.round(e),0,t);function tF(e){const t=this.getLabels();return e>=0&&e<t.length?t[e]:e}class zg extends Uc{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(St(t))return null;const r=this.getLabels();return n=isFinite(n)&&r[n]===t?n:nye(r,t,ct(n,t),this._addedLabels),rye(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 tF.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}}Ae(zg,"id","category"),Ae(zg,"defaults",{ticks:{callback:tF}});function sye(e,t){const n=[],{bounds:s,step:o,min:i,max:a,precision:l,count:u,maxTicks:d,maxDigits:f,includeBounds:h}=e,p=o||1,m=d-1,{min:g,max:b}=t,x=!St(i),y=!St(a),v=!St(u),w=(b-g)/(f+1);let S=ZP((b-g)/m/p)*p,C,j,D,k;if(S<1e-14&&!x&&!y)return[{value:g},{value:b}];k=Math.ceil(b/S)-Math.floor(g/S),k>m&&(S=ZP(k*S/m/p)*p),St(l)||(C=Math.pow(10,l),S=Math.ceil(S*C)/C),s==="ticks"?(j=Math.floor(g/S)*S,D=Math.ceil(b/S)*S):(j=g,D=b),x&&y&&o&&Qme((a-i)/o,S/1e3)?(k=Math.round(Math.min((a-i)/S,d)),S=(a-i)/k,j=i,D=a):v?(j=x?i:j,D=y?a:D,k=u-1,S=(D-j)/k):(k=(D-j)/S,Qm(k,Math.round(k),S/1e3)?k=Math.round(k):k=Math.ceil(k));const _=Math.max(XP(S),XP(j));C=Math.pow(10,St(l)?_:l),j=Math.round(j*C)/C,D=Math.round(D*C)/C;let M=0;for(x&&(h&&j!==i?(n.push({value:i}),j<i&&M++,Qm(Math.round((j+M*S)*C)/C,i,nF(i,w,e))&&M++):j<i&&M++);M<k;++M){const R=Math.round((j+M*S)*C)/C;if(y&&R>a)break;n.push({value:R})}return y&&h&&D!==a?n.length&&Qm(n[n.length-1].value,a,nF(a,w,e))?n[n.length-1].value=a:n.push({value:a}):(!y||D===a)&&n.push({value:D}),n}function nF(e,t,{horizontal:n,minRotation:r}){const s=pi(r),o=(n?Math.sin(s):Math.cos(s))||.001,i=.75*t*(""+e).length;return Math.min(t/o,i)}class Mv extends Uc{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 St(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=oa(s),u=oa(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=sye(s,o);return t.bounds==="ticks"&&lV(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 Kb(t,this.chart.options.locale,this.options.ticks.format)}}class _d extends Mv{determineDataLimits(){const{min:t,max:n}=this.getMinMax(!0);this.min=tr(t)?t:0,this.max=tr(n)?n:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),n=t?this.width:this.height,r=pi(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}}Ae(_d,"id","linear"),Ae(_d,"defaults",{ticks:{callback:D1.formatters.numeric}});const Bg=e=>Math.floor(nc(e)),uu=(e,t)=>Math.pow(10,Bg(e)+t);function rF(e){return e/Math.pow(10,Bg(e))===1}function sF(e,t,n){const r=Math.pow(10,n),s=Math.floor(e/r);return Math.ceil(t/r)-s}function oye(e,t){const n=t-e;let r=Bg(n);for(;sF(e,t,r)>10;)r++;for(;sF(e,t,r)<10;)r--;return Math.min(r,Bg(e))}function iye(e,{min:t,max:n}){t=so(e.min,t);const r=[],s=Bg(t);let o=oye(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=so(e.min,Math.round((l+d+f*Math.pow(10,o))*i)/i);for(;h<n;)r.push({value:h,major:rF(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 p=so(e.max,h);return r.push({value:p,major:rF(p),significand:f}),r}class Ph extends Uc{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,n){const r=Mv.prototype.parse.apply(this,[t,n]);if(r===0){this._zero=!0;return}return tr(r)&&r>0?r:null}determineDataLimits(){const{min:t,max:n}=this.getMinMax(!0);this.min=tr(t)?Math.max(0,t):null,this.max=tr(n)?Math.max(0,n):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!tr(this._userMin)&&(this.min=t===uu(this.min,0)?uu(this.min,-1):uu(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(uu(r,-1)),i(uu(s,1)))),r<=0&&o(uu(s,-1)),s<=0&&i(uu(r,1)),this.min=r,this.max=s}buildTicks(){const t=this.options,n={min:this._userMin,max:this._userMax},r=iye(n,this);return t.bounds==="ticks"&&lV(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":Kb(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=nc(t),this._valueRange=nc(this.max)-nc(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(nc(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const n=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+n*this._valueRange)}}Ae(Ph,"id","logarithmic"),Ae(Ph,"defaults",{ticks:{callback:D1.formatters.logarithmic,major:{enabled:!0}}});function Ck(e){const t=e.ticks;if(t.display&&e.display){const n=zr(t.backdropPadding);return ct(t.font&&t.font.size,Pn.font.size)+n.height}return 0}function aye(e,t,n){return n=yn(n)?n:[n],{w:mge(e,t.string,n),h:n.length*t.lineHeight}}function oF(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 lye(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?Fn/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=_n(u.font),h=aye(e.ctx,f,e._pointLabels[l]);r[l]=h;const p=lo(e.getIndexAngle(l)+a),m=Math.round(rM(p)),g=oF(m,d.x,h.w,0,180),b=oF(m,d.y,h.h,90,270);cye(n,t,p,g,b)}e.setCenterPoint(t.l-n.l,n.r-t.r,t.t-n.t,n.b-t.b),e._pointLabelItems=fye(e,r,s)}function cye(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 uye(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(rM(lo(l.angle+cr))),d=mye(l.y,a.h,u),f=hye(u),h=pye(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 dye(e,t){if(!t)return!0;const{left:n,top:r,right:s,bottom:o}=e;return!(Ka({x:n,y:r},t)||Ka({x:n,y:o},t)||Ka({x:s,y:r},t)||Ka({x:s,y:o},t))}function fye(e,t,n){const r=[],s=e._pointLabels.length,o=e.options,{centerPointLabels:i,display:a}=o.pointLabels,l={extra:Ck(o)/2,additionalAngle:i?Fn/s:0};let u;for(let d=0;d<s;d++){l.padding=n[d],l.size=t[d];const f=uye(e,d,l);r.push(f),a==="auto"&&(f.visible=dye(f,u),f.visible&&(u=f))}return r}function hye(e){return e===0||e===180?"center":e<180?"left":"right"}function pye(e,t,n){return n==="right"?e-=t:n==="center"&&(e-=t/2),e}function mye(e,t,n){return n===90||n===270?e-=t/2:(n>270||n<90)&&(e-=t),e}function gye(e,t,n){const{left:r,top:s,right:o,bottom:i}=n,{backdropColor:a}=t;if(!St(a)){const l=ol(t.borderRadius),u=zr(t.backdropPadding);e.fillStyle=a;const d=r-u.left,f=s-u.top,h=o-r+u.width,p=i-s+u.height;Object.values(l).some(m=>m!==0)?(e.beginPath(),sl(e,{x:d,y:f,w:h,h:p,radius:l}),e.fill()):e.fillRect(d,f,h,p)}}function bye(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));gye(n,i,o);const a=_n(i.font),{x:l,y:u,textAlign:d}=o;Ed(n,e._pointLabels[s],l,u+a.lineHeight/2,a,{color:i.color,textAlign:d,textBaseline:"middle"})}}function QV(e,t,n,r){const{ctx:s}=e;if(n)s.arc(e.xCenter,e.yCenter,t,0,An);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 xye(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(),QV(e,n,i,r),o.closePath(),o.stroke(),o.restore())}function yye(e,t,n){return Hc(e,{label:n,index:t,type:"pointLabel"})}class Tm extends Mv{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=zr(Ck(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=tr(t)&&!isNaN(t)?t:0,this.max=tr(n)&&!isNaN(n)?n:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/Ck(this.options))}generateTickLabels(t){Mv.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((n,r)=>{const s=pn(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?lye(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=An/(this._pointLabels.length||1),r=this.options.startAngle||0;return lo(t*n+pi(r))}getDistanceFromCenterForValue(t){if(St(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(St(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 yye(this.getContext(),t,r)}}getPointPosition(t,n,r=0){const s=this.getIndexAngle(t)-cr+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(),QV(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&&bye(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),p=s.setContext(h),m=o.setContext(h);xye(this,p,l,i,m)}}),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=_n(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=zr(u.backdropPadding);t.fillRect(-i/2-f.left,-o-d.size/2-f.top,i+f.width,d.size+f.height)}Ed(t,a.label,0,-o,d,{color:u.color,strokeColor:u.textStrokeColor,strokeWidth:u.textStrokeWidth})}),t.restore()}drawTitle(){}}Ae(Tm,"id","radialLinear"),Ae(Tm,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:D1.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),Ae(Tm,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),Ae(Tm,"descriptors",{angleLines:{_fallback:"grid"}});const R1={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}},Ws=Object.keys(R1);function iF(e,t){return e-t}function aF(e,t){if(St(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)),tr(i)||(i=typeof r=="string"?n.parse(i,r):n.parse(i)),i===null?null:(s&&(i=s==="week"&&(jd(o)||o===!0)?n.startOf(i,"isoWeek",o):n.startOf(i,s)),+i)}function lF(e,t,n,r){const s=Ws.length;for(let o=Ws.indexOf(e);o<s-1;++o){const i=R1[Ws[o]],a=i.steps?i.steps:Number.MAX_SAFE_INTEGER;if(i.common&&Math.ceil((n-t)/(a*i.size))<=r)return Ws[o]}return Ws[s-1]}function vye(e,t,n,r,s){for(let o=Ws.length-1;o>=Ws.indexOf(n);o--){const i=Ws[o];if(R1[i].common&&e._adapter.diff(s,r,i)>=t-1)return i}return Ws[n?Ws.indexOf(n):0]}function wye(e){for(let t=Ws.indexOf(e)+1,n=Ws.length;t<n;++t)if(R1[Ws[t]].common)return Ws[t]}function cF(e,t,n){if(!n)e[t]=!0;else if(n.length){const{lo:r,hi:s}=sM(n,t),o=n[r]>=t?n[r]:n[s];e[o]=!0}}function Sye(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 uF(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:Sye(e,r,s,n)}class Vg extends Uc{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 Tbe._date(t.adapters.date);s.init(n),Xm(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:aF(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=tr(s)&&!isNaN(s)?s:+n.startOf(Date.now(),r),o=tr(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=nge(s,o,i);return this._unit=n.unit||(r.autoSkip?lF(n.minUnit,this.min,this.max,this._getLabelCapacity(o)):vye(this,a.length,n.minUnit,this.min,this.max)),this._majorUnit=!r.major.enabled||this._unit==="year"?void 0:wye(this._unit),this.initOffsets(s),t.reverse&&a.reverse(),uF(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=Ir(n,0,i),r=Ir(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||lF(o.minUnit,n,r,this._getLabelCapacity(n)),a=ct(s.ticks.stepSize,1),l=i==="week"?o.isoWeekday:!1,u=jd(l)||l===!0,d={};let f=n,h,p;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 m=s.ticks.source==="data"&&this.getDataTimestamps();for(h=f,p=0;h<r;h=+t.add(h,a,i),p++)cF(d,h,m);return(h===r||s.bounds==="ticks"||p===1)&&cF(d,h,m),Object.keys(d).sort(iF).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 pn(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],p=u&&f&&h&&h.major;return this._adapter.format(t,s||(p?f:d))}generateTickLabels(t){let n,r,s;for(n=0,r=t.length;n<r;++n)s=t[n],s.label=this._tickFormatFunction(s.value,n,t)}getDecimalForValue(t){return t===null?NaN:(t-this.min)/(this.max-this.min)}getPixelForValue(t){const n=this._offsets,r=this.getDecimalForValue(t);return this.getPixelForDecimal((n.start+r)*n.factor)}getValueForPixel(t){const n=this._offsets,r=this.getDecimalForPixel(t)/n.factor-n.end;return this.min+r*(this.max-this.min)}_getLabelSize(t){const n=this.options.ticks,r=this.ctx.measureText(t).width,s=pi(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,uF(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(aF(this,s[n]));return this._cache.labels=this._normalized?t:this.normalize(t)}normalize(t){return dV(t.sort(iF))}}Ae(Vg,"id","time"),Ae(Vg,"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 w0(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}=Ga(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}=Ga(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 Nk extends Vg{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=w0(n,this.min),this._tableRange=w0(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(w0(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const n=this._offsets,r=this.getDecimalForPixel(t)/n.factor-n.end;return w0(this._table,r*this._tableRange+this._minPos,!0)}}Ae(Nk,"id","timeseries"),Ae(Nk,"defaults",Vg.defaults);var Cye=Object.freeze({__proto__:null,CategoryScale:zg,LinearScale:_d,LogarithmicScale:Ph,RadialLinearScale:Tm,TimeScale:Vg,TimeSeriesScale:Nk});const Nye=[Mbe,i0e,eye,Cye];class Nc{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*jye(e){for(const t of e)yield*t}function JV(e){return Array.from(jye(e))}function Of(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 at=1e-6,bM=1e-12,Rt=Math.PI,er=Rt/2,dF=Rt/4,vo=Rt*2,xs=180/Rt,mn=Rt/180,Gt=Math.abs,Np=Math.atan,ha=Math.atan2,wt=Math.cos,S0=Math.ceil,eH=Math.exp,Tv=Math.log,dN=Math.pow,mt=Math.sin,Lo=Math.sign||function(e){return e>0?1:e<0?-1:0},_s=Math.sqrt,xM=Math.tan;function tH(e){return e>1?0:e<-1?Rt:Math.acos(e)}function Ko(e){return e>1?er:e<-1?-er:Math.asin(e)}function Tr(){}function Rv(e,t){e&&hF.hasOwnProperty(e.type)&&hF[e.type](e,t)}var fF={Feature:function(e,t){Rv(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,s=n.length;++r<s;)Rv(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){jk(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)jk(n[r],t,0)},Polygon:function(e,t){pF(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)pF(n[r],t)},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,s=n.length;++r<s;)Rv(n[r],t)}};function jk(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 pF(e,t){var n=-1,r=e.length;for(t.polygonStart();++n<r;)jk(e[n],t,1);t.polygonEnd()}function ju(e,t){e&&fF.hasOwnProperty(e.type)?fF[e.type](e,t):Rv(e,t)}function kk(e){return[ha(e[1],e[0]),Ko(e[2])]}function Oh(e){var t=e[0],n=e[1],r=wt(n);return[r*wt(t),r*mt(t),mt(n)]}function C0(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function Iv(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 fN(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function N0(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function Ek(e){var t=_s(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function _k(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 Dk(e,t){return Gt(e)>Rt&&(e-=Math.round(e/vo)*vo),[e,t]}Dk.invert=Dk;function nH(e,t,n){return(e%=vo)?t||n?_k(gF(e),bF(t,n)):gF(e):t||n?bF(t,n):Dk}function mF(e){return function(t,n){return t+=e,Gt(t)>Rt&&(t-=Math.round(t/vo)*vo),[t,n]}}function gF(e){var t=mF(e);return t.invert=mF(-e),t}function bF(e,t){var n=wt(e),r=mt(e),s=wt(t),o=mt(t);function i(a,l){var u=wt(l),d=wt(a)*u,f=mt(a)*u,h=mt(l),p=h*n+d*r;return[ha(f*s-p*o,d*n-h*r),Ko(p*s+f*o)]}return i.invert=function(a,l){var u=wt(l),d=wt(a)*u,f=mt(a)*u,h=mt(l),p=h*s-f*o;return[ha(f*s+h*o,d*n+p*r),Ko(p*n-d*r)]},i}function kye(e){e=nH(e[0]*mn,e[1]*mn,e.length>2?e[2]*mn:0);function t(n){return n=e(n[0]*mn,n[1]*mn),n[0]*=xs,n[1]*=xs,n}return t.invert=function(n){return n=e.invert(n[0]*mn,n[1]*mn),n[0]*=xs,n[1]*=xs,n},t}function Eye(e,t,n,r,s,o){if(n){var i=wt(t),a=mt(t),l=r*n;s==null?(s=t+r*vo,o=t-l/2):(s=xF(i,s),o=xF(i,o),(r>0?s<o:s>o)&&(s+=r*vo));for(var u,d=s;r>0?d>o:d<o;d-=l)u=kk([i,-a*wt(d),-a*mt(d)]),e.point(u[0],u[1])}}function xF(e,t){t=Oh(t),t[0]-=e,Ek(t);var n=tH(-t[1]);return((-t[2]<0?-n:n)+vo-at)%vo}function rH(){var e=[],t;return{point:function(n,r,s){t.push([n,r,s])},lineStart:function(){e.push(t=[])},lineEnd:Tr,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function Fy(e,t){return Gt(e[0]-t[0])<at&&Gt(e[1]-t[1])<at}function j0(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 sH(e,t,n,r,s){var o=[],i=[],a,l;if(e.forEach(function(m){if(!((g=m.length-1)<=0)){var g,b=m[0],x=m[g],y;if(Fy(b,x)){if(!b[2]&&!x[2]){for(s.lineStart(),a=0;a<g;++a)s.point((b=m[a])[0],b[1]);s.lineEnd();return}x[0]+=2*at}o.push(y=new j0(b,m,null,!0)),i.push(y.o=new j0(b,null,y,!1)),o.push(y=new j0(x,m,null,!1)),i.push(y.o=new j0(x,null,y,!0))}}),!!o.length){for(i.sort(t),yF(o),yF(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,p=!0;h.v;)if((h=h.n)===u)return;d=h.z,s.lineStart();do{if(h.v=h.o.v=!0,h.e){if(p)for(a=0,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(p)for(d=h.p.z,a=d.length-1;a>=0;--a)s.point((f=d[a])[0],f[1]);else r(h.x,h.p.x,-1,s);h=h.p}h=h.o,d=h.z,p=!p}while(!h.v);s.lineEnd()}}}function yF(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 hN(e){return Gt(e[0])<=Rt?e[0]:Lo(e[0])*((Gt(e[0])+Rt)%vo-Rt)}function oH(e,t){var n=hN(t),r=t[1],s=mt(r),o=[mt(n),-wt(n),0],i=0,a=0,l=new Nc;s===1?r=er+at:s===-1&&(r=-er-at);for(var u=0,d=e.length;u<d;++u)if(h=(f=e[u]).length)for(var f,h,p=f[h-1],m=hN(p),g=p[1]/2+dF,b=mt(g),x=wt(g),y=0;y<h;++y,m=w,b=C,x=j,p=v){var v=f[y],w=hN(v),S=v[1]/2+dF,C=mt(S),j=wt(S),D=w-m,k=D>=0?1:-1,_=k*D,M=_>Rt,R=b*C;if(l.add(ha(R*k*mt(_),x*j+R*wt(_))),i+=M?D+k*vo:D,M^m>=n^w>=n){var O=Iv(Oh(p),Oh(v));Ek(O);var T=Iv(o,O);Ek(T);var I=(M^D>=0?-1:1)*Ko(T[2]);(r>I||r===I&&(O[0]||O[1]))&&(a+=M^D>=0?1:-1)}}return(i<-at||i<at&&l<-bM)^a&1}function iH(e,t,n,r){return function(s){var o=t(s),i=rH(),a=t(i),l=!1,u,d,f,h={point:p,lineStart:g,lineEnd:b,polygonStart:function(){h.point=x,h.lineStart=y,h.lineEnd=v,d=[],u=[]},polygonEnd:function(){h.point=p,h.lineStart=g,h.lineEnd=b,d=JV(d);var w=oH(u,r);d.length?(l||(s.polygonStart(),l=!0),sH(d,Dye,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 p(w,S){e(w,S)&&s.point(w,S)}function m(w,S){o.point(w,S)}function g(){h.point=m,o.lineStart()}function b(){h.point=p,o.lineEnd()}function x(w,S){f.push([w,S]),a.point(w,S)}function y(){a.lineStart(),f=[]}function v(){x(f[0][0],f[0][1]),a.lineEnd();var w=a.clean(),S=i.result(),C,j=S.length,D,k,_;if(f.pop(),u.push(f),f=null,!!j){if(w&1){if(k=S[0],(D=k.length-1)>0){for(l||(s.polygonStart(),l=!0),s.lineStart(),C=0;C<D;++C)s.point((_=k[C])[0],_[1]);s.lineEnd()}return}j>1&&w&2&&S.push(S.pop().concat(S.shift())),d.push(S.filter(_ye))}}return h}}function _ye(e){return e.length>1}function Dye(e,t){return((e=e.x)[0]<0?e[1]-er-at:er-e[1])-((t=t.x)[0]<0?t[1]-er-at:er-t[1])}const vF=iH(function(){return!0},Mye,Rye,[-Rt,-er]);function Mye(e){var t=NaN,n=NaN,r=NaN,s;return{lineStart:function(){e.lineStart(),s=1},point:function(o,i){var a=o>0?Rt:-Rt,l=Gt(o-t);Gt(l-Rt)<at?(e.point(t,n=(n+i)/2>0?er:-er),e.point(r,n),e.lineEnd(),e.lineStart(),e.point(a,n),e.point(o,n),s=0):r!==a&&l>=Rt&&(Gt(t-r)<at&&(t-=r*at),Gt(o-a)<at&&(o-=a*at),n=Tye(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 Tye(e,t,n,r){var s,o,i=mt(e-n);return Gt(i)>at?Np((mt(t)*(o=wt(r))*mt(n)-mt(r)*(s=wt(t))*mt(e))/(s*o*i)):(t+r)/2}function Rye(e,t,n,r){var s;if(e==null)s=n*er,r.point(-Rt,s),r.point(0,s),r.point(Rt,s),r.point(Rt,0),r.point(Rt,-s),r.point(0,-s),r.point(-Rt,-s),r.point(-Rt,0),r.point(-Rt,s);else if(Gt(e[0]-t[0])>at){var o=e[0]<t[0]?Rt:-Rt;s=n*o/2,r.point(-o,s),r.point(0,s),r.point(o,s)}else r.point(t[0],t[1])}function Iye(e){var t=wt(e),n=2*mn,r=t>0,s=Gt(t)>at;function o(d,f,h,p){Eye(p,e,n,h,d,f)}function i(d,f){return wt(d)*wt(f)>t}function a(d){var f,h,p,m,g;return{lineStart:function(){m=p=!1,g=1},point:function(b,x){var y=[b,x],v,w=i(b,x),S=r?w?0:u(b,x):w?u(b+(b<0?Rt:-Rt),x):0;if(!f&&(m=p=w)&&d.lineStart(),w!==p&&(v=l(f,y),(!v||Fy(f,v)||Fy(y,v))&&(y[2]=1)),w!==p)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 C;!(S&h)&&(C=l(y,f,!0))&&(g=0,r?(d.lineStart(),d.point(C[0][0],C[0][1]),d.point(C[1][0],C[1][1]),d.lineEnd()):(d.point(C[1][0],C[1][1]),d.lineEnd(),d.lineStart(),d.point(C[0][0],C[0][1],3)))}w&&(!f||!Fy(f,y))&&d.point(y[0],y[1]),f=y,p=w,h=S},lineEnd:function(){p&&d.lineEnd(),f=null},clean:function(){return g|(m&&p)<<1}}}function l(d,f,h){var p=Oh(d),m=Oh(f),g=[1,0,0],b=Iv(p,m),x=C0(b,b),y=b[0],v=x-y*y;if(!v)return!h&&d;var w=t*x/v,S=-t*y/v,C=Iv(g,b),j=N0(g,w),D=N0(b,S);fN(j,D);var k=C,_=C0(j,k),M=C0(k,k),R=_*_-M*(C0(j,j)-1);if(!(R<0)){var O=_s(R),T=N0(k,(-_-O)/M);if(fN(T,j),T=kk(T),!h)return T;var I=d[0],F=f[0],z=d[1],B=f[1],$;F<I&&($=I,I=F,F=$);var P=F-I,V=Gt(P-Rt)<at,L=V||P<at;if(!V&&B<z&&($=z,z=B,B=$),L?V?z+B>0^T[1]<(Gt(T[0]-I)<at?z:B):z<=T[1]&&T[1]<=B:P>Rt^(I<=T[0]&&T[0]<=F)){var A=N0(k,(-_+O)/M);return fN(A,j),[T,kk(A)]}}}function u(d,f){var h=r?e:Rt-e,p=0;return d<-h?p|=1:d>h&&(p|=2),f<-h?p|=4:f>h&&(p|=8),p}return iH(i,a,o,r?[0,-e]:[-Rt,e-Rt])}function Aye(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,p=u-a,m;if(m=n-i,!(!h&&m>0)){if(m/=h,h<0){if(m<d)return;m<f&&(f=m)}else if(h>0){if(m>f)return;m>d&&(d=m)}if(m=s-i,!(!h&&m<0)){if(m/=h,h<0){if(m>f)return;m>d&&(d=m)}else if(h>0){if(m<d)return;m<f&&(f=m)}if(m=r-a,!(!p&&m>0)){if(m/=p,p<0){if(m<d)return;m<f&&(f=m)}else if(p>0){if(m>f)return;m>d&&(d=m)}if(m=o-a,!(!p&&m<0)){if(m/=p,p<0){if(m>f)return;m>d&&(d=m)}else if(p>0){if(m<d)return;m<f&&(f=m)}return d>0&&(e[0]=i+d*h,e[1]=a+d*p),f<1&&(t[0]=i+f*h,t[1]=a+f*p),!0}}}}}var Rm=1e9,k0=-Rm;function Pye(e,t,n,r){function s(u,d){return e<=u&&u<=n&&t<=d&&d<=r}function o(u,d,f,h){var p=0,m=0;if(u==null||(p=i(u,f))!==(m=i(d,f))||l(u,d)<0^f>0)do h.point(p===0||p===3?e:n,p>1?r:t);while((p=(p+f+4)%4)!==m);else h.point(d[0],d[1])}function i(u,d){return Gt(u[0]-e)<at?d>0?0:3:Gt(u[0]-n)<at?d>0?2:1:Gt(u[1]-t)<at?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=rH(),h,p,m,g,b,x,y,v,w,S,C,j={point:D,lineStart:R,lineEnd:O,polygonStart:_,polygonEnd:M};function D(I,F){s(I,F)&&d.point(I,F)}function k(){for(var I=0,F=0,z=p.length;F<z;++F)for(var B=p[F],$=1,P=B.length,V=B[0],L,A,W=V[0],U=V[1];$<P;++$)L=W,A=U,V=B[$],W=V[0],U=V[1],A<=r?U>r&&(W-L)*(r-A)>(U-A)*(e-L)&&++I:U<=r&&(W-L)*(r-A)<(U-A)*(e-L)&&--I;return I}function _(){d=f,h=[],p=[],C=!0}function M(){var I=k(),F=C&&I,z=(h=JV(h)).length;(F||z)&&(u.polygonStart(),F&&(u.lineStart(),o(null,null,1,u),u.lineEnd()),z&&sH(h,a,I,o,u),u.polygonEnd()),d=u,h=p=m=null}function R(){j.point=T,p&&p.push(m=[]),S=!0,w=!1,y=v=NaN}function O(){h&&(T(g,b),x&&w&&f.rejoin(),h.push(f.result())),j.point=D,w&&d.lineEnd()}function T(I,F){var z=s(I,F);if(p&&m.push([I,F]),S)g=I,b=F,x=z,S=!1,z&&(d.lineStart(),d.point(I,F));else if(z&&w)d.point(I,F);else{var B=[y=Math.max(k0,Math.min(Rm,y)),v=Math.max(k0,Math.min(Rm,v))],$=[I=Math.max(k0,Math.min(Rm,I)),F=Math.max(k0,Math.min(Rm,F))];Aye(B,$,e,t,n,r)?(w||(d.lineStart(),d.point(B[0],B[1])),d.point($[0],$[1]),z||d.lineEnd(),C=!1):z&&(d.lineStart(),d.point(I,F),C=!1)}y=I,v=F,w=z}return j}}var Mk,Tk,$y,Ly,Fh={sphere:Tr,point:Tr,lineStart:Oye,lineEnd:Tr,polygonStart:Tr,polygonEnd:Tr};function Oye(){Fh.point=$ye,Fh.lineEnd=Fye}function Fye(){Fh.point=Fh.lineEnd=Tr}function $ye(e,t){e*=mn,t*=mn,Tk=e,$y=mt(t),Ly=wt(t),Fh.point=Lye}function Lye(e,t){e*=mn,t*=mn;var n=mt(t),r=wt(t),s=Gt(e-Tk),o=wt(s),i=mt(s),a=r*i,l=Ly*n-$y*r*o,u=$y*n+Ly*r*o;Mk.add(ha(_s(a*a+l*l),u)),Tk=e,$y=n,Ly=r}function zye(e){return Mk=new Nc,ju(e,Fh),+Mk}var Rk=[null,null],Bye={type:"LineString",coordinates:Rk};function Ik(e,t){return Rk[0]=e,Rk[1]=t,zye(Bye)}var wF={Feature:function(e,t){return Av(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,s=n.length;++r<s;)if(Av(n[r].geometry,t))return!0;return!1}},SF={Sphere:function(){return!0},Point:function(e,t){return CF(e.coordinates,t)},MultiPoint:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(CF(n[r],t))return!0;return!1},LineString:function(e,t){return NF(e.coordinates,t)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(NF(n[r],t))return!0;return!1},Polygon:function(e,t){return jF(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(jF(n[r],t))return!0;return!1},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,s=n.length;++r<s;)if(Av(n[r],t))return!0;return!1}};function Av(e,t){return e&&SF.hasOwnProperty(e.type)?SF[e.type](e,t):!1}function CF(e,t){return Ik(e,t)===0}function NF(e,t){for(var n,r,s,o=0,i=e.length;o<i;o++){if(r=Ik(e[o],t),r===0||o>0&&(s=Ik(e[o],e[o-1]),s>0&&n<=s&&r<=s&&(n+r-s)*(1-Math.pow((n-r)/s,2))<bM*s))return!0;n=r}return!1}function jF(e,t){return!!oH(e.map(Vye),aH(t))}function Vye(e){return e=e.map(aH),e.pop(),e}function aH(e){return[e[0]*mn,e[1]*mn]}function Hye(e,t){return(e&&wF.hasOwnProperty(e.type)?wF[e.type]:Av)(e,t)}function kF(e,t,n){var r=Of(e,t-at,n).concat(t);return function(s){return r.map(function(o){return[s,o]})}}function EF(e,t,n){var r=Of(e,t-at,n).concat(t);return function(s){return r.map(function(o){return[o,s]})}}function lH(){var e,t,n,r,s,o,i,a,l=10,u=l,d=90,f=360,h,p,m,g,b=2.5;function x(){return{type:"MultiLineString",coordinates:y()}}function y(){return Of(S0(r/d)*d,n,d).map(m).concat(Of(S0(a/f)*f,i,f).map(g)).concat(Of(S0(t/l)*l,e,l).filter(function(v){return Gt(v%d)>at}).map(h)).concat(Of(S0(o/u)*u,s,u).filter(function(v){return Gt(v%f)>at}).map(p))}return x.lines=function(){return y().map(function(v){return{type:"LineString",coordinates:v}})},x.outline=function(){return{type:"Polygon",coordinates:[m(r).concat(g(i).slice(1),m(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=kF(o,s,90),p=EF(t,e,b),m=kF(a,i,90),g=EF(r,n,b),x):b},x.extentMajor([[-180,-90+at],[180,90-at]]).extentMinor([[-180,-80-at],[180,80+at]])}function Uye(){return lH()()}const Ak=e=>e;var pN=new Nc,Pk=new Nc,cH,uH,Ok,Fk,za={point:Tr,lineStart:Tr,lineEnd:Tr,polygonStart:function(){za.lineStart=Wye,za.lineEnd=Yye},polygonEnd:function(){za.lineStart=za.lineEnd=za.point=Tr,pN.add(Gt(Pk)),Pk=new Nc},result:function(){var e=pN/2;return pN=new Nc,e}};function Wye(){za.point=qye}function qye(e,t){za.point=dH,cH=Ok=e,uH=Fk=t}function dH(e,t){Pk.add(Fk*e-Ok*t),Ok=e,Fk=t}function Yye(){dH(cH,uH)}var $h=1/0,Pv=$h,Hg=-$h,Ov=Hg,Fv={point:Gye,lineStart:Tr,lineEnd:Tr,polygonStart:Tr,polygonEnd:Tr,result:function(){var e=[[$h,Pv],[Hg,Ov]];return Hg=Ov=-(Pv=$h=1/0),e}};function Gye(e,t){e<$h&&($h=e),e>Hg&&(Hg=e),t<Pv&&(Pv=t),t>Ov&&(Ov=t)}var $k=0,Lk=0,Im=0,$v=0,Lv=0,Ff=0,zk=0,Bk=0,Am=0,fH,hH,ea,ta,$o={point:Dd,lineStart:_F,lineEnd:DF,polygonStart:function(){$o.lineStart=Xye,$o.lineEnd=Qye},polygonEnd:function(){$o.point=Dd,$o.lineStart=_F,$o.lineEnd=DF},result:function(){var e=Am?[zk/Am,Bk/Am]:Ff?[$v/Ff,Lv/Ff]:Im?[$k/Im,Lk/Im]:[NaN,NaN];return $k=Lk=Im=$v=Lv=Ff=zk=Bk=Am=0,e}};function Dd(e,t){$k+=e,Lk+=t,++Im}function _F(){$o.point=Kye}function Kye(e,t){$o.point=Zye,Dd(ea=e,ta=t)}function Zye(e,t){var n=e-ea,r=t-ta,s=_s(n*n+r*r);$v+=s*(ea+e)/2,Lv+=s*(ta+t)/2,Ff+=s,Dd(ea=e,ta=t)}function DF(){$o.point=Dd}function Xye(){$o.point=Jye}function Qye(){pH(fH,hH)}function Jye(e,t){$o.point=pH,Dd(fH=ea=e,hH=ta=t)}function pH(e,t){var n=e-ea,r=t-ta,s=_s(n*n+r*r);$v+=s*(ea+e)/2,Lv+=s*(ta+t)/2,Ff+=s,s=ta*e-ea*t,zk+=s*(ea+e),Bk+=s*(ta+t),Am+=s*3,Dd(ea=e,ta=t)}function mH(e){this._context=e}mH.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,vo);break}}},result:Tr};var Vk=new Nc,mN,gH,bH,Pm,Om,Ug={point:Tr,lineStart:function(){Ug.point=eve},lineEnd:function(){mN&&xH(gH,bH),Ug.point=Tr},polygonStart:function(){mN=!0},polygonEnd:function(){mN=null},result:function(){var e=+Vk;return Vk=new Nc,e}};function eve(e,t){Ug.point=xH,gH=Pm=e,bH=Om=t}function xH(e,t){Pm-=e,Om-=t,Vk.add(_s(Pm*Pm+Om*Om)),Pm=e,Om=t}let MF,zv,TF,RF;class IF{constructor(t){this._append=t==null?yH:tve(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!==TF||this._append!==zv){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`,TF=r,zv=this._append,RF=this._,this._=s}this._+=RF;break}}}result(){const t=this._;return this._="",t.length?t:null}}function yH(e){let t=1;this._+=e[0];for(const n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function tve(e){const t=Math.floor(e);if(!(t>=0))throw new RangeError(`invalid digits: ${e}`);if(t>15)return yH;if(t!==MF){const n=10**t;MF=t,zv=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 zv}function AF(e,t){let n=3,r=4.5,s,o;function i(a){return a&&(typeof r=="function"&&o.pointRadius(+r.apply(this,arguments)),ju(a,s(o))),o.result()}return i.area=function(a){return ju(a,s(za)),za.result()},i.measure=function(a){return ju(a,s(Ug)),Ug.result()},i.bounds=function(a){return ju(a,s(Fv)),Fv.result()},i.centroid=function(a){return ju(a,s($o)),$o.result()},i.projection=function(a){return arguments.length?(s=a==null?(e=null,Ak):(e=a).stream,i):e},i.context=function(a){return arguments.length?(o=a==null?(t=null,new IF(n)):new mH(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 IF(n)),i},i.projection(e).digits(n).context(t)}function yM(e){return function(t){var n=new Hk;for(var r in e)n[r]=e[r];return n.stream=t,n}}function Hk(){}Hk.prototype={constructor:Hk,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 vM(e,t,n){var r=e.clipExtent&&e.clipExtent();return e.scale(150).translate([0,0]),r!=null&&e.clipExtent(null),ju(n,e.stream(Fv)),t(Fv.result()),r!=null&&e.clipExtent(r),e}function wM(e,t,n){return vM(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 wM(e,[[0,0],t],n)}function wH(e,t,n){return vM(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 SH(e,t,n){return vM(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 PF=16,nve=wt(30*mn);function OF(e,t){return+t?sve(e,t):rve(e)}function rve(e){return yM({point:function(t,n){t=e(t,n),this.stream.point(t[0],t[1])}})}function sve(e,t){function n(r,s,o,i,a,l,u,d,f,h,p,m,g,b){var x=u-r,y=d-s,v=x*x+y*y;if(v>4*t&&g--){var w=i+h,S=a+p,C=l+m,j=_s(w*w+S*S+C*C),D=Ko(C/=j),k=Gt(Gt(C)-1)<at||Gt(o-f)<at?(o+f)/2:ha(S,w),_=e(k,D),M=_[0],R=_[1],O=M-r,T=R-s,I=y*O-x*T;(I*I/v>t||Gt((x*O+y*T)/v-.5)>.3||i*h+a*p+l*m<nve)&&(n(r,s,o,i,a,l,M,R,k,w/=j,S/=j,C,g,b),b.point(M,R),n(M,R,k,w,S,C,u,d,f,h,p,m,g,b))}}return function(r){var s,o,i,a,l,u,d,f,h,p,m,g,b={point:x,lineStart:y,lineEnd:w,polygonStart:function(){r.polygonStart(),b.lineStart=S},polygonEnd:function(){r.polygonEnd(),b.lineStart=y}};function x(D,k){D=e(D,k),r.point(D[0],D[1])}function y(){f=NaN,b.point=v,r.lineStart()}function v(D,k){var _=Oh([D,k]),M=e(D,k);n(f,h,d,p,m,g,f=M[0],h=M[1],d=D,p=_[0],m=_[1],g=_[2],PF,r),r.point(f,h)}function w(){b.point=x,r.lineEnd()}function S(){y(),b.point=C,b.lineEnd=j}function C(D,k){v(s=D,k),o=f,i=h,a=p,l=m,u=g,b.point=v}function j(){n(f,h,d,p,m,g,o,i,s,a,l,u,PF,r),b.lineEnd=w,w()}return b}}var ove=yM({point:function(e,t){this.stream.point(e*mn,t*mn)}});function ive(e){return yM({point:function(t,n){var r=e(t,n);return this.stream.point(r[0],r[1])}})}function ave(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 FF(e,t,n,r,s,o){if(!o)return ave(e,t,n,r,s);var i=wt(o),a=mt(o),l=i*e,u=a*e,d=i/e,f=a/e,h=(a*n-i*t)/e,p=(a*t+i*n)/e;function m(g,b){return g*=r,b*=s,[l*g-u*b+t,n-u*g-l*b]}return m.invert=function(g,b){return[r*(d*g-f*b+h),s*(p-f*g-d*b)]},m}function xl(e){return CH(function(){return e})()}function CH(e){var t,n=150,r=480,s=250,o=0,i=0,a=0,l=0,u=0,d,f=0,h=1,p=1,m=null,g=vF,b=null,x,y,v,w=Ak,S=.5,C,j,D,k,_;function M(I){return D(I[0]*mn,I[1]*mn)}function R(I){return I=D.invert(I[0],I[1]),I&&[I[0]*xs,I[1]*xs]}M.stream=function(I){return k&&_===I?k:k=ove(ive(d)(g(C(w(_=I)))))},M.preclip=function(I){return arguments.length?(g=I,m=void 0,T()):g},M.postclip=function(I){return arguments.length?(w=I,b=x=y=v=null,T()):w},M.clipAngle=function(I){return arguments.length?(g=+I?Iye(m=I*mn):(m=null,vF),T()):m*xs},M.clipExtent=function(I){return arguments.length?(w=I==null?(b=x=y=v=null,Ak):Pye(b=+I[0][0],x=+I[0][1],y=+I[1][0],v=+I[1][1]),T()):b==null?null:[[b,x],[y,v]]},M.scale=function(I){return arguments.length?(n=+I,O()):n},M.translate=function(I){return arguments.length?(r=+I[0],s=+I[1],O()):[r,s]},M.center=function(I){return arguments.length?(o=I[0]%360*mn,i=I[1]%360*mn,O()):[o*xs,i*xs]},M.rotate=function(I){return arguments.length?(a=I[0]%360*mn,l=I[1]%360*mn,u=I.length>2?I[2]%360*mn:0,O()):[a*xs,l*xs,u*xs]},M.angle=function(I){return arguments.length?(f=I%360*mn,O()):f*xs},M.reflectX=function(I){return arguments.length?(h=I?-1:1,O()):h<0},M.reflectY=function(I){return arguments.length?(p=I?-1:1,O()):p<0},M.precision=function(I){return arguments.length?(C=OF(j,S=I*I),T()):_s(S)},M.fitExtent=function(I,F){return wM(M,I,F)},M.fitSize=function(I,F){return vH(M,I,F)},M.fitWidth=function(I,F){return wH(M,I,F)},M.fitHeight=function(I,F){return SH(M,I,F)};function O(){var I=FF(n,0,0,h,p,f).apply(null,t(o,i)),F=FF(n,r-I[0],s-I[1],h,p,f);return d=nH(a,l,u),j=_k(t,F),D=_k(d,j),C=OF(j,S),T()}function T(){return k=_=null,M}return function(){return t=e.apply(this,arguments),M.invert=t.invert&&R,O()}}function SM(e){var t=0,n=Rt/3,r=CH(e),s=r(t,n);return s.parallels=function(o){return arguments.length?r(t=o[0]*mn,n=o[1]*mn):[t*xs,n*xs]},s}function lve(e){var t=wt(e);function n(r,s){return[r*t,mt(s)/t]}return n.invert=function(r,s){return[r/t,Ko(s*t)]},n}function cve(e,t){var n=mt(e),r=(n+mt(t))/2;if(Gt(r)<at)return lve(e);var s=1+n*(2*r-n),o=_s(s)/r;function i(a,l){var u=_s(s-2*r*mt(l))/r;return[u*mt(a*=r),o-u*wt(a)]}return i.invert=function(a,l){var u=o-l,d=ha(a,Gt(u))*Lo(u);return u*r<0&&(d-=Rt*Lo(a)*Lo(u)),[d/r,Ko((s-(a*a+u*u)*r*r)/(2*r))]},i}function Bv(){return SM(cve).scale(155.424).center([0,33.6442])}function NH(){return Bv().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function uve(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 dve(){var e,t,n=NH(),r,s=Bv().rotate([154,0]).center([-2,58.5]).parallels([55,65]),o,i=Bv().rotate([157,0]).center([-3,19.9]).parallels([8,18]),a,l,u={point:function(h,p){l=[h,p]}};function d(h){var p=h[0],m=h[1];return l=null,r.point(p,m),l||(o.point(p,m),l)||(a.point(p,m),l)}d.invert=function(h){var p=n.scale(),m=n.translate(),g=(h[0]-m[0])/p,b=(h[1]-m[1])/p;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=uve([n.stream(t=h),s.stream(h),i.stream(h)])},d.precision=function(h){return arguments.length?(n.precision(h),s.precision(h),i.precision(h),f()):n.precision()},d.scale=function(h){return arguments.length?(n.scale(h),s.scale(h*.35),i.scale(h),d.translate(n.translate())):n.scale()},d.translate=function(h){if(!arguments.length)return n.translate();var p=n.scale(),m=+h[0],g=+h[1];return r=n.translate(h).clipExtent([[m-.455*p,g-.238*p],[m+.455*p,g+.238*p]]).stream(u),o=s.translate([m-.307*p,g+.201*p]).clipExtent([[m-.425*p+at,g+.12*p+at],[m-.214*p-at,g+.234*p-at]]).stream(u),a=i.translate([m-.205*p,g+.212*p]).clipExtent([[m-.214*p+at,g+.166*p+at],[m-.115*p-at,g+.234*p-at]]).stream(u),f()},d.fitExtent=function(h,p){return wM(d,h,p)},d.fitSize=function(h,p){return vH(d,h,p)},d.fitWidth=function(h,p){return wH(d,h,p)},d.fitHeight=function(h,p){return SH(d,h,p)};function f(){return e=t=null,d}return d.scale(1070)}function jH(e){return function(t,n){var r=wt(t),s=wt(n),o=e(r*s);return o===1/0?[2,0]:[o*s*mt(t),o*mt(n)]}}function Zb(e){return function(t,n){var r=_s(t*t+n*n),s=e(r),o=mt(s),i=wt(s);return[ha(t*o,r*i),Ko(r&&n*o/r)]}}var kH=jH(function(e){return _s(2/(1+e))});kH.invert=Zb(function(e){return 2*Ko(e/2)});function fve(){return xl(kH).scale(124.75).clipAngle(180-.001)}var EH=jH(function(e){return(e=tH(e))&&e/mt(e)});EH.invert=Zb(function(e){return e});function hve(){return xl(EH).scale(79.4188).clipAngle(180-.001)}function I1(e,t){return[e,Tv(xM((er+t)/2))]}I1.invert=function(e,t){return[e,2*Np(eH(t))-er]};function pve(){return _H(I1).scale(961/vo)}function _H(e){var t=xl(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=Rt*r(),h=t(kye(t.rotate()).invert([0,0]));return o(i==null?[[h[0]-f,h[1]-f],[h[0]+f,h[1]+f]]:e===I1?[[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 E0(e){return xM((er+e)/2)}function mve(e,t){var n=wt(e),r=e===t?mt(e):Tv(n/wt(t))/Tv(E0(t)/E0(e)),s=n*dN(E0(e),r)/r;if(!r)return I1;function o(i,a){s>0?a<-er+at&&(a=-er+at):a>er-at&&(a=er-at);var l=s/dN(E0(a),r);return[l*mt(r*i),s-l*wt(r*i)]}return o.invert=function(i,a){var l=s-a,u=Lo(r)*_s(i*i+l*l),d=ha(i,Gt(l))*Lo(l);return l*r<0&&(d-=Rt*Lo(i)*Lo(l)),[d/r,2*Np(dN(s/u,1/r))-er]},o}function gve(){return SM(mve).scale(109.5).parallels([30,30])}function Vv(e,t){return[e,t]}Vv.invert=Vv;function bve(){return xl(Vv).scale(152.63)}function xve(e,t){var n=wt(e),r=e===t?mt(e):(n-wt(t))/(t-e),s=n/r+e;if(Gt(r)<at)return Vv;function o(i,a){var l=s-a,u=r*i;return[l*mt(u),s-l*wt(u)]}return o.invert=function(i,a){var l=s-a,u=ha(i,Gt(l))*Lo(l);return l*r<0&&(u-=Rt*Lo(i)*Lo(l)),[u/r,s-Lo(r)*_s(i*i+l*l)]},o}function yve(){return SM(xve).scale(131.154).center([0,13.9389])}var ng=1.340264,rg=-.081106,sg=893e-6,og=.003796,Hv=_s(3)/2,vve=12;function DH(e,t){var n=Ko(Hv*mt(t)),r=n*n,s=r*r*r;return[e*wt(n)/(Hv*(ng+3*rg*r+s*(7*sg+9*og*r))),n*(ng+rg*r+s*(sg+og*r))]}DH.invert=function(e,t){for(var n=t,r=n*n,s=r*r*r,o=0,i,a,l;o<vve&&(a=n*(ng+rg*r+s*(sg+og*r))-t,l=ng+3*rg*r+s*(7*sg+9*og*r),n-=i=a/l,r=n*n,s=r*r*r,!(Gt(i)<bM));++o);return[Hv*e*(ng+3*rg*r+s*(7*sg+9*og*r))/wt(n),Ko(mt(n)/Hv)]};function wve(){return xl(DH).scale(177.158)}function MH(e,t){var n=wt(t),r=wt(e)*n;return[n*mt(e)/r,mt(t)/r]}MH.invert=Zb(Np);function Sve(){return xl(MH).scale(144.049).clipAngle(60)}function TH(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)))]}TH.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(Gt(s)>at&&--r>0);return[e/(.8707+(o=n*n)*(-.131979+o*(-.013791+o*o*o*(.003971-.001529*o)))),n]};function Cve(){return xl(TH).scale(175.295)}function RH(e,t){return[wt(t)*mt(e),mt(t)]}RH.invert=Zb(Ko);function Nve(){return xl(RH).scale(249.5).clipAngle(90+at)}function IH(e,t){var n=wt(t),r=1+wt(e)*n;return[n*mt(e)/r,mt(t)/r]}IH.invert=Zb(function(e){return 2*Np(e)});function jve(){return xl(IH).scale(250).clipAngle(142)}function AH(e,t){return[Tv(xM((er+t)/2)),-e]}AH.invert=function(e,t){return[-t,2*Np(eH(e))-er]};function kve(){var e=_H(AH),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 tn(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 A1(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function CM(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function jp(){}var Md=.7,Lh=1/Md,eh="\\s*([+-]?\\d+)\\s*",Wg="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",aa="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Eve=/^#([0-9a-f]{3,8})$/,_ve=new RegExp(`^rgb\\(${eh},${eh},${eh}\\)$`),Dve=new RegExp(`^rgb\\(${aa},${aa},${aa}\\)$`),Mve=new RegExp(`^rgba\\(${eh},${eh},${eh},${Wg}\\)$`),Tve=new RegExp(`^rgba\\(${aa},${aa},${aa},${Wg}\\)$`),Rve=new RegExp(`^hsl\\(${Wg},${aa},${aa}\\)$`),Ive=new RegExp(`^hsla\\(${Wg},${aa},${aa},${Wg}\\)$`),$F={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};A1(jp,NM,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:LF,formatHex:LF,formatHex8:Ave,formatHsl:Pve,formatRgb:zF,toString:zF});function LF(){return this.rgb().formatHex()}function Ave(){return this.rgb().formatHex8()}function Pve(){return OH(this).formatHsl()}function zF(){return this.rgb().formatRgb()}function NM(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=Eve.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?BF(t):n===3?new ns(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?_0(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?_0(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=_ve.exec(e))?new ns(t[1],t[2],t[3],1):(t=Dve.exec(e))?new ns(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Mve.exec(e))?_0(t[1],t[2],t[3],t[4]):(t=Tve.exec(e))?_0(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Rve.exec(e))?UF(t[1],t[2]/100,t[3]/100,1):(t=Ive.exec(e))?UF(t[1],t[2]/100,t[3]/100,t[4]):$F.hasOwnProperty(e)?BF($F[e]):e==="transparent"?new ns(NaN,NaN,NaN,0):null}function BF(e){return new ns(e>>16&255,e>>8&255,e&255,1)}function _0(e,t,n,r){return r<=0&&(e=t=n=NaN),new ns(e,t,n,r)}function PH(e){return e instanceof jp||(e=NM(e)),e?(e=e.rgb(),new ns(e.r,e.g,e.b,e.opacity)):new ns}function qg(e,t,n,r){return arguments.length===1?PH(e):new ns(e,t,n,r??1)}function ns(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}A1(ns,qg,CM(jp,{brighter(e){return e=e==null?Lh:Math.pow(Lh,e),new ns(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Md:Math.pow(Md,e),new ns(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new ns(nd(this.r),nd(this.g),nd(this.b),Uv(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:VF,formatHex:VF,formatHex8:Ove,formatRgb:HF,toString:HF}));function VF(){return`#${Au(this.r)}${Au(this.g)}${Au(this.b)}`}function Ove(){return`#${Au(this.r)}${Au(this.g)}${Au(this.b)}${Au((isNaN(this.opacity)?1:this.opacity)*255)}`}function HF(){const e=Uv(this.opacity);return`${e===1?"rgb(":"rgba("}${nd(this.r)}, ${nd(this.g)}, ${nd(this.b)}${e===1?")":`, ${e})`}`}function Uv(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function nd(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Au(e){return e=nd(e),(e<16?"0":"")+e.toString(16)}function UF(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ci(e,t,n,r)}function OH(e){if(e instanceof ci)return new ci(e.h,e.s,e.l,e.opacity);if(e instanceof jp||(e=NM(e)),!e)return new ci;if(e instanceof ci)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 ci(i,a,l,e.opacity)}function Fve(e,t,n,r){return arguments.length===1?OH(e):new ci(e,t,n,r??1)}function ci(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}A1(ci,Fve,CM(jp,{brighter(e){return e=e==null?Lh:Math.pow(Lh,e),new ci(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Md:Math.pow(Md,e),new ci(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 ns(gN(e>=240?e-240:e+120,s,r),gN(e,s,r),gN(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new ci(WF(this.h),D0(this.s),D0(this.l),Uv(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=Uv(this.opacity);return`${e===1?"hsl(":"hsla("}${WF(this.h)}, ${D0(this.s)*100}%, ${D0(this.l)*100}%${e===1?")":`, ${e})`}`}}));function WF(e){return e=(e||0)%360,e<0?e+360:e}function D0(e){return Math.max(0,Math.min(1,e||0))}function gN(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 $ve=Math.PI/180,Lve=180/Math.PI;var FH=-.14861,jM=1.78277,kM=-.29227,P1=-.90649,Yg=1.97294,qF=Yg*P1,YF=Yg*jM,GF=jM*kM-P1*FH;function zve(e){if(e instanceof rd)return new rd(e.h,e.s,e.l,e.opacity);e instanceof ns||(e=PH(e));var t=e.r/255,n=e.g/255,r=e.b/255,s=(GF*r+qF*t-YF*n)/(GF+qF-YF),o=r-s,i=(Yg*(n-s)-kM*o)/P1,a=Math.sqrt(i*i+o*o)/(Yg*s*(1-s)),l=a?Math.atan2(i,o)*Lve-120:NaN;return new rd(l<0?l+360:l,a,s,e.opacity)}function pa(e,t,n,r){return arguments.length===1?zve(e):new rd(e,t,n,r??1)}function rd(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}A1(rd,pa,CM(jp,{brighter(e){return e=e==null?Lh:Math.pow(Lh,e),new rd(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Md:Math.pow(Md,e),new rd(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=isNaN(this.h)?0:(this.h+120)*$ve,t=+this.l,n=isNaN(this.s)?0:this.s*t*(1-t),r=Math.cos(e),s=Math.sin(e);return new ns(255*(t+n*(FH*r+jM*s)),255*(t+n*(kM*r+P1*s)),255*(t+n*(Yg*r)),this.opacity)}}));function Bve(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 Vve(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 Bve((n-r/t)*t,i,s,o,a)}}const EM=e=>()=>e;function $H(e,t){return function(n){return e+n*t}}function Hve(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 Uve(e,t){var n=t-e;return n?$H(e,n>180||n<-180?n-360*Math.round(n/360):n):EM(isNaN(e)?t:e)}function Wve(e){return(e=+e)==1?th:function(t,n){return n-t?Hve(t,n,e):EM(isNaN(t)?n:t)}}function th(e,t){var n=t-e;return n?$H(e,n):EM(isNaN(e)?t:e)}(function e(t){var n=Wve(t);function r(s,o){var i=n((s=qg(s)).r,(o=qg(o)).r),a=n(s.g,o.g),l=n(s.b,o.b),u=th(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 qve(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=qg(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 Yve=qve(Vve);function LH(e){return function t(n){n=+n;function r(s,o){var i=e((s=pa(s)).h,(o=pa(o)).h),a=th(s.s,o.s),l=th(s.l,o.l),u=th(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)}LH(Uve);var _M=LH(th);const kn=e=>Yve(e[e.length-1]);var Gve=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(tn);const Kve=kn(Gve);var Zve=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(tn);const Xve=kn(Zve);var Qve=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(tn);const Jve=kn(Qve);var ewe=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(tn);const twe=kn(ewe);var nwe=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(tn);const rwe=kn(nwe);var swe=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(tn);const owe=kn(swe);var iwe=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(tn);const awe=kn(iwe);var lwe=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(tn);const cwe=kn(lwe);var uwe=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(tn);const dwe=kn(uwe);var fwe=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(tn);const hwe=kn(fwe);var pwe=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(tn);const mwe=kn(pwe);var gwe=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(tn);const bwe=kn(gwe);var xwe=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(tn);const ywe=kn(xwe);var vwe=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(tn);const wwe=kn(vwe);var Swe=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(tn);const Cwe=kn(Swe);var Nwe=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(tn);const jwe=kn(Nwe);var kwe=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(tn);const Ewe=kn(kwe);var _we=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(tn);const Dwe=kn(_we);var Mwe=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(tn);const Twe=kn(Mwe);var Rwe=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(tn);const Iwe=kn(Rwe);var Awe=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(tn);const Pwe=kn(Awe);var Owe=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(tn);const Fwe=kn(Owe);var $we=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(tn);const Lwe=kn($we);var zwe=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(tn);const Bwe=kn(zwe);var Vwe=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(tn);const Hwe=kn(Vwe);var Uwe=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(tn);const Wwe=kn(Uwe);var qwe=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(tn);const Ywe=kn(qwe);function Gwe(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 Kwe=_M(pa(300,.5,0),pa(-240,.5,1));var Zwe=_M(pa(-100,.75,.35),pa(80,1.5,.8)),Xwe=_M(pa(260,.75,.35),pa(80,1.5,.8)),M0=pa();function Qwe(e){(e<0||e>1)&&(e-=Math.floor(e));var t=Math.abs(e-.5);return M0.h=360*e-100,M0.s=1.5-1.5*t,M0.l=.8-.9*t,M0+""}var T0=qg(),Jwe=Math.PI/3,e1e=Math.PI*2/3;function t1e(e){var t;return e=(.5-e)*Math.PI,T0.r=255*(t=Math.sin(e))*t,T0.g=255*(t=Math.sin(e+Jwe))*t,T0.b=255*(t=Math.sin(e+e1e))*t,T0+""}function n1e(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 O1(e){var t=e.length;return function(n){return e[Math.max(0,Math.min(t-1,Math.floor(n*t)))]}}const r1e=O1(tn("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var s1e=O1(tn("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),o1e=O1(tn("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),i1e=O1(tn("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function a1e(e){return e}function l1e(e){if(e==null)return a1e;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 c1e(e,t){for(var n,r=e.length,s=r-t;s<--r;)n=e[s],e[s++]=e[r],e[r]=n}function u1e(e,t){return typeof t=="string"&&(t=e.objects[t]),t.type==="GeometryCollection"?{type:"FeatureCollection",features:t.geometries.map(function(n){return KF(e,n)})}:KF(e,t)}function KF(e,t){var n=t.id,r=t.bbox,s=t.properties==null?{}:t.properties,o=d1e(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 d1e(e,t){var n=l1e(e.transform),r=e.arcs;function s(d,f){f.length&&f.pop();for(var h=r[d<0?~d:d],p=0,m=h.length;p<m;++p)f.push(n(h[p],p));d<0&&c1e(f,m)}function o(d){return n(d)}function i(d){for(var f=[],h=0,p=d.length;h<p;++h)s(d[h],f);return f.length<2&&f.push(f[0]),f}function a(d){for(var f=i(d);f.length<4;)f.push(f[0]);return f}function 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 ig={geoAzimuthalEqualArea:fve,geoAzimuthalEquidistant:hve,geoGnomonic:Sve,geoOrthographic:Nve,geoStereographic:jve,geoEqualEarth:wve,geoAlbers:NH,geoAlbersUsa:dve,geoConicConformal:gve,geoConicEqualArea:Bv,geoConicEquidistant:yve,geoEquirectangular:bve,geoMercator:pve,geoTransverseMercator:kve,geoNaturalEarth1:Cve};Object.keys(ig).forEach(e=>{ig[`${e.charAt(3).toLowerCase()}${e.slice(4)}`]=ig[e]});class Xd extends Uc{constructor(t){super(t),this.outlineBounds=null,this.oldChartBounds=null,this.geoPath=AF()}init(t){t.position="chartArea",super.init(t),typeof t.projection=="function"?this.projection=t.projection:this.projection=(ig[t.projection]||ig.albersUsa)(),this.geoPath.projection(this.projection),this.outlineBounds=null,this.oldChartBounds=null}computeBounds(t){const n=AF(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,p=n.height*f,m=(l-h)*.5+t.left+o,g=(u-p)*.5+t.top+s,b=this.options;return this.projection.scale(n.refScale*f*b.projectionScale).translate([f*n.refX+m+b.projectionOffset[0],f*n.refY+g+b.projectionOffset[1]]),!d||d.chartWidth!==this.oldChartBounds.chartWidth||d.chartHeight!==this.oldChartBounds.chartHeight}}Xd.id="projection";Xd.defaults={projection:"albersUsa",projectionScale:1,projectionOffset:[0,0],padding:0};Xd.descriptors={_scriptable:e=>e!=="projection",_indexable:e=>e!=="projectionOffset"};const F1={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 f1e(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 h1e(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=f1e(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 $f extends _d{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=(p,m)=>p<1?m*p:p,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=h1e(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 zH extends Ph{constructor(){super(...arguments),this.legendSize={w:0,h:0}}init(t){$f.prototype.init.call(this,t)}parse(t,n){return $f.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 $f.prototype.update.call(this,t,n,r)}_computeLabelArea(){}draw(t){return $f.prototype.draw.call(this,t)}_drawIndicator(){}}const Ba={interpolateBlues:Fwe,interpolateBrBG:Kve,interpolateBuGn:hwe,interpolateBuPu:mwe,interpolateCividis:Gwe,interpolateCool:Xwe,interpolateCubehelixDefault:Kwe,interpolateGnBu:bwe,interpolateGreens:Lwe,interpolateGreys:Bwe,interpolateInferno:o1e,interpolateMagma:s1e,interpolateOrRd:ywe,interpolateOranges:Ywe,interpolatePRGn:Xve,interpolatePiYG:Jve,interpolatePlasma:i1e,interpolatePuBu:Cwe,interpolatePuBuGn:wwe,interpolatePuOr:twe,interpolatePuRd:jwe,interpolatePurples:Hwe,interpolateRainbow:Qwe,interpolateRdBu:rwe,interpolateRdGy:owe,interpolateRdPu:Ewe,interpolateRdYlBu:awe,interpolateRdYlGn:cwe,interpolateReds:Wwe,interpolateSinebow:t1e,interpolateSpectral:dwe,interpolateTurbo:n1e,interpolateViridis:r1e,interpolateWarm:Zwe,interpolateYlGn:Twe,interpolateYlGnBu:Dwe,interpolateYlOrBr:Iwe,interpolateYlOrRd:Pwe};Object.keys(Ba).forEach(e=>{Ba[`${e.charAt(11).toLowerCase()}${e.slice(12)}`]=Ba[e],Ba[e.slice(11)]=Ba[e]});function BH(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 VH={interpolate:"blues",missing:"transparent",quantize:0};class jc extends $f{get interpolate(){const t=this.options;return t?typeof t.interpolate=="function"?t.interpolate:Ba[t.interpolate]||Ba.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=BH(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)}}}}jc.id="color";jc.defaults=vr({},[_d.defaults,F1,VH]);jc.descriptors={_scriptable:e=>e!=="interpolate",_indexable:!1};class DM extends zH{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=Ba[t.interpolate]||Ba.blues}getColorForValue(t){return jc.prototype.getColorForValue.call(this,t)}getColor(t){let n=t;return this.options.quantize>0&&(n=BH(n,this.options.quantize)),this.interpolate(n)}_drawIndicator(){return jc.prototype._drawIndicator.call(this)}}DM.id="colorLogarithmic";DM.defaults=vr({},[Ph.defaults,F1,VH]);DM.descriptors={_scriptable:e=>e!=="interpolate",_indexable:!1};const HH={missing:1,mode:"area",range:[2,20],legend:{align:"bottom",length:90,width:70,indicatorWidth:42}};class kc extends $f{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,p={pointStyle:"circle",borderWidth:0,...this._model||{},radius:d};kv(t,p,f,h)})}}kc.id="size";kc.defaults=vr({},[_d.defaults,F1,HH]);kc.descriptors={_scriptable:!0,_indexable:e=>e!=="range"};class UH extends zH{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 kc.prototype.getSizeImpl.call(this,t)}_drawIndicator(){kc.prototype._drawIndicator.call(this)}}UH.id="sizeLogarithmic";UH.defaults=vr({},[Ph.defaults,F1,HH]);function p1e(e,t){return[[e[0][0]-t,e[0][1]-t],[e[1][0]+t,e[1][1]+t]]}class hl extends Qo{constructor(){super(...arguments),this.cache=void 0}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&&Hye(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=p1e(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())}}hl.id="geoFeature";hl.defaults={...ia.defaults,outlineBackgroundColor:null,outlineBorderWidth:0,graticuleBorderColor:"#CCCCCC",graticuleBorderWidth:0};hl.defaultRoutes={outlineBorderColor:"borderColor",...ia.defaultRoutes||{}};const WH={showOutline:!1,showGraticule:!1,clipMap:!0},qH={scales:{projection:{axis:"x",type:Xd.id,position:"chartArea",display:!1}}};function ZF(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 YH extends Gs{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 ct(this.getGeoDataset().showOutline,this.getGeoOptions().showOutline)}clipMap(){return ct(this.getGeoDataset().clipMap,this.getGeoOptions().clipMap)}getGraticule(){return ct(this.getGeoDataset().showGraticule,this.getGeoOptions().showGraticule)}update(t){super.update(t);const n=this.getMeta(),r=this.getProjectionScale(),s=r.updateBounds();if(this.showOutline()){const o=n.dataset;if(s&&delete o.cache,o.projectionScale=r,o.pixelRatio=this.chart.currentDevicePixelRatio,t!=="resize"){const i=ZF(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=ZF(this.resolveDatasetElementOptions(t)));this.updateElements(n.data,0,n.data.length,t),s&&n.data.forEach(o=>delete o.cache)}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(Uye());else{const i=lH();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,dc(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||dc(t.ctx,t.chartArea):r&&(r=!1,fc(t.ctx)),this.showGraticule(),n===!0||n==="items"?r||dc(t.ctx,t.chartArea):r&&(r=!1,fc(t.ctx)),this.getMeta().data.forEach(s=>s.draw.call(s,t.ctx,t.chartArea)),r&&(r=!1,fc(t.ctx))}}function GH(e,t,n,r=[],s=[]){Qn.addControllers(n),Array.isArray(r)?Qn.addElements(...r):Qn.addElements(r),Array.isArray(s)?Qn.addScales(...s):Qn.addScales(s);const o=t;return o.type=e,o}class kp extends YH{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,d.feature=this._data[u].feature,d.center=this._data[u].center,d.pixelRatio=this.chart.currentDevicePixelRatio;const f=d.getCenterPoint(),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])}}kp.id="choropleth";kp.defaults=vr({},[WH,{datasetElementType:hl.id,dataElementType:hl.id}]);kp.overrides=vr({},[qH,{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:jc.id,axis:"x"}},elements:{geoFeature:{backgroundColor(e){return e.dataIndex==null?null:e.chart.getDatasetMeta(e.datasetIndex).controller.indexToColor(e.dataIndex)}}}}]);class m1e extends Kt{constructor(t,n){super(t,GH("choropleth",n,kp,hl,[jc,Xd]))}}m1e.id=kp.id;class Ep extends YH{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),p=u.projection([h.x,h.y]),m={x:p?p[0]:0,y:p?p[1]:0,skip:Number.isNaN(h.x)||Number.isNaN(h.y)};l&&(m.options=a||this.resolveDataElementOptions(d,s),o&&(m.options.radius=0)),this.updateElement(f,d,m,s)}}indexToRadius(t){const n=this.getMeta().rScale;return n.getSizeForValue(this.getParsed(t)[n.axis])}}Ep.id="bubbleMap";Ep.defaults=vr({},[WH,{dataElementType:td.id,datasetElementType:hl.id,showOutline:!0,clipMap:"outline+graticule"}]);Ep.overrides=vr({},[qH,{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:kc.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 g1e extends Kt{constructor(t,n){super(t,GH("bubbleMap",n,Ep,hl,[kc,Xd]))}}g1e.id=Ep.id;function b1e(e){var n;return{...e,type:"bar",options:{...e==null?void 0:e.options,indexAxis:"y",scales:{x:{display:!0},y:{display:!0}},plugins:{...(n=e==null?void 0:e.options)==null?void 0:n.plugins,legend:{position:"bottom",align:"center"}}}}}function x1e(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 y1e(e){var n;return{...e,type:"bar",options:{...e==null?void 0:e.options,scales:{x:{display:!0},y:{display:!0}},plugins:{...(n=e==null?void 0:e.options)==null?void 0:n.plugins,legend:{position:"bottom",align:"center"}}}}}function v1e(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 w1e(e,t,n=!1){var s,o,i,a,l;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:!0,stacked:!n},y:{...(a=(i=e==null?void 0:e.options)==null?void 0:i.scales)==null?void 0:a.y,display:!0,stacked:t==="stackedBar"}},plugins:{...(l=e==null?void 0:e.options)==null?void 0:l.plugins,legend:{display:!1,position:"bottom",align:"center"}}}}}function S1e(e){var n;return{...e,type:"line",options:{...e==null?void 0:e.options,scales:{x:{display:!0},y:{display:!0}},plugins:{...(n=e==null?void 0:e.options)==null?void 0:n.plugins,legend:{position:"bottom",align:"center"}}}}}function C1e(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 N1e(e){var r,s;const t=ee.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:Sn.slate[800]},angleLines:{color:Sn.slate[800]},ticks:{color:Sn.slate[800],showLabelBackdrop:!1}}}}}),n}function Cs({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 p=new Intl.NumberFormat(l,f).format(d);return n&&(p+=a),p}function $1(e,t){if(!t)return"";const n=t.find(r=>e>=r.start&&e<=r.end);return(n==null?void 0:n.color)||""}const j1e=5,k1e=30,Uk=5;function E1e({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o,cardConfig:i,isDevMode:a=!1,card:l}){var I,F,z,B,$,P,V,L,A,W,U;if(!e||e.length===0)return{type:s,data:{labels:[],datasets:[]}};const u=r==null?void 0:r.bubbleScatterConfig,d=_1e(e,u,i,a,s);if(!d.xKey||!d.yKey)return{type:s,data:{labels:[],datasets:[]}};const f=ee.getState(),h=o??f.themeStyle,p=M1e(e,d,u,s),m=R1e(p,h,r,s),g=Nd(m,n),b=O1e(r),x=QD(s),y=(F=(I=r==null?void 0:r.chartOptions)==null?void 0:I.plugins)==null?void 0:F.legend,v=JB(x,y),w=!!(y!=null&&y.labels||($=(B=(z=t==null?void 0:t.options)==null?void 0:z.plugins)==null?void 0:B.legend)!=null&&$.labels||(L=(V=(P=n==null?void 0:n.options)==null?void 0:P.plugins)==null?void 0:V.legend)!=null&&L.labels);(y==null?void 0:y.display)===void 0&&(v.display=d.grouping.enabled);const S=$1e(l);let C=A1e({resolvedKeys:d,formatConfig:b,preferences:r,cardType:s,legendConfig:v,hasCustomLegendLabels:w,hasDrillDown:S});C=XD(C,v);const{plugins:j=[],options:D}=Vc((r==null?void 0:r.customVisualCode)||""),k=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:{...((W=r.chartOptions.plugins)==null?void 0:W.legend)??{},display:v.display}}}:void 0,_=F1e([C,t==null?void 0:t.options,k,n==null?void 0:n.options,D]),M=ar(((U=h==null?void 0:h.chart)==null?void 0:U.options)||{},_),R={type:s,data:{datasets:g},options:M,plugins:j},O=Yb(s,r),T=(r==null?void 0:r.dataLabelsConfig)??O;return R.options=Cp(R.options||{},T,r,s),R.options=Sp.applyAxisConfig(R.options||{},s,r),R}function _1e(e,t,n,r,s){var v,w;const{metricKeys:o,keys:i}=rr(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(S=>S.label||S.name||S.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],p=(h==null?void 0:h.label)||(h==null?void 0:h.name)||(h==null?void 0:h.alias),m=r?(t==null?void 0:t.labelKey)??f??i[0]:(t==null?void 0:t.labelKey)??p??i[0],g=D1e(t,n,r,l);let b,x,y;if(r){const S=1+(g.enabled&&g.groupKey?1:0),C=l.slice(S);b=(t==null?void 0:t.xMetricKey)??C[0],x=(t==null?void 0:t.yMetricKey)??C[1],y=s==="bubble"?(t==null?void 0:t.radiusMetricKey)??C[2]:void 0,b||(b=C[0]),x||(x=C[1]??C[0]),s==="bubble"&&!y&&(y=C[2]??C[1]??C[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:m,xKey:b,yKey:x,radiusKey:y,grouping:g}}function D1e(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 M1e(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=>R0(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)??j1e,h=(n==null?void 0:n.maxRadius)??k1e,p=(n==null?void 0:n.radiusScale)??"sqrt",m=(n==null?void 0:n.fixedRadius)??Uk,g=x=>{const y=R0(x[o]),v=R0(x[i]);if(!Number.isFinite(y)||!Number.isFinite(v))return null;let w;if(r==="scatter")w=m;else if(p==="fixed")w=m;else if(a){const C=R0(x[a]);if(!Number.isFinite(C))return null;w=T1e(C,d,f,h,p)}else w=m;const S=XF(x[s]);return{x:y,y:v,r:w,label:S,meta:x}};if(l.enabled&&l.groupKey){const x=l.groupKey,y=new Map;for(const v of e){const w=XF(v[x]);y.has(w)||y.set(w,[]);const S=g(v);S&&y.get(w).push(S)}return Array.from(y.entries()).map(([v,w])=>({group:v,points:w}))}return[{group:"",points:e.map(g).filter(x=>x!==null)}]}function T1e(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 R1e(e,t,n,r){var u,d,f,h;const s=Kd().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((p,m)=>{var y,v;if(!p.group&&e.length===1){const w=p.points.map((j,D)=>{var M,R;const _=((R=(M=n==null?void 0:n.colorConfig)==null?void 0:M.segments)==null?void 0:R[j.label])||a[D%a.length]||"#3b82f6";return QF(_,.8)}),S=p.points.map((j,D)=>{var _,M;return((M=(_=n==null?void 0:n.colorConfig)==null?void 0:_.segments)==null?void 0:M[j.label])||l[D%l.length]||"#3b82f6"}),C={label:void 0,data:p.points.map(j=>({x:j.x,y:j.y,r:j.r,label:j.label,meta:j.meta})),backgroundColor:w,borderColor:S,borderWidth:1};return r==="scatter"&&(C.pointRadius=((y=p.points[0])==null?void 0:y.r)??Uk),C}const b=I1e({seriesKey:p.group,seriesIndex:m,preferences:n,backgroundPalette:a,borderPalette:l}),x={label:p.group||void 0,data:p.points.map(w=>({x:w.x,y:w.y,r:w.r,label:w.label,meta:w.meta})),backgroundColor:QF(b.backgroundColor,.8),borderColor:b.borderColor,borderWidth:1};return r==="scatter"&&(x.pointRadius=((v=p.points[0])==null?void 0:v.r)??Uk),x})}function I1e({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 A1e({resolvedKeys:e,formatConfig:t,preferences:n,cardType:r,legendConfig:s,hasCustomLegendLabels:o,hasDrillDown:i}){var p,m,g,b,x,y,v,w;const a=((m=(p=n==null?void 0:n.xAxisConfig)==null?void 0:p.name)==null?void 0:m.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:S=>ag(Number(S),"x",t,n)}},y:{type:"linear",position:"left",title:{display:l,text:d},ticks:{callback:S=>ag(Number(S),"y",t,n)}}},plugins:{legend:{...s,...f?{labels:{generateLabels:z1e(e)}}:{}},tooltip:{displayColors:!1,callbacks:P1e(e,t,r,n,i)}}}}function P1e(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=ag(i.x,"x",t,r),u=ag(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=ag(d[e.radiusKey],"y",t,r);a.push(`${e.radiusKey} (size): ${f}`)}}return s&&(a.push("─────────────────"),a.push("Click to drill")),a}}}function O1e(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 R0(e){const t=Number(e);return Number.isFinite(t)?t:Number.NaN}function XF(e){return e==null||e===""?"(Blank)":String(e)}function F1e(e){return e.reduce((t,n)=>ar(t,n||{}),{})}function ag(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 Fr(e,o,(s==null?void 0:s.formatOptions)||{});if(r!=null&&r.numberAxisFormat){const a=r.numberAxisFormat;return Cs({number:e,decimalPlaces:a.decimalPlaces??0,useSuffix:!!a.suffix,customSuffix:a.suffix||"",locale:a.locale||"",currency:a.currency||""})}return Fr(e,n.format,n.options)}function $1e(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 L1e(e){return/^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(e.trim())}function QF(e,t){if(!e||!L1e(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 z1e(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 B1e({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var M,R,O,T,I;const i=((M=r==null?void 0:r.chartOptions)==null?void 0:M.indexAxis)||"y",a={...t,options:{indexAxis:i}},{keys:l}=rr(e),u=[l[1]],d=l==null?void 0:l[0],f=GB(u,e,r,d),h=Nd(f,n);h.forEach((F,z)=>{var B,$,P;F.shrinkAnchor=((P=($=(B=n==null?void 0:n.data)==null?void 0:B.datasets)==null?void 0:$[z])==null?void 0:P.shrinkAnchor)||"top"});const{plugins:p,options:m}=Vc((r==null?void 0:r.customVisualCode)||""),g=l[0],b=qb(e,g),x=ar((a==null?void 0:a.options)||{},(n==null?void 0:n.options)||{}),y=ar(x,(r==null?void 0:r.chartOptions)||{});Array(h.length).fill(!0);const v=e.map(F=>F[g]),w=e.map(F=>F[u[0]]),S=(R=h[0])==null?void 0:R.backgroundColor.slice(),C={...y,plugins:{...y.plugins,legend:{...(O=y.plugins)==null?void 0:O.legend,labels:{generateLabels:F=>{const z=F.data.labels;return v.map((B,$)=>({text:B,fillStyle:S[$],hidden:!z.includes(B.toString()),index:$,datasetIndex:0,lineWidth:0}))}},onClick:(F,z,B)=>{const $=B.chart,P=z.index,V=v[P],L=$.data.datasets[0],A=$.data.labels,W=L.data,U=L.backgroundColor,Y=A.indexOf(V.toString());Y>=0?(A.splice(Y,1),W.splice(Y,1),U.splice(Y,1)):(A.splice(P,0,v[P].toString()),W.splice(P,0,Number(w[P])),U.splice(P,0,S[P])),$.update()}},datalabels:{...(T=y.plugins)==null?void 0:T.datalabels,anchor:F=>F.dataset.data[F.dataIndex]<.02?"end":"start",align:F=>F.dataset.data[F.dataIndex]<.02?"end":"center",textAlign:"center",font:{size:14},formatter:(F,z)=>{var B,$,P,V;return Cs({number:Number(F),decimalPlaces:((B=r==null?void 0:r.numberAxisFormat)==null?void 0:B.decimalPlaces)||0,useSuffix:!!(($=r==null?void 0:r.numberAxisFormat)!=null&&$.suffix),customSuffix:"",locale:((P=r==null?void 0:r.numberAxisFormat)==null?void 0:P.locale)||"",currency:((V=r==null?void 0:r.numberAxisFormat)==null?void 0:V.currency)||""})}},tooltip:{...(I=y.plugins)==null?void 0:I.tooltip,callbacks:{title:function(F){var V,L,A,W;const B=((L=(V=F==null?void 0:F[0])==null?void 0:V.dataset)==null?void 0:L.data).reduce((U,Y)=>U+Y,0),P=(((A=F==null?void 0:F[0])==null?void 0:A.parsed[i==="x"?"y":"x"])/B*100).toFixed(2);return`${(W=F==null?void 0:F[0])==null?void 0:W.label} (${P}%)`},label:function(F){var W,U,Y,K;F.dataset.label;const z=F.dataset.data;z.reduce((H,q)=>H+q,0);const B=F.parsed[i==="x"?"y":"x"],$=z.indexOf(B),P=z[$-1],V=Cs({number:Number(B),decimalPlaces:((W=r==null?void 0:r.numberAxisFormat)==null?void 0:W.decimalPlaces)||0,useSuffix:!!((U=r==null?void 0:r.numberAxisFormat)!=null&&U.suffix),customSuffix:"",locale:((Y=r==null?void 0:r.numberAxisFormat)==null?void 0:Y.locale)||"",currency:((K=r==null?void 0:r.numberAxisFormat)==null?void 0:K.currency)||""});let L=0;return P!==void 0&&(L=Number((B/P*100).toFixed(2))),V+(P!==void 0?` | Conversion: ${L}%`:"")},footer:function(F){var B,$,P,V;return((($=(B=o==null?void 0:o.interactionConfig)==null?void 0:B.drillHierarchies)==null?void 0:$.length)??0)>0||(((V=(P=o==null?void 0:o.interactionConfig)==null?void 0:P.interactions)==null?void 0:V.some(L=>L.mode==="drillDown"||L.mode==="drillToDetail"||L.mode==="drillThrough"||L.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},j=ar(y,C),D=r!=null&&r.dataLabelsConfig?Cp(j,r.dataLabelsConfig,r,"funnel"):j,k=ar(D,m);return delete k.scales,{type:s,data:{labels:b,datasets:h},options:k,plugins:[...p]}}function V1e({data:e,cfg:t,customCfg:n,preferences:r,card:s}){var C,j;const o=v1e(t),i=H1e(e),a=Nd(i,n),{plugins:l,options:u}=Vc((r==null?void 0:r.customVisualCode)||""),d=ar((o==null?void 0:o.options)||{},(t==null?void 0:t.options)||{}),f=ar(d,(r==null?void 0:r.chartOptions)||{}),h=ar(f,(n==null?void 0:n.options)||{}),p={...h,plugins:{...h==null?void 0:h.plugins,tooltip:{...(C=h==null?void 0:h.plugins)==null?void 0:C.tooltip,callbacks:{label:function(D){if(Array.isArray(D.raw)&&D.raw.every(k=>k===null))return null},footer:function(D){var _,M,R,O;return(((M=(_=s==null?void 0:s.interactionConfig)==null?void 0:_.drillHierarchies)==null?void 0:M.length)??0)>0||(((O=(R=s==null?void 0:s.interactionConfig)==null?void 0:R.interactions)==null?void 0:O.some(T=>T.mode==="drillDown"||T.mode==="drillToDetail"||T.mode==="drillThrough"||T.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},m=ar(p,u),g=tV(t,r),b=ar(m,g);let x;r!=null&&r.dataLabelsConfig?x=Cp(b,r.dataLabelsConfig,r,"range"):x={...b,plugins:{...b==null?void 0:b.plugins,datalabels:{...(j=b==null?void 0:b.plugins)==null?void 0:j.datalabels,formatter:(D,k)=>D.map(M=>{var R,O,T,I;return Cs({number:Number(M),decimalPlaces:((R=r==null?void 0:r.numberAxisFormat)==null?void 0:R.decimalPlaces)||0,useSuffix:!!((O=r==null?void 0:r.numberAxisFormat)!=null&&O.suffix),customSuffix:"",locale:((T=r==null?void 0:r.numberAxisFormat)==null?void 0:T.locale)||"",currency:((I=r==null?void 0:r.numberAxisFormat)==null?void 0:I.currency)||""})}).slice(0,2).join(" - ")}}};const{keys:y}=rr(e),v=y[0];return{type:"bar",data:{labels:[...new Set(qb(e,v))],datasets:a},options:x,plugins:[...l]}}function H1e(e){var h,p,m,g;const{keys:t}=rr(e),n=t.slice(0,2),r=t.slice(2),s=ee.getState().themeStyle,o=(p=(h=s==null?void 0:s.chart)==null?void 0:h.dataset)==null?void 0:p.backgroundColor,i=(g=(m=s==null?void 0:s.chart)==null?void 0:m.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(S=>(S==null?void 0:S[a])===b),w=u.map(S=>{const C=y.filter(j=>(j==null?void 0:j[l])===S);return C.length===0?[[null,null,null]]:C.map(j=>[j==null?void 0:j[r[0]],j==null?void 0:j[r[1]],j==null?void 0:j[r[2]],S])}).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 U1e({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var w;const i=x1e(t),{keys:a}=rr(e),l=E1({dataArray:e,groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:u}=rr(l),d=u.slice(1),f=YB(d,l,r),h=Nd(f,n),p=u[0],m=qb(l,p),{options:g,plugins:b}=wv({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:m,datasets:h},options:g,plugins:b},y="x2";return{...x,data:{...x.data,datasets:x.data.datasets.map((S,C)=>C===1?{...S,xAxisID:y}:S)},options:{...x.options,scales:{...(w=x==null?void 0:x.options)==null?void 0:w.scales,[y]:{beginAtZero:!0,stack:1}}}}}const JF={type:"treemap",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function W1e({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s}){var S;if(!e||e.length===0)return JF;const{dimensionKeys:o,metricKeys:i,keys:a}=rr(e),l=o.length>0?o:a.slice(0,1);let u=i[0];if(u||(u=a.find(C=>!l.includes(C))||i[0]||a[1]),!u)return console.warn("Treemap chart could not determine a metric column."),JF;const d=K1e(e,l,u),f=s??ee.getState().themeStyle,h=((S=r==null?void 0:r.chartOptions)==null?void 0:S.treemapColorMode)??"branch",p=Z1e(d,l,r,f),m=X1e(r),g=q1e({tree:d,dimensionKeys:l,metricKey:u,colorLookups:p,formatConfig:m,themeStyle:f,preferences:r,colorMode:h}),b=Y1e({dimensionKeys:l,metricKey:u,formatConfig:m}),{plugins:x,options:y}=Vc((r==null?void 0:r.customVisualCode)||""),v=G1e([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 q1e({tree:e,dimensionKeys:t,metricKey:n,colorLookups:r,formatConfig:s,themeStyle:o,preferences:i,colorMode:a}){var p,m,g,b,x,y,v,w,S,C,j;const l=Yb("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=(m=(p=o==null?void 0:o.chart)==null?void 0:p.dataset)==null?void 0:m.borderColor)==null?void 0:g[0])||"rgba(255,255,255,0.8)",labels:{display:d,align:"center",position:"middle",overflow:"fit",formatter:D=>{if(!d)return"";const k=D==null?void 0:D.raw,_=KH(k,t),M=Number((k==null?void 0:k.v)??0),R=ZH(M,s);return _?`${_}
|
|
763
|
-
${R}`:R},color:D=>{if(f)return f;const k=D==null?void 0:D.raw,_=e5({raw:k,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a});return Bo(_)},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)||((S=u==null?void 0:u.font)==null?void 0:S.weight)||"bold",family:((j=(C=o==null?void 0:o.chart)==null?void 0:C.font)==null?void 0:j.family)||"Inter"}},backgroundColor:D=>{const k=D==null?void 0:D.raw;return e5({raw:k,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a})}}}function Y1e({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 J1e(o==null?void 0:o.raw,e)},label:s=>{const o=s==null?void 0:s.raw,i=KH(o,e),a=Number((o==null?void 0:o.v)??0),l=ZH(a,n),u=t||"Value";return i?`${i} — ${u}: ${l}`:`${u}: ${l}`}}}}}}function G1e(e){return e.reduce((t,n)=>ar(t,n||{}),{})}function K1e(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 Z1e(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))??Kd();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,p)=>{var m,g;if((g=(m=n==null?void 0:n.colorConfig)==null?void 0:m.segments)!=null&&g[h]){d.set(h,n.colorConfig.segments[h]);return}d.set(h,s[p%s.length])}),d})}function X1e(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!=="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 KH(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 Q1e(e._data,t);if(e.path){const r=e.path.split("."),s=r[r.length-1];if(s)return s}return""}function Q1e(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 J1e(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 ZH(e,t){return Fr(e,t.format,t.formatOptions)}function e5({raw:e,dimensionKeys:t,colorLookups:n,themeStyle:r,preferences:s,colorMode:o}){var m,g,b,x,y,v,w;if(!e)return"#999999";const i=((b=(g=(m=r==null?void 0:r.chart)==null?void 0:m.dataset)==null?void 0:g.backgroundColor)==null?void 0:b.filter(Boolean))??Kd(),a=eSe(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=MM(f,0,d);if(h===0||o==="category")return u;const p=tSe(e);return nSe(u,p,h)}function eSe(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 tSe(e){if(!e)return 1;const t=Number(e.v??0),n=Number(e.gs??e.s??0);return n>0&&Number.isFinite(t)?MM(t/n,0,1):1}function nSe(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=t5(e,"#ffffff",o);return a=t5(a,"#000000",i),a}function t5(e,t,n){const r=MM(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=n5(e),o=n5(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 rSe(i,a,l)}function n5(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 rSe(e,t,n){const r=s=>s.toString(16).padStart(2,"0");return`#${r(bN(e))}${r(bN(t))}${r(bN(n))}`}function bN(e){return Math.min(255,Math.max(0,Math.round(e)))}function MM(e,t,n){return Math.max(t,Math.min(n,e))}const XH=["poor","satisfactory","good"],xN={poor:"Poor",satisfactory:"Average",good:"Good"},sSe=["#F5F6F8","#E3E6EC","#CED4DD"],oSe=["#1F2933","#27323D","#303B47"];function iSe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s}){var ne,ae,ie,he,be,Ce,Oe;if(!e||e.length===0)return{type:"bar",data:{labels:[],datasets:[]}};const{dimensionKeys:o,metricKeys:i,keys:a}=rr(e),l=o[0]??a[0];if(!l)return{type:"bar",data:{labels:[],datasets:[]}};const u=i[0]??a.find(ue=>ue!==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(ue=>ue!==u),h=(d==null?void 0:d.comparativeMetricKey)??(d!=null&&d.disableAutoComparative?void 0:i.find(ue=>ue!==u&&ue!==f)),p=ee.getState(),m=s??p.themeStyle,g=p.theme==="dark",b=aSe({data:e,dimensionKey:l,actualKey:u,targetKey:f,comparativeKey:h,bulletConfig:d}),x=b.map(ue=>ue.label),y=(d==null?void 0:d.showRanges)??wSe(d),v=uSe(b,y),w=(ne=r==null?void 0:r.chartOptions)==null?void 0:ne.indexAxis,C=(w?w==="y"?"horizontal":"vertical":void 0)??(d==null?void 0:d.orientation)??"horizontal",j=C==="vertical"?"x":"y",D=r?{...r,chartOptions:{...r.chartOptions||{},indexAxis:j}}:{chartOptions:{indexAxis:j}},k=xSe(r),_=vSe(d),M=ySe(g),R=Kd().filter(Boolean),O=(((ie=(ae=m==null?void 0:m.chart)==null?void 0:ae.dataset)==null?void 0:ie.backgroundColor)||[]).filter(Boolean),T=(((be=(he=m==null?void 0:m.chart)==null?void 0:he.dataset)==null?void 0:be.borderColor)||[]).filter(Boolean),I=O.length>0?O:R.length>0?R:["#3b82f6"],F=T.length>0?T:I.length>0?I:["#111827"],z=vN({metricKey:u,metricIndex:0,preferences:r,backgroundPalette:I,borderPalette:F}),$=vN({metricKey:f||`${u}__target`,metricIndex:1,preferences:r,backgroundPalette:I,borderPalette:F}).borderColor||z.borderColor||"#111827",P=vN({metricKey:h,metricIndex:2,preferences:r,backgroundPalette:I,borderPalette:F}),V=y?dSe(b,M,C,g,_):[],L=fSe(b,z,C,u),A=hSe(b,P,C,h),W=[...V,L];A&&W.push(A);let U=pSe({orientation:C,chartMax:v,formatConfig:k,series:b,preferences:D,rangeLabelMap:_,showRanges:y});const Y=(Oe=(Ce=r==null?void 0:r.chartOptions)==null?void 0:Ce.plugins)==null?void 0:Oe.legend;U=XD(U,Y);const{plugins:K=[],options:H}=Vc((r==null?void 0:r.customVisualCode)||""),q=jSe([U,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,H]),X=b.some(ue=>ue.target!=null)&&v>0?bSe({series:b,orientation:C,color:$}):null,Z={type:"bar",data:{labels:x,datasets:W},options:q,plugins:X?[...K,X]:K},G=Yb("bullet",r),Q=(r==null?void 0:r.dataLabelsConfig)??G;return Z.options=Cp(Z.options||{},Q,D,"bar"),Z.options=Sp.applyAxisConfig(Z.options||{},"bar",D),Z.options=Z.options||{},Z.options.indexAxis=j,Z}function aSe({data:e,dimensionKey:t,actualKey:n,targetKey:r,comparativeKey:s,bulletConfig:o}){const i=e.map(l=>{const u=cSe(l[t]),d=zy(l[n]),f=r&&l[r]!=null?zy(l[r]):(o==null?void 0:o.targetValue)??null,h=s&&l[s]!=null?zy(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=lSe({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 lSe({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:yN("poor",e,o,i,a*.5,s,a),satisfactory:yN("satisfactory",e,o,i,a*.8,s,a),good:yN("good",e,o,i,a,s,a)};let u=0;return XH.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 yN(e,t,n,r,s,o,i){const a=n==null?void 0:n[e];if(a&&t[a]!=null)return zy(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 zy(e){const t=Number(e);return Number.isFinite(t)?t:0}function cSe(e){return e==null||e===""?"(Blank)":String(e)}function uSe(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 dSe(e,t,n,r,s){const o=[];return XH.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:CSe(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 fSe(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 hSe(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 pSe({orientation:e,chartMax:t,formatConfig:n,series:r,preferences:s,rangeLabelMap:o,showRanges:i}){var f,h,p,m,g,b,x,y,v;const a={type:"linear",stacked:!1,beginAtZero:!0,suggestedMax:t,ticks:{callback:w=>Fr(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:((p=(h=(f=s==null?void 0:s.chartOptions)==null?void 0:f.plugins)==null?void 0:h.legend)==null?void 0:p.display)??!0,position:((b=(g=(m=s==null?void 0:s.chartOptions)==null?void 0:m.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 S=w.dataset.customRole;return S?S!=="range":!0},callbacks:mSe(r,n,o,i)}},indexAxis:e==="vertical"?"x":"y"}}function mSe(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"}: ${Fr(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=Fr(o.target,t.format,t.options),d=o.actual-o.target,f=Fr(d,t.format,t.options),h=o.targetKey||"Target";i.push(`${h}: ${u} (${f})`)}const a=gSe(o,n);r&&a&&i.push(`Range: ${a}`);const l=o.comparative;return l!=null&&i.push(`Comparative: ${Fr(l,t.format,t.options)}`),i}}}function gSe(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 bSe({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],p=((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]),m=p?t==="horizontal"?p.height??p.width??20:p.width??p.height??20:20,g=Math.max(Math.min(m/2,12),6);if(t==="horizontal"){const S=o.getPixelForValue(d.target),C=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(S,C-g),s.lineTo(S,C+g),s.stroke(),s.beginPath(),s.moveTo(S-4,C-g),s.lineTo(S+4,C-g),s.moveTo(S-4,C+g),s.lineTo(S+4,C+g),s.stroke()}else{const S=o.getPixelForValue(d.target),C=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(C-g,S),s.lineTo(C+g,S),s.stroke(),s.beginPath(),s.moveTo(C-g,S-4),s.lineTo(C-g,S+4),s.moveTo(C+g,S-4),s.lineTo(C+g,S+4),s.stroke()}}),s.restore()}}}function xSe(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 ySe(e){return[...e?oSe:sSe]}function vSe(e){var n,r,s;const t=(e==null?void 0:e.rangeLabels)||{};return{poor:((n=t.poor)==null?void 0:n.trim())||xN.poor,satisfactory:((r=t.satisfactory)==null?void 0:r.trim())||xN.satisfactory,good:((s=t.good)==null?void 0:s.trim())||xN.good}}function wSe(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 SSe(e,t,n){const r=QH(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 NSe(i,a,l)}function CSe(e,t,n){return SSe(e,n?"#000000":"#ffffff",t)}function vN({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 NSe(e,t,n){return`#${wN(e)}${wN(t)}${wN(n)}`}function wN(e){return QH(Math.round(e),0,255).toString(16).padStart(2,"0")}function QH(e,t,n){return Math.max(t,Math.min(n,e))}function jSe(e){return e.reduce((t,n)=>ar(t,n||{}),{})}const Wk={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"}},JH=["#dcfce7","#15803d"],I0={type:"matrix",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function kSe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o}){var U,Y,K;if(!Array.isArray(e)||e.length===0)return I0;const{dimensionKeys:i,metricKeys:a,keys:l}=rr(e),u=i[0]??l[0];if(!u)return I0;const d=i[1],f=l.find(H=>H!==u&&!a.includes(H)&&H!==d)??d,h=!d&&(!f||typeof((U=e[0])==null?void 0:U[f])!="string")&&a.length>1,p=a[0]??l.find(H=>H!==u&&H!==f);if(!p&&!h)return I0;const m=r==null?void 0:r.heatmapConfig,g=(m==null?void 0:m.legendPosition)??"bottom",b=h?_Se({data:e,dimensionKey:u,metricKeys:a}):ESe({data:e,xKey:u,yKey:f||p,metricKey:p});if(b.length===0)return I0;const x=h?a.map(zh):SN(b.map(H=>H.x)),y=SN(h?e.map(H=>zh(H==null?void 0:H[u])):b.map(H=>H.y)),v=DSe(b),w=o??ee.getState().themeStyle,S=PSe({min:v.min,max:v.max,heatmapConfig:m,themeStyle:w}),C=MSe({points:b,xLabels:x,yLabels:y,fill:(m==null?void 0:m.fillMissingCells)!==!1}),j=zSe(r),k=["auto","number","currency","percent","none"].includes(j.format)?j.format:"auto",_=Yb("heatmap",r),M=_?{..._,format:_.format??k,formatOptions:_.formatOptions??j.options}:void 0,R=(r==null?void 0:r.dataLabelsConfig)??M,O=TSe({points:C,xLabels:x,yLabels:y,colorScale:S,datasetLabel:h?"Value":p||"Value",dataLabelPrefs:R,formatConfig:j}),T=RSe({xLabels:x,yLabels:y,heatmapConfig:m,formatConfig:j,themeStyle:w,legendPreferences:(K=(Y=r==null?void 0:r.chartOptions)==null?void 0:Y.plugins)==null?void 0:K.legend,cardType:s,legendPosition:g}),{plugins:I=[],options:F}=Vc((r==null?void 0:r.customVisualCode)||""),z=BSe([T,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,F]),B=(m==null?void 0:m.showLegend)===!1?null:OSe({stops:S.stops,min:v.min,max:v.max,formatConfig:j,position:g}),$={type:"matrix",data:{datasets:[O]},options:z,plugins:B?[...I,B]:I};$.options=Cp($.options||{},R,r,"matrix");const P=uk(s??"heatmap","x"),V=uk(s??"heatmap","y"),L=dk(P,r==null?void 0:r.xAxisConfig),A=dk(V,r==null?void 0:r.yAxisConfig),W=L||A||r?{...r||{},...L?{xAxisConfig:L}:{},...A?{yAxisConfig:A}:{}}:r;return $.options=Sp.applyAxisConfig($.options||{},"heatmap",W),$}function ESe({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=zh(i),u=zh(a),d=`${l}__${u}`,f=eU(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 _Se({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=zh(o);n.forEach(a=>{if(a===t)return;const l=eU(s==null?void 0:s[a]),u=zh(a);r.push({x:u,y:i,v:l,raw:{...s,_metricKey:a}})})}),r}function zh(e){return e==null||e===""?"Unknown":String(e)}function eU(e){const t=Number(e);return Number.isFinite(t)?t:null}function SN(e){const t=new Set,n=[];return e.forEach(r=>{t.has(r)||(t.add(r),n.push(r))}),n}function DSe(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 MSe({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 TSe({points:e,xLabels:t,yLabels:n,colorScale:r,datasetLabel:s,dataLabelPrefs:o,formatConfig:i}){const a=pme(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 LSe(h,.85)},borderWidth:1,borderColor:"rgba(255, 255, 255, 0.65)",width:({chart:d})=>{var f;return s5((f=d==null?void 0:d.chartArea)==null?void 0:f.width,t.length)},height:({chart:d})=>{var f;return s5((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)?"":TM(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 Bo($Se(h))},font:{size:Math.max(10,Math.min(14,120/l))}}}}function s5(e,t){return!e||t===0?0:Math.max(4,e/t-2)}function RSe({xLabels:e,yLabels:t,heatmapConfig:n,formatConfig:r,themeStyle:s,legendPreferences:o,cardType:i,legendPosition:a}){var p,m,g;const l=(n==null?void 0:n.showLegend)??!0,u=((g=(m=(p=s==null?void 0:s.chart)==null?void 0:p.options)==null?void 0:m.plugins)==null?void 0:g.tooltip)||{},d=QD(i??"heatmap"),f=JB(d,o);return{responsive:!0,maintainAspectRatio:!1,layout:{padding:ISe(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:ASe(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 ISe(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 ASe(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=TM(n.v,e);return s?`${s}: ${o}`:`${r}: ${o}`}}}function PSe({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"?Wk[i]??Wk.blue:void 0,l=n==null?void 0:n.colorRange,u=l&&l[0]&&l[1]?l:a?[a.start,a.end]:i==="custom"?JH:void 0,d=(u==null?void 0:u[0])??s[0]??o[0],f=(u==null?void 0:u[1])??s[1]??o[1],h=(n==null?void 0:n.colorMode)??"continuous",p=Math.max(3,(n==null?void 0:n.steps)??5),m=(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:du(d)},{offset:1,color:du(f)}]:Array.from({length:p}).map((w,S)=>{const C=p===1?0:S/(p-1||1);return{offset:C,color:o5(du(d),du(f),C)}}),x=h==="continuous"?null:b.map(w=>w.color);return{getColor(w){if(w==null||w===0)return m;if(h==="continuous"){const j=Gg((w-e)/g,0,1);return o5(du(d),du(f),j)}const S=Gg((w-e)/g,0,1),C=Math.min(p-1,Math.max(0,Math.floor(S*p)));return(x==null?void 0:x[C])??du(d)},stops:b}}function OSe({stops:e,min:t,max:n,formatConfig:r,position:s}){if(!e||e.length===0)return null;const o=i=>TM(i,r);return{id:"heatmapLegend",afterDraw(i){var m,g,b,x;const{ctx:a,chartArea:l}=i;if(!a||!l)return;a.save();const u=((x=(b=(g=(m=i.options)==null?void 0:m.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=Bo(nl()),p=24;if(a.font=`${d}px ${f}`,a.fillStyle=h,s==="bottom"||s==="top"){const v=l.left,w=l.right,S=s==="bottom"?l.bottom+p/2:l.top-10-p/2,C=a.createLinearGradient(v,0,w,0);e.forEach(D=>C.addColorStop(D.offset,D.color)),a.fillStyle=C,a.fillRect(v,S,w-v,10),a.fillStyle=h,a.textAlign="left",a.textBaseline=s==="bottom"?"top":"bottom";const j=s==="bottom"?S+10+4:S-4;a.fillText(o(t),v,j),a.textAlign="center",a.fillText(o(t+(n-t)/2),(v+w)/2,j),a.textAlign="right",a.fillText(o(n),w,j)}else{const v=l.top,w=l.bottom,S=s==="left"?l.left-10-p/2:l.right+p/2,C=a.createLinearGradient(0,v,0,w);e.forEach(D=>C.addColorStop(D.offset,D.color)),a.fillStyle=C,a.fillRect(S,v,10,w-v),a.fillStyle=h,a.textAlign=s==="left"?"right":"left",a.textBaseline="middle";const j=s==="left"?S-6:S+10+6;a.fillText(o(n),j,v),a.fillText(o(t+(n-t)/2),j,(v+w)/2),a.fillText(o(t),j,w)}a.restore()}}}function du(e){if(!e)return"#3b82f6";if(e.startsWith("rgb"))return e;if(e.startsWith("#")){const t=tU(e);return t?FSe(t.r,t.g,t.b,1):e}return e}function o5(e,t,n){const r=Wv(e),s=Wv(t);if(!r||!s)return e;const o=Gg(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 Wv(e){if(e.startsWith("#")){const n=tU(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 tU(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 FSe(e,t,n,r){return`rgba(${e}, ${t}, ${n}, ${r})`}function $Se(e){const t=Wv(e);return t?`#${CN(t.r)}${CN(t.g)}${CN(t.b)}`:"#000000"}function CN(e){return Gg(Math.round(e),0,255).toString(16).padStart(2,"0")}function LSe(e,t){const n=Wv(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${Gg(t,0,1)})`:e}function Gg(e,t,n){return Math.min(n,Math.max(t,e))}function TM(e,t){return e==null||Number.isNaN(e)?"—":Fr(e,t.format,t.options)}function zSe(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 BSe(e){return e.reduce((t,n)=>n?Nh({},t,n):t,{})}function RM({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,S,C,j;const f=e.config,h=d??!!e.sql;let p=t;const m=f&&f.pivotByColumns&&f.pivotByColumns.length>0,g=f&&f.groupByColumns&&f.groupByColumns.length>0;if(m&&g&&(p=ume(t,(f==null?void 0:f.metricColumns)||[])),n==="map"){if(!l)return null;const D=(b=a==null?void 0:a.mapVisualOptions)==null?void 0:b.objectKey;if(!D)return null;const k=u1e(l,(x=l==null?void 0:l.objects)==null?void 0:x[D]).features;if(!k)return null;const _={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:((S=a==null?void 0:a.mapVisualOptions)==null?void 0:S.colorScale)||"blues",quantize:5,legend:{position:"bottom-right",align:"right"}}}},{keys:M}=rr(p),R=k.map(B=>{var L;const $=M==null?void 0:M[0],P=M==null?void 0:M[1],V=(L=p.find(A=>(A==null?void 0:A[$])===B.properties.NAME||(A==null?void 0:A[$])===B.properties.name))==null?void 0:L[P];return{feature:B,value:V}}),T=Nd([{label:D,data:R,borderColor:"lightgray"}],s),I={type:"choropleth",data:{labels:k.map(B=>B.properties.NAME||B.properties.name),datasets:T},options:_},{options:F}=wv({cfg:I,preferences:a,customCfg:s,cardType:n});return{...I,options:F}}if(n==="bar"){const D=y1e(r);return ff({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}if(n==="horizontalBar"){const D=b1e(r);return ff({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}if(n==="funnel")return B1e({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="tornado"||n==="pyramid")return U1e({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="treemap")return W1e({data:p,cfg:r,customCfg:s,preferences:a});if(n==="heatmap")return kSe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n});if(n==="bullet")return iSe({data:p,cfg:r,customCfg:s,preferences:a});if(n==="stackedBar"||n==="stackedLine"){const D=qB(p),k=w1e(r,n,D),{keys:_}=rr(p);return!D&&(!m||!g)&&(p=E1({dataArray:p,groupKey:_[0],pivotKey:_[1],valueKey:_[2],sortChart:a==null?void 0:a.sortChart})),ff({card:e,data:p,cfg:k,customCfg:s,cardType:n,preferences:a})}if(n==="line"){const D=S1e(r);return ff({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}if(n==="range")return V1e({data:p,cfg:r,customCfg:s,preferences:a,card:e});if(n==="pie"||n==="doughnut"||n==="polarArea"){const D=C1e(n,r),{keys:k}=rr(p),_=k.slice(0,1),M=k.slice(1),R=GB(M,p,a,_==null?void 0:_[0]),O=Nd(R,s),{plugins:T,options:I}=Vc((a==null?void 0:a.customVisualCode)||""),F=_[0],z=qb(p,F),B=ar((D==null?void 0:D.options)||{},(s==null?void 0:s.options)||{}),$=ar(B,(a==null?void 0:a.chartOptions)||{}),P={...$,plugins:{...$.plugins,datalabels:{...(C=$.plugins)==null?void 0:C.datalabels,formatter:(Y,K)=>{var H,q,X,Z;return Cs({number:Number(Y),decimalPlaces:((H=a==null?void 0:a.numberAxisFormat)==null?void 0:H.decimalPlaces)||0,useSuffix:!!((q=a==null?void 0:a.numberAxisFormat)!=null&&q.suffix),customSuffix:"",locale:((X=a==null?void 0:a.numberAxisFormat)==null?void 0:X.locale)||"",currency:((Z=a==null?void 0:a.numberAxisFormat)==null?void 0:Z.currency)||""})}},tooltip:{...(j=$.plugins)==null?void 0:j.tooltip,callbacks:{label:function(Y){var G,Q,ne,ae;Y.dataset.label;const H=Y.dataset.data.reduce((ie,he)=>ie+he,0),q=Y.parsed,X=Cs({number:Number(q),decimalPlaces:((G=a==null?void 0:a.numberAxisFormat)==null?void 0:G.decimalPlaces)||0,useSuffix:!!((Q=a==null?void 0:a.numberAxisFormat)!=null&&Q.suffix),customSuffix:"",locale:((ne=a==null?void 0:a.numberAxisFormat)==null?void 0:ne.locale)||"",currency:((ae=a==null?void 0:a.numberAxisFormat)==null?void 0:ae.currency)||""}),Z=(q/H*100).toFixed(2);return X+` (${Z}%)`},footer:function(Y){var H,q,X,Z;return(((q=(H=e==null?void 0:e.interactionConfig)==null?void 0:H.drillHierarchies)==null?void 0:q.length)??0)>0||(((Z=(X=e==null?void 0:e.interactionConfig)==null?void 0:X.interactions)==null?void 0:Z.some(G=>G.mode==="drillDown"||G.mode==="drillToDetail"||G.mode==="drillThrough"||G.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},V=ar($,P),{options:L}=wv({cfg:{options:V},preferences:a,customCfg:s,cardType:n,card:e}),A=ar(L,I);return{type:n,data:{labels:z,datasets:O},options:A,plugins:[n==="doughnut"?{id:"doughnutLabel",beforeDatasetsDraw:function(Y,K,H){var he,be,Ce,Oe;const{ctx:q,data:X}=Y;q.save();const Z=Y.getDatasetMeta(0).data[0].x,G=Y.getDatasetMeta(0).data[0].y,Q=Bo(nl()),ne=window.getComputedStyle(q.canvas).fontFamily;q.font=`1em ${ne}`,q.fontWeight="bolder",q.fillStyle=Q,q.textAlign="center",q.textBaseline="middle";const ae=X.datasets[0].data.reduce((ue,De)=>ue+De,0),ie=Cs({number:Number(ae),decimalPlaces:((he=a==null?void 0:a.numberAxisFormat)==null?void 0:he.decimalPlaces)||0,useSuffix:!!((be=a==null?void 0:a.numberAxisFormat)!=null&&be.suffix),customSuffix:"",locale:((Ce=a==null?void 0:a.numberAxisFormat)==null?void 0:Ce.locale)||"",currency:((Oe=a==null?void 0:a.numberAxisFormat)==null?void 0:Oe.currency)||""});q.fillText(ie,Z,G)}}:"",...T]}}if(n==="radar"){const D=N1e(r);return ff({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}return n==="bubble"||n==="scatter"?E1e({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,cardConfig:f,isDevMode:h,card:e}):ff({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a})}function VSe({chart:e,elementIndex:t,datasetIndex:n,cardType:r,cfg:s,apply:o}){const i=ee.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)&&USe(e,t,s,o,a),["pie","doughnut","polarArea","funnel"].includes(r)&&WSe(e,t,s,o,a),["stackedBar","pyramid"].includes(r)&&HSe({chart:e,elementIndex:t,datasetIndex:n,cfg:s,apply:o,blurColor:a})}function HSe(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 p,m;typeof f.backgroundColor=="string"&&(f.backgroundColor=new Array(f.data.length).fill(f.backgroundColor),f.borderColor=new Array(f.data.length).fill(f.borderColor)),f.backgroundColor=(p=f==null?void 0:f.backgroundColor)==null?void 0:p.map((g,b)=>b===n&&h===r?g:i),f.borderColor=(m=f==null?void 0:f.borderColor)==null?void 0:m.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 p,m,g,b,x,y;f.backgroundColor=new Array(f.data.length).fill((g=(m=(p=s==null?void 0:s.data)==null?void 0:p.datasets)==null?void 0:m[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 USe(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,p)=>p===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,p)=>p===t?h:s)}):(l=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||l.forEach((u,d)=>{var f,h,p,m,g,b;u.backgroundColor=new Array(u.data.length).fill((p=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:p.backgroundColor),u.borderColor=new Array(u.data.length).fill((b=(g=(m=n==null?void 0:n.data)==null?void 0:m.datasets)==null?void 0:g[d])==null?void 0:b.borderColor)}),e==null||e.update()}function WSe(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,p)=>p===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,p)=>p===t?h:s)}):(l=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||l.forEach((u,d)=>{var f,h,p,m,g,b,x,y;typeof u.backgroundColor=="string"&&(u.backgroundColor=(p=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:p.backgroundColor,u.borderColor=(b=(g=(m=n==null?void 0:n.data)==null?void 0:m.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 S;return(S=n.data.datasets[d].backgroundColor)==null?void 0:S[w]}),u.borderColor=(y=u==null?void 0:u.borderColor)==null?void 0:y.map((v,w)=>{var S;return(S=n.data.datasets[d].borderColor)==null?void 0:S[w]})}),e==null||e.update()}function qSe({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}=rr(t);if(e.type==="map"){const p=h[0],m=((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:p,columnValue:m}]}if(["bar","horizontalBar","line","pie","doughnut","radar","polarArea","funnel"].includes(e.type)){const p=h[0],m=h.slice(1),g=(u=t[r])==null?void 0:u[p];return[{columnName:p,columnValue:g,metric:m[n],value:s}]}if(["stackedBar","pyramid"].includes(e.type)){const p=E1({dataArray:t,groupKey:h[0],pivotKey:h[1],valueKey:h[2]}),m=h[0],g=(d=p[r])==null?void 0:d[m],b=h[1],{keys:x}=rr(p),v=x.slice(1)[n];return[{columnName:m,columnValue:g,metric:h[2],value:s},{columnName:b,columnValue:v,metric:h[2],value:s}]}if(e.type==="bubble"||e.type==="scatter"){const p=h[0],m=(f=t[n])==null?void 0:f[p];return console.log(s,"bubble"),[{columnName:p,columnValue:m,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 YSe(e,t){var r,s;if((((r=e.data.datasets)==null?void 0:r.filter(o=>!!o.fill))||[]).length>0){const o=(s=e==null?void 0:e.data.datasets)==null?void 0:s.map(a=>({...a,backgroundColor:[a.backgroundColor].map(l=>{const u=t.createLinearGradient(0,0,0,400);return u.addColorStop(0,l),u.addColorStop(.7,cme("--semaphor-background")),u})}));return{...e,data:{...e.data,datasets:o}}}return e}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}=un({queryKey:["topojson",t],queryFn:()=>fetch(t).then(p=>p.json()),enabled:n,staleTime:1/0});return{data:r,isLoading:s,isFetching:o,isError:i}}function Ii(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,r=Ee(h=>h.selectedConnectionId),s=Ee(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r||s,{refetch:i,isPending:a,data:l,isLoading:u,isError:d}=un({queryKey:["connections"],queryFn:()=>Vn(`${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 GSe(e){const{connections:t}=Ii(e),n=Ee(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}}function KSe(e){return e.flatMap(t=>t.columns.map(n=>({id:`${t.entityId}-${n.name}`,name:n.name,qualifiedFieldName:n.qualifiedFieldName,dataType:n.dataType,qualifiedEntityName:t.qualifiedEntityName,label:n.label||Yo(n.name),description:n.description,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType})))}function Lf(e){if(gj.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 IM(e){var b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{hasSchemaSupport:r}=GSe(e),s=Ee(x=>{var y;return(y=x.card.dataSource)==null?void 0:y.connectionId}),o=Ee(x=>{var y,v;return(v=(y=x.card.dataSource)==null?void 0:y.selectedEntities)==null?void 0:v.filter(w=>w.type==="model")})||[],i=Ee(x=>{var y,v;return(v=(y=x.card.dataSource)==null?void 0:y.selectedEntities)==null?void 0:v.filter(w=>gj.includes(w.type))})||[],a=Ee(x=>{var y,v;return(v=(y=x.card.dataSource)==null?void 0:y.selectedEntities)==null?void 0:v.filter(w=>w.type==="dataset")})||[];function l(x){return x.type==="dataset"?!!s&&!!x.domainId&&!!x.name:x.type==="model"?!!s&&!!x.id:gj.includes(x.type)?r?!!s&&!!x.name&&!!x.database&&!!x.schema:["S3","API"].includes(x.connectionType)?!!s&&!!x.name:!!s&&!!x.name&&!!x.database:!1}const u=[...o,...i,...a],d=B_({queries:u.map(x=>{let y={};return x.type==="model"?y={connection_id:s,datamodel_id:x.id,database_name:"",schema_name:"",table_name:""}:x.type==="dataset"?y={connection_id:x.connectionId,domain_id:x.domainId,dataset_name:x.name}:y={connection_id:s,datamodel_id:"",database_name:x.database,schema_name:x.schema,table_name:x.name},{queryKey:["columns",s,x],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",y),enabled:!!s&&l(x)}})}),f=d.some(x=>x.isPending),h=d.some(x=>x.isError),p=(b=d.find(x=>x.isError))==null?void 0:b.error,m=d.map((x,y)=>{var S;const v=u[y],w=Lf(v);return{entityId:v.id||v.name,entityType:v.type,entityName:v.name,label:v.label,description:v.description,qualifiedEntityName:w,columns:(S=x.data)==null?void 0:S.columns.map(C=>({id:`${v.name}-${C.column_name}`,name:C.column_name,qualifiedFieldName:C.qualifiedFieldName||C.column_name,dataType:C.data_type,label:C.label||P_(C.column_name),description:C.description||"",qualifiedEntityName:w,entityId:v.id||v.id||v.name,entityName:v.name,entityType:v.type}))}}).filter(x=>{var y;return((y=x==null?void 0:x.columns)==null?void 0:y.length)>0})||[],g=KSe(m);return{columnGroups:m,columns:g,isLoading:f,hasError:h,error:p,refetch:()=>{d.forEach(x=>x.refetch())}}}function ZSe(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 AM(e,t){var m,g,b,x,y,v,w;const{joinabilityMap:n,selectedFields:r,cardConfig:s,autoJoinMetadata:o,baseEntityName:i}=t;if(!n)return{state:"draggable"};if(r.length===0)return{state:"draggable",tooltip:"Select to establish base dataset"};let a;const l=(g=(m=s==null?void 0:s.joinPlan)==null?void 0:m.baseEntity)==null?void 0:g.name,u=(x=(b=o==null?void 0:o.resolvedJoinPlan)==null?void 0:b.baseEntity)==null?void 0:x.name;l?a=l:u?a=u:i?a=i:a=[...new Set(r.map(C=>C.entityName))].filter(Boolean)[0];const d=r.some(S=>S.entityName===e.entityName&&(S.name===e.name||S.id===e.id));if(e.entityName===a)return{state:"base",tooltip:d?"Field already in query (base dataset)":"From base dataset",isSelected:d};const f=n[a];if(!f)return{state:"unreachable",tooltip:"No relationships defined for base dataset"};if(f.canJoinTo.includes(e.entityName))return{state:"draggable",tooltip:`Direct join from ${a}`,joinPath:[a,e.entityName],isSelected:d};const h=(y=f.indirectJoins)==null?void 0:y[e.entityName];if(h&&h.length>0){const S=[a,...h,e.entityName];return{state:"indirect",joinPath:S,tooltip:`Multi-hop join: ${S.join(" → ")}`,isSelected:d}}const p=n[e.entityName];if(p){if(p.canJoinTo.includes(a))return{state:"draggable",tooltip:`Direct join to ${a}`,joinPath:[e.entityName,a],isSelected:d};const S=(v=p.indirectJoins)==null?void 0:v[a];if(S&&S.length>0){const C=[e.entityName,...S,a];return{state:"indirect",joinPath:C,tooltip:`Multi-hop join: ${C.join(" → ")}`,isSelected:d}}}return(w=s==null?void 0:s.joinPlan)!=null&&w.joins&&s.joinPlan.joins.length>0&&ZSe(a,e.entityName,s.joinPlan.joins)?{state:"draggable",tooltip:"Manual join configured",isSelected:d}:{state:"unreachable",tooltip:`Cannot join ${e.entityName} to ${a}`,isSelected:d}}function rU(e,t,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:e===t||e===Lf(n.baseEntity)||t===Lf(n.baseEntity)?!0:n.joins.some(s=>{const o=Lf(s.source),i=Lf(s.target);return o===e&&i===t||o===t&&i===e})}function XSe(e,t,n){var a;const{joinPlan:r,joinabilityMap:s,semanticDomainId:o}=n;if(t.length===0)return{isValid:!0};const i=t[0].qualifiedEntityName;if(!i)return{isValid:!0};if(i===e.qualifiedEntityName)return{isValid:!0};if(e.qualifiedEntityName){if(o&&s)return AM(e,{joinabilityMap:s,selectedFields:t,baseEntityName:(a=r==null?void 0:r.baseEntity)==null?void 0:a.name}).state==="unreachable"?{isValid:!1,showError:!0}:{isValid:!0};if(!r)return{isValid:!1,showError:!0};if(!rU(i,e.qualifiedEntityName,r))return{isValid:!1,showError:!0}}return{isValid:!0}}function sU(){$e.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 oU(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 QSe(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 JSe(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 iU(e,t){return`${e}-${t.qualifiedEntityName}-${t.name}-${Date.now()}`}function aU(e,t){const n=Yo(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 eCe(e,t,n){const r=Ks(e.dataType);return n==="kpi"?r==="date"?"groupBy":"metrics":t.length===0||r==="number"?"metrics":r==="date"||r==="string"||r==="boolean"?"groupBy":"metrics"}function lU(e,t,n=[]){const r=iU(t,e),s=Ks(e.dataType),o=s==="date",i={id:r,name:e.name,dataType:e.dataType,label:P_(e.name),qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityId:e.entityId,entityName:e.entityName,entityType:e.entityType};if(t==="metrics"){const a=s==="number"?"SUM":"COUNT",l=aU(e.label,a),u=JSe({...i,label:l},n,t);return{...i,role:"metric",label:u,aggregate:a}}return t==="groupBy"?{...i,role:"groupby",...o&&{granularity:"month",dateFormat:"YYYY-MM"}}:t==="pivotBy"?{...i,role:"pivotby"}:t==="sortBy"?{...i,role:"sortby",label:e.label,direction:"asc"}:null}function tCe(e){var s,o,i;const t=(s=e.config)==null?void 0:s.metricColumns,n=(o=e.config)==null?void 0:o.groupByColumns,r=(i=e.config)==null?void 0:i.pivotByColumns;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)}function nCe(e){var i,a;const[t]=N.useState({id:"",title:"",type:"bar"}),{getCard:n}=Yt(),r=n(e),s=Xb(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 Xb(e){var O;const{onChartElementClicked:t}=qe(),[n,r]=N.useState(0),s=ee(T=>T.themeStyle),o=ee(T=>T.filteringCards),i=ee(T=>T.selectedSheetId),a=ee(T=>T.selectedLensId),l=ee(T=>T.filterValues),u=N.useRef(l),d=(O=e==null?void 0:e.preferences)==null?void 0:O.onClickFilter,{addFilteringCard:f,addOrUpdateFilterValues:h,removeFilterValues:p,removeFilteringCard:m}=Yt(),{data:g,isLoading:b,isFetching:x,isError:y,isPending:v,queryKey:w,isFilteringCard:S,isSingleCardFrame:C,pagination:j,comparisonMetadata:D}=fa(e),{data:k}=nU(e);let _;_=N.useMemo(()=>{if(!(!(g!=null&&g.records)||!(g!=null&&g.records.length)))return RM({card:e,data:g==null?void 0:g.records,cardType:e.type,queryConfig:e.queryConfig,customCfg:e.customCfg,preferences:e.preferences,topoJson:k})},[g==null?void 0:g.records,e,k,s]);const M=N.useRef({filteringCards:o});N.useEffect(()=>{e.connectionId&&!S&&(u.current=l)},[l,a,e.connectionId,S]),N.useEffect(()=>{var I;S&&(M.current.filteringCards=[...o||[]]),!S&&((I=M.current.filteringCards)==null?void 0:I.find(F=>F.id===e.id))&&C&&r(F=>F+1)},[S,C,e.id,o]);function R(T,I,F,z){var P;if(tCe(e))return;let B=!1;if(!(g!=null&&g.records))return;const $=qSe({card:e,data:g==null?void 0:g.records,datasetIndex:I,clickIndex:F,value:z});if(console.log("fieldValues",$),t==null||t(e,$),!!(((P=e==null?void 0:e.preferences)==null?void 0:P.onClickFilter)??[]).length){if(S){const V=e.id;p(V),m(e)}else{if(B=!0,!$)return;const V=[];$.forEach((L,A)=>{const W=d==null?void 0:d.find(Y=>Y.columnIndex===A);if(!W)return;const U={filterId:e.id+"-"+L.columnName+"-"+i,connectionId:e==null?void 0:e.connectionId,tableName:e.lastSelectedTable,name:L.columnName,expression:W.expression,valueType:I_($[W.columnIndex].columnValue),operation:"=",values:[$[W.columnIndex].columnValue]};V.push(U)}),h(V),f(e)}VSe({chart:T,elementIndex:F,datasetIndex:I,cardType:e.type,cfg:_,apply:B})}}return{isPending:v,isError:y,isLoading:b,isFetching:x,data:g,visualKey:n,handleDatapointClick:R,cfg:_,queryKey:w,pagination:j,comparisonMetadata:D}}function cU(e){var x;const{tokenProps:t}=qe(),n=ee(y=>y.authToken)||e,r=Ee(y=>y.selectedConnectionId),s=Ee(y=>y.selectedDatabaseName),o=Ee(y=>y.selectedDatamodelId),i=Ee(y=>y.selectedSchemaName),a=Ee(y=>y.selectedTableName),{selectedConnection:l}=Ii(),u=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:p,refetch:m}=un({queryKey:["columns",r,s,o,i,a],queryFn:()=>Vn(`${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:p,refetchColumns:m}}function lg(e,t){const[n,r]=N.useState(e);return N.useEffect(()=>{const s=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(s)}},[e,t]),n}var rCe=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 uU=$c(rCe);function A0(e,t=uU){const[n,r]=N.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 sCe(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 uU(e,t)}const i5={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:""},us=pl()(Mb(e=>({...i5,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=>VB(t),resetShareState:()=>{e(t=>{Object.assign(t,i5)})},resetUserSelections:()=>{e(t=>{t.selectedUsers=[],t.usersToRemove=[],t.usersToUpdate=[]})},resetGroupSelections:()=>{e(t=>{t.selectedGroups=[],t.groupsToRemove=[],t.groupsToUpdate=[]})}}}))),dU=()=>us(e=>e.searchQuery),_p=()=>us(e=>e.selectedUsers),Qd=()=>us(e=>e.usersToRemove),Dp=()=>us(e=>e.usersToUpdate),Qb=()=>us(e=>e.selectedTenant),PM=()=>us(e=>e.selectedTab),fU=()=>us(e=>e.currentContext),Wc=()=>us(e=>e.currentMode),OM=()=>us(e=>e.orgWideRole),FM=()=>us(e=>e.allTenantsRole),L1=()=>us(e=>e.tenantWideRole),hU=()=>us(e=>e.groupWideRole),Mp=()=>us(e=>e.selectedGroups),Tp=()=>us(e=>e.groupsToRemove),Rp=()=>us(e=>e.groupsToUpdate),qc=()=>us(e=>e.actions),$M=()=>{const e=dU(),t=lg(e,300),n=qc();return N.useEffect(()=>{n.setDebouncedSearchQuery(t)},[t,n]),{searchQuery:e,debouncedSearchQuery:t,setSearchQuery:n.setSearchQuery}};function Li(e,t){var n;return((n=t.find(r=>r.value===e))==null?void 0:n.label)||e}function oCe(e){return["POWER_USER","ADMIN","EDITOR"].includes(e)}function pU(e){return"tenantId"in e&&e.tenantId?"tenant":"organization"}function iCe(e,t,n){const r=pU(e),s=(n==null?void 0:n.type)||"organization";if(!(!t||!t.shares))if(s==="organization")if(r==="organization"){if("specificOrgUsers"in t.shares)return(t.shares.specificOrgUsers||[]).find(a=>a.orgUserId===e.id)}else return(t.shares.specificTenantUsers||[]).find(a=>a.tenantUserId===e.id);else return(t.shares.specificTenantUsers||[]).find(a=>a.tenantUserId===e.id)}function aCe({user:e}){return pU(e)==="tenant"?c.jsx(Fe,{variant:"outline",className:"text-xs",children:e.role==="POWER_USER"?"Power User":"Viewer"}):c.jsx(Fe,{variant:"outline",className:"text-xs",children:e.role==="ADMIN"?"Admin":e.role==="POWER_USER"?"Power User":"Viewer"})}function lCe({user:e,userShare:t,usersToUpdate:n,currentUser:r,getRoleOptions:s,handleUpdateAccess:o}){if(!(t!=null&&t.role))return null;const i=oCe((r==null?void 0:r.type)||""),a=n.some(f=>f.id===e.id),l=n.find(f=>f.id===e.id),u=l?l.newRole:t==null?void 0:t.role,d=s(e.type);return t?c.jsx("div",{className:"flex items-center gap-2",children:i?c.jsx(Sd,{currentRole:u,onRoleChange:f=>{o(e.id,t.role,f)},roleOptions:d,disabled:!i,allowDropdown:i,className:a?"border-orange-300 bg-orange-100":""}):c.jsx(Fe,{variant:"outline",className:"text-xs",children:Li(u,d)})}):c.jsx(Fe,{variant:"outline",className:"text-xs",children:"Unknown"})}function cCe({hasAccess:e,isUserRemoving:t,isSelected:n,hasAccessFromAPI:r}){return c.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e&&!t&&c.jsxs(Fe,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[c.jsx(bc,{className:"mr-1 h-3 w-3"}),"Has Access"]}),t&&c.jsxs(Fe,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[c.jsx(vt,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&c.jsxs(Fe,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[c.jsx(Qu,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function uCe({isUserRemoving:e,isRemoving:t}){return c.jsx(c.Fragment,{children:e&&c.jsx("span",{className:"text-xs font-medium text-red-600",children:t?c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(On,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"})})}function dCe({existingShares:e,allUsers:t,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in e.shares){const i=e.shares,a=i.specificOrgUsers||[],l=i.specificTenantUsers||[],u=i.orgWide||[],d=i.orgUsersOnly||[],f=i.allTenantsOnly||[];return c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"font-medium",children:"Current Access"}),c.jsxs("div",{className:"space-y-2",children:[a.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",a.length,")"]}),c.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[a.slice(0,3).map((h,p)=>{var x,y;const m=((x=t.find(v=>v.id===h.orgUserId))==null?void 0:x.name)||"Unknown User",g=((y=t.find(v=>v.id===h.orgUserId))==null?void 0:y.type)||"",b=Li(h.role,n(g));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:m}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},p)}),a.length>3&&c.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",a.length-3," more users"]})]})]}),l.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",l.length,")"]}),c.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((h,p)=>{var x,y;const m=((x=t.find(v=>v.id===h.tenantUserId))==null?void 0:x.name)||"Unknown User",g=((y=t.find(v=>v.id===h.tenantUserId))==null?void 0:y.type)||"",b=Li(h.role,n(g));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:m}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},p)}),l.length>3&&c.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.length-3," more users"]})]})]}),u.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((h,p)=>{const m=Li(h.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},p)})})]}),d.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:d.map((h,p)=>{const m=Li(h.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},p)})})]}),f.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:f.map((h,p)=>{const m=Li(h.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},p)})})]}),!a.length&&!l.length&&!u.length&&!d.length&&!f.length&&c.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const i=e.shares.specificTenantUsers||[],a=e.shares.tenantWide||[];return c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"font-medium",children:"Current Access"}),c.jsxs("div",{className:"space-y-2",children:[i.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",i.length,")"]}),c.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((l,u)=>{var p,m;const d=((p=t.find(g=>g.id===l.tenantUserId))==null?void 0:p.name)||"Unknown User",f=((m=t.find(g=>g.id===l.tenantUserId))==null?void 0:m.type)||"",h=Li(l.role,n(f));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:d}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)}),i.length>3&&c.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:a.map((l,u)=>{const d=Li(l.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:d})]},u)})})]}),!i.length&&!a.length&&c.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=e.shares.specificTenantUsers||[],i=e.shares.tenantWide||[];return c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"font-medium",children:"Current Access"}),c.jsxs("div",{className:"space-y-2",children:[o.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),c.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((a,l)=>{var h,p;const u=((h=t.find(m=>m.id===a.tenantUserId))==null?void 0:h.name)||"Unknown User",d=((p=t.find(m=>m.id===a.tenantUserId))==null?void 0:p.type)||"",f=Li(a.role,n(d));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:u}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},l)}),o.length>3&&c.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),i.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((a,l)=>{const u=Li(a.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},l)})})]}),!o.length&&!i.length&&c.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function fCe({isInitialLoading:e,searchQuery:t,availableUsers:n}){return e?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?c.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:t?"No users found matching your search.":"No users available to share with."}):null}function hCe({user:e,userShare:t,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:s,isSelected:o,selectedUser:i,roleOptions:a,currentUser:l,usersToUpdate:u,handleUserToggle:d,handleRemoveAccess:f,handleUpdateAccess:h,handleUserRoleChange:p}){return c.jsxs("div",{className:J("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[c.jsx(dn,{checked:s?!n:o,onCheckedChange:()=>{s?n?d(e.id):f(e.id):d(e.id)}}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("p",{className:"truncate text-sm font-medium",children:e.name}),c.jsx(aCe,{user:e})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?c.jsx(Sd,{currentRole:t==null?void 0:t.role,onRoleChange:m=>h(e.id,t.role,m),roleOptions:a,disabled:!1,allowDropdown:!0}):c.jsx(lCe,{user:e,userShare:t,usersToUpdate:u,currentUser:l,getRoleOptions:()=>a,handleUpdateAccess:h}),o&&!s&&c.jsx("div",{onClick:m=>m.stopPropagation(),children:c.jsx(Sd,{currentRole:(i==null?void 0:i.role)||"VIEWER",onRoleChange:m=>p(e.id,m),roleOptions:a,disabled:!1})})]})]}),c.jsx("p",{className:"truncate text-xs text-muted-foreground",children:e.email}),c.jsx(cCe,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:s}),c.jsx(uCe,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function mU({existingShares:e,isInitialLoading:t,isSearching:n,getRoleOptions:r,allUsers:s=[],currentUser:o,handleUserToggle:i,handleUserRoleChange:a,handleRemoveAccess:l,handleUpdateAccess:u}){const d=_p(),f=Qd(),h=Dp(),p=dU(),m=qc(),g=i||(S=>{const C=d.some(D=>D.id===S),j=f.includes(S);C?m.removeSelectedUser(S):j?m.removeUserFromRemove(S):m.addSelectedUser({id:S,role:"VIEWER"})}),b=a||m.updateSelectedUserRole,x=l||m.addUserToRemove,y=u||((S,C,j)=>{m.addUserToUpdate({id:S,currentRole:C,newRole:j})}),v=s.filter(S=>S.id!==(o==null?void 0:o.id)),w=f;return c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs(ce,{className:"text-sm font-medium",children:["All Users (",(v??[]).length,")"]}),c.jsx(Yn,{children:c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:c.jsx(xr,{className:"h-4 w-4"})})}),c.jsx(Cn,{className:"w-48 max-w-sm",children:c.jsx(dCe,{existingShares:e,allUsers:s,getRoleOptions:r,currentUser:o})})]})})]}),(v==null?void 0:v.length)>0&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>{d.length===v.length?m.setSelectedUsers([]):m.setSelectedUsers(v.map(S=>({id:S.id,role:"VIEWER"})))},className:"h-7 text-xs",children:d.length===v.length?"Deselect all":"Select all"})]}),c.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[c.jsx(fCe,{isInitialLoading:t,isSearching:n,searchQuery:p,availableUsers:v||[]}),!t&&!n&&(v==null?void 0:v.length)>0&&v.map(S=>{const C=e?iCe(S,e,o):void 0,j=w.includes(S.id),D=!!C,k=D&&!j,_=d.some(O=>O.id===S.id),M=d.find(O=>O.id===S.id),R=r(S.type);return c.jsx(hCe,{user:S,userShare:C,isUserRemoving:j,hasAccess:k,hasAccessFromAPI:D,isSelected:_,selectedUser:M,roleOptions:R,currentUser:o,usersToUpdate:h,handleUserToggle:g,handleRemoveAccess:x,handleUpdateAccess:y,handleUserRoleChange:b},S.id)})]})]})}var LM="Radio",[pCe,gU]=_r(LM),[mCe,gCe]=pCe(LM),bU=E.forwardRef((e,t)=>{const{__scopeRadio:n,name:r,checked:s=!1,required:o,disabled:i,value:a="on",onCheck:l,form:u,...d}=e,[f,h]=E.useState(null),p=ft(t,b=>h(b)),m=E.useRef(!1),g=f?u||!!f.closest("form"):!0;return c.jsxs(mCe,{scope:n,checked:s,disabled:i,children:[c.jsx(Be.button,{type:"button",role:"radio","aria-checked":s,"data-state":vU(s),"data-disabled":i?"":void 0,disabled:i,value:a,...d,ref:p,onClick:ke(e.onClick,b=>{s||l==null||l(),g&&(m.current=b.isPropagationStopped(),m.current||b.stopPropagation())})}),g&&c.jsx(bCe,{control:f,bubbles:!m.current,name:r,value:a,checked:s,required:o,disabled:i,form:u,style:{transform:"translateX(-100%)"}})]})});bU.displayName=LM;var xU="RadioIndicator",yU=E.forwardRef((e,t)=>{const{__scopeRadio:n,forceMount:r,...s}=e,o=gCe(xU,n);return c.jsx(sr,{present:r||o.checked,children:c.jsx(Be.span,{"data-state":vU(o.checked),"data-disabled":o.disabled?"":void 0,...s,ref:t})})});yU.displayName=xU;var bCe=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=E.useRef(null),i=j1(n),a=h1(t);return E.useEffect(()=>{const l=o.current,u=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(u,"checked").set;if(i!==n&&f){const h=new Event("click",{bubbles:r});f.call(l,n),l.dispatchEvent(h)}},[i,n,r]),c.jsx("input",{type:"radio","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:o,style:{...e.style,...a,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function vU(e){return e?"checked":"unchecked"}var xCe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],zM="RadioGroup",[yCe]=_r(zM,[up,gU]),wU=up(),SU=gU(),[vCe,wCe]=yCe(zM),CU=E.forwardRef((e,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:s,value:o,required:i=!1,disabled:a=!1,orientation:l,dir:u,loop:d=!0,onValueChange:f,...h}=e,p=wU(n),m=Vd(u),[g,b]=$r({prop:o,defaultProp:s,onChange:f});return c.jsx(vCe,{scope:n,name:r,required:i,disabled:a,value:g,onValueChange:b,children:c.jsx(wD,{asChild:!0,...p,orientation:l,dir:m,loop:d,children:c.jsx(Be.div,{role:"radiogroup","aria-required":i,"aria-orientation":l,"data-disabled":a?"":void 0,dir:m,...h,ref:t})})})});CU.displayName=zM;var NU="RadioGroupItem",jU=E.forwardRef((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...s}=e,o=wCe(NU,n),i=o.disabled||r,a=wU(n),l=SU(n),u=E.useRef(null),d=ft(t,u),f=o.value===s.value,h=E.useRef(!1);return E.useEffect(()=>{const p=g=>{xCe.includes(g.key)&&(h.current=!0)},m=()=>h.current=!1;return document.addEventListener("keydown",p),document.addEventListener("keyup",m),()=>{document.removeEventListener("keydown",p),document.removeEventListener("keyup",m)}},[]),c.jsx(SD,{asChild:!0,...a,focusable:!i,active:f,children:c.jsx(bU,{disabled:i,required:o.required,checked:f,...l,...s,name:o.name,ref:d,onCheck:()=>o.onValueChange(s.value),onKeyDown:ke(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:ke(s.onFocus,()=>{var p;h.current&&((p=u.current)==null||p.click())})})})});jU.displayName=NU;var SCe="RadioGroupIndicator",kU=E.forwardRef((e,t)=>{const{__scopeRadioGroup:n,...r}=e,s=SU(n);return c.jsx(yU,{...s,...r,ref:t})});kU.displayName=SCe;var EU=CU,_U=jU,CCe=kU;const ma=E.forwardRef(({className:e,...t},n)=>c.jsx(EU,{className:J("grid gap-2",e),...t,ref:n}));ma.displayName=EU.displayName;const Nr=E.forwardRef(({className:e,...t},n)=>c.jsx(_U,{ref:n,className:J("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:c.jsx(CCe,{className:"flex items-center justify-center",children:c.jsx(X_,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Nr.displayName=_U.displayName;function BM({shareType:e,onShareTypeChange:t,currentUser:n,options:r}){const s=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return c.jsxs("div",{className:"space-y-3",children:[c.jsx(ma,{value:e,onValueChange:t,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>c.jsxs("div",{children:[c.jsx(Nr,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),c.jsxs(ce,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||c.jsx(xc,{className:"mb-3 h-6 w-6"}),c.jsxs("div",{className:"space-y-1 text-center",children:[c.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),c.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!s&&r.some(o=>o.value==="all_users")&&c.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, can share with all users."})]})}var NN,VM="HoverCard",[DU]=_r(VM,[ya]),z1=ya(),[NCe,B1]=DU(VM),MU=e=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:s,onOpenChange:o,openDelay:i=700,closeDelay:a=300}=e,l=z1(t),u=E.useRef(0),d=E.useRef(0),f=E.useRef(!1),h=E.useRef(!1),[p=!1,m]=$r({prop:r,defaultProp:s,onChange:o}),g=E.useCallback(()=>{clearTimeout(d.current),u.current=window.setTimeout(()=>m(!0),i)},[i,m]),b=E.useCallback(()=>{clearTimeout(u.current),!f.current&&!h.current&&(d.current=window.setTimeout(()=>m(!1),a))},[a,m]),x=E.useCallback(()=>m(!1),[m]);return E.useEffect(()=>()=>{clearTimeout(u.current),clearTimeout(d.current)},[]),c.jsx(NCe,{scope:t,open:p,onOpenChange:m,onOpen:g,onClose:b,onDismiss:x,hasSelectionRef:f,isPointerDownOnContentRef:h,children:c.jsx(lp,{...l,children:n})})};MU.displayName=VM;var TU="HoverCardTrigger",RU=E.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=B1(TU,n),o=z1(n);return c.jsx(cp,{asChild:!0,...o,children:c.jsx(Be.a,{"data-state":s.open?"open":"closed",...r,ref:t,onPointerEnter:ke(e.onPointerEnter,Yv(s.onOpen)),onPointerLeave:ke(e.onPointerLeave,Yv(s.onClose)),onFocus:ke(e.onFocus,s.onOpen),onBlur:ke(e.onBlur,s.onClose),onTouchStart:ke(e.onTouchStart,i=>i.preventDefault())})})});RU.displayName=TU;var HM="HoverCardPortal",[jCe,kCe]=DU(HM,{forceMount:void 0}),IU=e=>{const{__scopeHoverCard:t,forceMount:n,children:r,container:s}=e,o=B1(HM,t);return c.jsx(jCe,{scope:t,forceMount:n,children:c.jsx(sr,{present:n||o.open,children:c.jsx(Ud,{asChild:!0,container:s,children:r})})})};IU.displayName=HM;var qv="HoverCardContent",AU=E.forwardRef((e,t)=>{const n=kCe(qv,e.__scopeHoverCard),{forceMount:r=n.forceMount,...s}=e,o=B1(qv,e.__scopeHoverCard);return c.jsx(sr,{present:r||o.open,children:c.jsx(ECe,{"data-state":o.open?"open":"closed",...s,onPointerEnter:ke(e.onPointerEnter,Yv(o.onOpen)),onPointerLeave:ke(e.onPointerLeave,Yv(o.onClose)),ref:t})})});AU.displayName=qv;var ECe=E.forwardRef((e,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:i,...a}=e,l=B1(qv,n),u=z1(n),d=E.useRef(null),f=ft(t,d),[h,p]=E.useState(!1);return E.useEffect(()=>{if(h){const m=document.body;return NN=m.style.userSelect||m.style.webkitUserSelect,m.style.userSelect="none",m.style.webkitUserSelect="none",()=>{m.style.userSelect=NN,m.style.webkitUserSelect=NN}}},[h]),E.useEffect(()=>{if(d.current){const m=()=>{p(!1),l.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var b;((b=document.getSelection())==null?void 0:b.toString())!==""&&(l.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",m),()=>{document.removeEventListener("pointerup",m),l.hasSelectionRef.current=!1,l.isPointerDownOnContentRef.current=!1}}},[l.isPointerDownOnContentRef,l.hasSelectionRef]),E.useEffect(()=>{d.current&&MCe(d.current).forEach(g=>g.setAttribute("tabindex","-1"))}),c.jsx(Hd,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:i,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:ke(o,m=>{m.preventDefault()}),onDismiss:l.onDismiss,children:c.jsx($b,{...u,...a,onPointerDown:ke(a.onPointerDown,m=>{m.currentTarget.contains(m.target)&&p(!0),l.hasSelectionRef.current=!1,l.isPointerDownOnContentRef.current=!0}),ref:f,style:{...a.style,userSelect:h?"text":void 0,WebkitUserSelect:h?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),_Ce="HoverCardArrow",DCe=E.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=z1(n);return c.jsx(Lb,{...s,...r,ref:t})});DCe.displayName=_Ce;function Yv(e){return t=>t.pointerType==="touch"?void 0:e()}function MCe(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;n.nextNode();)t.push(n.currentNode);return t}var TCe=MU,RCe=RU,PU=AU;const Ip=TCe,Ap=RCe,Jd=E.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>c.jsx(PU,{ref:s,align:t,sideOffset:n,className:J("z-50 w-64 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}));Jd.displayName=PU.displayName;const ui=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function ICe({currentUser:e,currentShare:t,isSharing:n,onUpdateAccess:r,allUsersToUpdate:s=null,allUsersToRemove:o=!1,isUpdating:i=!1,isRemoving:a=!1}){const l=Wc(),u=ui().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),p=s!==null&&s.newRole!==d,m=o,g=d==="NONE"||!d,b=y=>{switch(y){case"VIEWER":return c.jsx(bc,{className:"h-4 w-4"});case"EDITOR":return c.jsx(a1,{className:"h-4 w-4"});case"CONTRIBUTOR":return c.jsx(Eae,{className:"h-4 w-4"});default:return c.jsx(bc,{className:"h-4 w-4"})}},x=y=>{r(d,y)};return c.jsx("div",{className:"space-y-4",children:c.jsxs(xo,{className:J("pb-6",p&&!m&&!g?"border-orange-300 bg-orange-50":h?"border-green-300 bg-green-50":m||g?"border-destructive bg-destructive/10":""),children:[c.jsxs(vi,{children:[c.jsxs(wi,{className:"flex items-center gap-2 text-base",children:[c.jsx(is,{className:"h-5 w-5"}),"Share with All"," ",l==="allOrgUsers"?"Organization":l==="allTenantUsers"?"Tenant":l==="specificOrgUsers"?"Org":"Tenant"," ","Users",h&&c.jsx(Fe,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),p&&c.jsx(Fe,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(m||g)&&c.jsx(Fe,{variant:"destructive",className:"ml-2",children:"No Access"})]}),c.jsx(o8,{children:m||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(Si,{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(Ip,{children:[c.jsx(Ap,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:c.jsx(xr,{className:"h-3 w-3"})})}),c.jsx(Jd,{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(oe,{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 OU({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,p=(g,b)=>{o(g,b)},m=()=>{i()};return c.jsx(ICe,{currentUser:e,currentShare:f,isSharing:n,isUpdating:r,isRemoving:s,onUpdateAccess:p,onRemoveAccess:m,allUsersToUpdate:h,allUsersToRemove:l})}const ACe=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 Vn(s,t,r)};function UM(e={}){var o,i,a;const{authToken:t,tokenProps:n}=qe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=un({queryKey:["unified-users",e],queryFn:()=>ACe(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 Bh(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=At.DASHBOARD,userType:s,tenantId:o}=e,i=N.useMemo(()=>({search:t,active:!0,...s?{type:s}:{},...s==="tenant"&&o?{tenantId:o}:{}}),[t,s,o]),{users:a,isLoading:l,isError:u}=UM(i),d=Bfe(r,n);return{allUsers:a,isLoadingUsers:l,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function PCe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var L,A;const a=PM(),l=Qb(),{searchQuery:u,setSearchQuery:d,debouncedSearchQuery:f}=$M(),h=_p(),p=Qd(),m=Dp(),g=Wc(),b=OM(),x=qc(),[y,v]=N.useState("specific_users"),w=()=>{if(a==="org")return"organization";if(a==="tenant")return"tenant"},S=()=>{if(a==="tenant"&&l)return l},{allUsers:C,existingShares:j,isLoadingUsers:D}=Bh({debouncedSearchQuery:f,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:w(),tenantId:S()});N.useEffect(()=>{x.setCurrentContext("org-tab"),x.setCurrentMode(y==="all_users"?"allOrgUsers":"specificOrgUsers")},[x,y]);const k=W=>{var Y,K;const U=W;if(v(U),r==null||r(U),x.setCurrentContext("org-tab"),U==="specific_users")x.setCurrentMode("specificOrgUsers");else if(U==="all_users"){x.setCurrentMode("allOrgUsers");const H=(K=(Y=j==null?void 0:j.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:K[0];H&&H.role!==void 0&&x.setOrgWideRole(H.role)}},_=C.filter(W=>W.name.toLowerCase().includes(u.toLowerCase())||W.email.toLowerCase().includes(u.toLowerCase())),M=C.filter(W=>h.some(U=>U.id===W.id)),R=W=>{var H,q;const U=h.some(X=>X.id===W),Y=p.includes(W),K=(q=(H=j==null?void 0:j.shares)==null?void 0:H.specificOrgUsers)==null?void 0:q.some(X=>X.orgUserId===W);U?x.removeSelectedUser(W):Y?x.removeUserFromRemove(W):K||x.addSelectedUser({id:W,role:"VIEWER"})},O=(W,U)=>{x.updateSelectedUserRole(W,U)},T=W=>{x.addUserToRemove(W),x.removeSelectedUser(W)},I=W=>{x.removeUserFromRemove(W)},F=W=>{x.removeUserFromUpdate(W)},z=(W,U)=>{x.setOrgWideRole(U)},B=()=>{x.setOrgWideRole(($==null?void 0:$.role)||"NONE")},$=(A=(L=j==null?void 0:j.shares)==null?void 0:L.orgUsersOnly)==null?void 0:A[0];N.useEffect(()=>{y==="all_users"&&$&&$.role!==void 0&&x.setOrgWideRole($.role)},[y,$,x]);const P=D,V=!1;return n?c.jsxs(c.Fragment,{children:[c.jsx(BM,{shareType:y,onShareTypeChange:k,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:c.jsx(xc,{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(is,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),y==="specific_users"?c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsx(yv,{value:u,onChange:d}),c.jsx(AB,{selectedUsers:h,selectedUserObjects:M,onRemove:R,onRoleChange:O,getRoleOptions:ui}),c.jsx(PB,{usersToRemove:p,allUsers:_,onRemove:I}),c.jsx(OB,{usersToUpdate:m,allUsers:_,onRemove:F,getRoleOptions:ui}),c.jsx(mU,{existingShares:j,isInitialLoading:P,isSearching:V,resource:e,onShare:()=>{},getRoleOptions:ui,allUsers:_,currentUser:n,handleUserToggle:R,handleUserRoleChange:O,handleRemoveAccess:T,handleUpdateAccess:(W,U,Y)=>{x.addUserToUpdate({id:W,currentRole:U,newRole:Y})}})]}):c.jsx("div",{className:"mt-3",children:c.jsx(OU,{currentUser:n,currentShare:$,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:z,onRemoveAccess:B,allUsersToUpdate:g==="allOrgUsers"&&b!==(($==null?void 0:$.role)||"NONE")?{currentRole:($==null?void 0:$.role)||"NONE",newRole:b}:null,allUsersToRemove:g==="allOrgUsers"&&($==null?void 0:$.role)===void 0})})]}):null}function OCe(e){switch(e){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function FCe(e){switch(e){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function FU({groups:e,existingGroupShares:t,isLoading:n,resource:r,getRoleOptions:s,currentUser:o,handleGroupToggle:i,handleGroupRoleChange:a,handleRemoveAccess:l,handleUpdateAccess:u}){const d=Mp(),f=Tp(),h=Rp(),p=qc(),m=s(o==null?void 0:o.type);return n?c.jsx("div",{className:"flex items-center justify-center py-6",children:c.jsx(On,{className:"h-6 w-6 animate-spin"})}):e.length===0?c.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{children:"Available Groups"}),c.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:e.map(g=>{const b=t==null?void 0:t.find(j=>j.groupId===g.id),x=d.some(j=>j.id===g.id),y=f.includes(g.id),v=h.find(j=>j.id===g.id),w=!!b&&!y;let C=(b==null?void 0:b.role)||"VIEWER";if(x){const j=d.find(D=>D.id===g.id);C=(j==null?void 0:j.role)||"VIEWER"}else v&&(C=v.newRole);return c.jsxs("div",{className:J("flex items-center justify-between rounded-lg p-2 transition-colors",w&&!y?"border border-green-200 bg-green-50":y?"border border-red-200 bg-red-50":x?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[c.jsxs("div",{className:"flex items-center space-x-3",children:[c.jsx(dn,{id:`group-${g.id}`,checked:w?!y:x,disabled:!1,onCheckedChange:()=>{w?y?p.removeGroupFromRemove(g.id):l==null||l(g.id):i==null||i(g.id)}}),c.jsxs("label",{htmlFor:`group-${g.id}`,className:"flex cursor-pointer flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:g.name}),g.type==="ORG_GROUP"?c.jsx(md,{className:"h-3 w-3 text-blue-600"}):c.jsx(is,{className:"h-3 w-3 text-green-600"}),c.jsxs(Fe,{variant:"secondary",className:"text-xs",children:[g.memberCount," members"]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:J("text-xs",FCe(g.type)),children:OCe(g.type)}),g.type==="TENANT_GROUP"&&g.tenantName&&c.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",g.tenantName]})]}),g.description&&c.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]})]}),c.jsxs("div",{className:"flex items-center space-x-2",children:[w&&!y?c.jsx(Sd,{currentRole:C,onRoleChange:j=>{b&&j!==b.role&&(u==null||u(g.id,b.role,j))},roleOptions:m,disabled:!1,allowDropdown:!0,className:v?"border-orange-300 bg-orange-100":""}):x&&!w&&c.jsx(Sd,{currentRole:C,onRoleChange:j=>a==null?void 0:a(g.id,j),roleOptions:m,disabled:!1}),w&&!y&&!v&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>l==null?void 0:l(g.id),children:c.jsx(vt,{className:"h-4 w-4"})}),y&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromRemove(g.id),children:"Undo"}),v&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromUpdate(g.id),children:"Cancel"})]})]},g.id)})})]})}function $U({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(md,{className:"h-4 w-4 text-blue-600"}):c.jsx(is,{className:"h-4 w-4 text-green-600"}),c.jsx("span",{className:"text-sm font-medium",children:a.name}),c.jsxs(Fe,{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(Sd,{currentRole:i.role,onRoleChange:l=>r(i.id,l),roleOptions:o}),c.jsx(oe,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>n(i.id),children:c.jsx(vt,{className:"h-3 w-3"})})]})]},i.id):null})})]})}const $Ce=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 Vn(s,t,r)},LCe=async(e,t,n)=>{const r=`${e}/management/v1/groups/${n}/members`;return await Vn(r,t)};function WM(e={}){var o,i,a;const{authToken:t,tokenProps:n}=qe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=un({queryKey:["groups",e],queryFn:()=>$Ce(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 zCe(e){const{authToken:t,tokenProps:n}=qe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId);return un({queryKey:["group-members",e],queryFn:()=>LCe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r&&!!e,retry:1,staleTime:6e4})}function LU(e,t){const{tokenProps:n}=qe(),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)),WM(r)}function qk(e,[t,n]){return Math.min(n,Math.max(t,e))}var zU=E.forwardRef((e,t)=>{const{children:n,...r}=e,s=E.Children.toArray(n),o=s.find(VCe);if(o){const i=o.props.children,a=s.map(l=>l===o?E.Children.count(i)>1?E.Children.only(null):E.isValidElement(i)?i.props.children:null:l);return c.jsx(Yk,{...r,ref:t,children:E.isValidElement(i)?E.cloneElement(i,void 0,a):null})}return c.jsx(Yk,{...r,ref:t,children:n})});zU.displayName="Slot";var Yk=E.forwardRef((e,t)=>{const{children:n,...r}=e;if(E.isValidElement(n)){const s=UCe(n),o=HCe(r,n.props);return n.type!==E.Fragment&&(o.ref=t?Es(t,s):s),E.cloneElement(n,o)}return E.Children.count(n)>1?E.Children.only(null):null});Yk.displayName="SlotClone";var BCe=({children:e})=>c.jsx(c.Fragment,{children:e});function VCe(e){return E.isValidElement(e)&&e.type===BCe}function HCe(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)=>{o(...a),s(...a)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function UCe(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 WCe=[" ","Enter","ArrowUp","ArrowDown"],qCe=[" ","Enter"],Jb="Select",[V1,H1,YCe]=l1(Jb),[Pp]=_r(Jb,[YCe,ya]),U1=ya(),[GCe,Yc]=Pp(Jb),[KCe,ZCe]=Pp(Jb),BU=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:p,form:m}=e,g=U1(t),[b,x]=E.useState(null),[y,v]=E.useState(null),[w,S]=E.useState(!1),C=Vd(u),[j=!1,D]=$r({prop:r,defaultProp:s,onChange:o}),[k,_]=$r({prop:i,defaultProp:a,onChange:l}),M=E.useRef(null),R=b?m||!!b.closest("form"):!0,[O,T]=E.useState(new Set),I=Array.from(O).map(F=>F.props.value).join(";");return c.jsx(lp,{...g,children:c.jsxs(GCe,{required:p,scope:t,trigger:b,onTriggerChange:x,valueNode:y,onValueNodeChange:v,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:nr(),value:k,onValueChange:_,open:j,onOpenChange:D,dir:C,triggerPointerDownPosRef:M,disabled:h,children:[c.jsx(V1.Provider,{scope:t,children:c.jsx(KCe,{scope:e.__scopeSelect,onNativeOptionAdd:E.useCallback(F=>{T(z=>new Set(z).add(F))},[]),onNativeOptionRemove:E.useCallback(F=>{T(z=>{const B=new Set(z);return B.delete(F),B})},[]),children:n})}),R?c.jsxs(hW,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:k,onChange:F=>_(F.target.value),disabled:h,form:m,children:[k===void 0?c.jsx("option",{value:""}):null,Array.from(O)]},I):null]})})};BU.displayName=Jb;var VU="SelectTrigger",HU=E.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=U1(n),i=Yc(VU,n),a=i.disabled||r,l=ft(t,i.onTriggerChange),u=H1(n),d=E.useRef("touch"),[f,h,p]=pW(g=>{const b=u().filter(v=>!v.disabled),x=b.find(v=>v.value===i.value),y=mW(b,g,x);y!==void 0&&i.onValueChange(y.value)}),m=g=>{a||(i.onOpenChange(!0),p()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return c.jsx(cp,{asChild:!0,...o,children:c.jsx(Be.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":fW(i.value)?"":void 0,...s,ref:l,onClick:ke(s.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&m(g)}),onPointerDown:ke(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"&&(m(g),g.preventDefault())}),onKeyDown:ke(s.onKeyDown,g=>{const b=f.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(b&&g.key===" ")&&WCe.includes(g.key)&&(m(),g.preventDefault())})})})});HU.displayName=VU;var UU="SelectValue",WU=E.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:i="",...a}=e,l=Yc(UU,n),{onValueNodeHasChildrenChange:u}=l,d=o!==void 0,f=ft(t,l.onValueNodeChange);return Lr(()=>{u(d)},[u,d]),c.jsx(Be.span,{...a,ref:f,style:{pointerEvents:"none"},children:fW(l.value)?c.jsx(c.Fragment,{children:i}):o})});WU.displayName=UU;var XCe="SelectIcon",qU=E.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return c.jsx(Be.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});qU.displayName=XCe;var QCe="SelectPortal",YU=e=>c.jsx(Ud,{asChild:!0,...e});YU.displayName=QCe;var Td="SelectContent",GU=E.forwardRef((e,t)=>{const n=Yc(Td,e.__scopeSelect),[r,s]=E.useState();if(Lr(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?gc.createPortal(c.jsx(KU,{scope:e.__scopeSelect,children:c.jsx(V1.Slot,{scope:e.__scopeSelect,children:c.jsx("div",{children:e.children})})}),o):null}return c.jsx(ZU,{...e,ref:t})});GU.displayName=Td;var oi=10,[KU,Gc]=Pp(Td),JCe="SelectContentImpl",ZU=E.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:p,sticky:m,hideWhenDetached:g,avoidCollisions:b,...x}=e,y=Yc(Td,n),[v,w]=E.useState(null),[S,C]=E.useState(null),j=ft(t,K=>w(K)),[D,k]=E.useState(null),[_,M]=E.useState(null),R=H1(n),[O,T]=E.useState(!1),I=E.useRef(!1);E.useEffect(()=>{if(v)return zb(v)},[v]),c1();const F=E.useCallback(K=>{const[H,...q]=R().map(G=>G.ref.current),[X]=q.slice(-1),Z=document.activeElement;for(const G of K)if(G===Z||(G==null||G.scrollIntoView({block:"nearest"}),G===H&&S&&(S.scrollTop=0),G===X&&S&&(S.scrollTop=S.scrollHeight),G==null||G.focus(),document.activeElement!==Z))return},[R,S]),z=E.useCallback(()=>F([D,v]),[F,D,v]);E.useEffect(()=>{O&&z()},[O,z]);const{onOpenChange:B,triggerPointerDownPosRef:$}=y;E.useEffect(()=>{if(v){let K={x:0,y:0};const H=X=>{var Z,G;K={x:Math.abs(Math.round(X.pageX)-(((Z=$.current)==null?void 0:Z.x)??0)),y:Math.abs(Math.round(X.pageY)-(((G=$.current)==null?void 0:G.y)??0))}},q=X=>{K.x<=10&&K.y<=10?X.preventDefault():v.contains(X.target)||B(!1),document.removeEventListener("pointermove",H),$.current=null};return $.current!==null&&(document.addEventListener("pointermove",H),document.addEventListener("pointerup",q,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",H),document.removeEventListener("pointerup",q,{capture:!0})}}},[v,B,$]),E.useEffect(()=>{const K=()=>B(!1);return window.addEventListener("blur",K),window.addEventListener("resize",K),()=>{window.removeEventListener("blur",K),window.removeEventListener("resize",K)}},[B]);const[P,V]=pW(K=>{const H=R().filter(Z=>!Z.disabled),q=H.find(Z=>Z.ref.current===document.activeElement),X=mW(H,K,q);X&&setTimeout(()=>X.ref.current.focus())}),L=E.useCallback((K,H,q)=>{const X=!I.current&&!q;(y.value!==void 0&&y.value===H||X)&&(k(K),X&&(I.current=!0))},[y.value]),A=E.useCallback(()=>v==null?void 0:v.focus(),[v]),W=E.useCallback((K,H,q)=>{const X=!I.current&&!q;(y.value!==void 0&&y.value===H||X)&&M(K)},[y.value]),U=r==="popper"?Gk:XU,Y=U===Gk?{side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:b}:{};return c.jsx(KU,{scope:n,content:v,viewport:S,onViewportChange:C,itemRefCallback:L,selectedItem:D,onItemLeave:A,itemTextRefCallback:W,focusSelectedItem:z,selectedItemText:_,position:r,isPositioned:O,searchRef:P,children:c.jsx(dp,{as:zU,allowPinchZoom:!0,children:c.jsx(op,{asChild:!0,trapped:y.open,onMountAutoFocus:K=>{K.preventDefault()},onUnmountAutoFocus:ke(s,K=>{var H;(H=y.trigger)==null||H.focus({preventScroll:!0}),K.preventDefault()}),children:c.jsx(Hd,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:K=>K.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:c.jsx(U,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:K=>K.preventDefault(),...x,...Y,onPlaced:()=>T(!0),ref:j,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:ke(x.onKeyDown,K=>{const H=K.ctrlKey||K.altKey||K.metaKey;if(K.key==="Tab"&&K.preventDefault(),!H&&K.key.length===1&&V(K.key),["ArrowUp","ArrowDown","Home","End"].includes(K.key)){let X=R().filter(Z=>!Z.disabled).map(Z=>Z.ref.current);if(["ArrowUp","End"].includes(K.key)&&(X=X.slice().reverse()),["ArrowUp","ArrowDown"].includes(K.key)){const Z=K.target,G=X.indexOf(Z);X=X.slice(G+1)}setTimeout(()=>F(X)),K.preventDefault()}})})})})})})});ZU.displayName=JCe;var eNe="SelectItemAlignedPosition",XU=E.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=Yc(Td,n),i=Gc(Td,n),[a,l]=E.useState(null),[u,d]=E.useState(null),f=ft(t,j=>d(j)),h=H1(n),p=E.useRef(!1),m=E.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:x,focusSelectedItem:y}=i,v=E.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&u&&g&&b&&x){const j=o.trigger.getBoundingClientRect(),D=u.getBoundingClientRect(),k=o.valueNode.getBoundingClientRect(),_=x.getBoundingClientRect();if(o.dir!=="rtl"){const Z=_.left-D.left,G=k.left-Z,Q=j.left-G,ne=j.width+Q,ae=Math.max(ne,D.width),ie=window.innerWidth-oi,he=qk(G,[oi,Math.max(oi,ie-ae)]);a.style.minWidth=ne+"px",a.style.left=he+"px"}else{const Z=D.right-_.right,G=window.innerWidth-k.right-Z,Q=window.innerWidth-j.right-G,ne=j.width+Q,ae=Math.max(ne,D.width),ie=window.innerWidth-oi,he=qk(G,[oi,Math.max(oi,ie-ae)]);a.style.minWidth=ne+"px",a.style.right=he+"px"}const M=h(),R=window.innerHeight-oi*2,O=g.scrollHeight,T=window.getComputedStyle(u),I=parseInt(T.borderTopWidth,10),F=parseInt(T.paddingTop,10),z=parseInt(T.borderBottomWidth,10),B=parseInt(T.paddingBottom,10),$=I+F+O+B+z,P=Math.min(b.offsetHeight*5,$),V=window.getComputedStyle(g),L=parseInt(V.paddingTop,10),A=parseInt(V.paddingBottom,10),W=j.top+j.height/2-oi,U=R-W,Y=b.offsetHeight/2,K=b.offsetTop+Y,H=I+F+K,q=$-H;if(H<=W){const Z=M.length>0&&b===M[M.length-1].ref.current;a.style.bottom="0px";const G=u.clientHeight-g.offsetTop-g.offsetHeight,Q=Math.max(U,Y+(Z?A:0)+G+z),ne=H+Q;a.style.height=ne+"px"}else{const Z=M.length>0&&b===M[0].ref.current;a.style.top="0px";const Q=Math.max(W,I+g.offsetTop+(Z?L:0)+Y)+q;a.style.height=Q+"px",g.scrollTop=H-W+g.offsetTop}a.style.margin=`${oi}px 0`,a.style.minHeight=P+"px",a.style.maxHeight=R+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,o.trigger,o.valueNode,a,u,g,b,x,o.dir,r]);Lr(()=>v(),[v]);const[w,S]=E.useState();Lr(()=>{u&&S(window.getComputedStyle(u).zIndex)},[u]);const C=E.useCallback(j=>{j&&m.current===!0&&(v(),y==null||y(),m.current=!1)},[v,y]);return c.jsx(nNe,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:C,children:c.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:w},children:c.jsx(Be.div,{...s,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});XU.displayName=eNe;var tNe="SelectPopperPosition",Gk=E.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=oi,...o}=e,i=U1(n);return c.jsx($b,{...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)"}})});Gk.displayName=tNe;var[nNe,qM]=Pp(Td,{}),Kk="SelectViewport",QU=E.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Gc(Kk,n),i=qM(Kk,n),a=ft(t,o.onViewportChange),l=E.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(V1.Slot,{scope:n,children:c.jsx(Be.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...s.style},onScroll:ke(s.onScroll,u=>{const d=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const p=Math.abs(l.current-d.scrollTop);if(p>0){const m=window.innerHeight-oi*2,g=parseFloat(f.style.minHeight),b=parseFloat(f.style.height),x=Math.max(g,b);if(x<m){const y=x+p,v=Math.min(m,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})})})]})});QU.displayName=Kk;var JU="SelectGroup",[rNe,sNe]=Pp(JU),eW=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=nr();return c.jsx(rNe,{scope:n,id:s,children:c.jsx(Be.div,{role:"group","aria-labelledby":s,...r,ref:t})})});eW.displayName=JU;var tW="SelectLabel",nW=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=sNe(tW,n);return c.jsx(Be.div,{id:s.id,...r,ref:t})});nW.displayName=tW;var Gv="SelectItem",[oNe,rW]=Pp(Gv),sW=E.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...i}=e,a=Yc(Gv,n),l=Gc(Gv,n),u=a.value===r,[d,f]=E.useState(o??""),[h,p]=E.useState(!1),m=ft(t,y=>{var v;return(v=l.itemRefCallback)==null?void 0:v.call(l,y,r,s)}),g=nr(),b=E.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(oNe,{scope:n,value:r,disabled:s,textId:g,isSelected:u,onItemTextChange:E.useCallback(y=>{f(v=>v||((y==null?void 0:y.textContent)??"").trim())},[]),children:c.jsx(V1.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:c.jsx(Be.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:m,onFocus:ke(i.onFocus,()=>p(!0)),onBlur:ke(i.onBlur,()=>p(!1)),onClick:ke(i.onClick,()=>{b.current!=="mouse"&&x()}),onPointerUp:ke(i.onPointerUp,()=>{b.current==="mouse"&&x()}),onPointerDown:ke(i.onPointerDown,y=>{b.current=y.pointerType}),onPointerMove:ke(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:ke(i.onPointerLeave,y=>{var v;y.currentTarget===document.activeElement&&((v=l.onItemLeave)==null||v.call(l))}),onKeyDown:ke(i.onKeyDown,y=>{var w;((w=l.searchRef)==null?void 0:w.current)!==""&&y.key===" "||(qCe.includes(y.key)&&x(),y.key===" "&&y.preventDefault())})})})})});sW.displayName=Gv;var Fm="SelectItemText",oW=E.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,i=Yc(Fm,n),a=Gc(Fm,n),l=rW(Fm,n),u=ZCe(Fm,n),[d,f]=E.useState(null),h=ft(t,x=>f(x),l.onItemTextChange,x=>{var y;return(y=a.itemTextRefCallback)==null?void 0:y.call(a,x,l.value,l.disabled)}),p=d==null?void 0:d.textContent,m=E.useMemo(()=>c.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:g,onNativeOptionRemove:b}=u;return Lr(()=>(g(m),()=>b(m)),[g,b,m]),c.jsxs(c.Fragment,{children:[c.jsx(Be.span,{id:l.textId,...o,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?gc.createPortal(o.children,i.valueNode):null]})});oW.displayName=Fm;var iW="SelectItemIndicator",aW=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return rW(iW,n).isSelected?c.jsx(Be.span,{"aria-hidden":!0,...r,ref:t}):null});aW.displayName=iW;var Zk="SelectScrollUpButton",lW=E.forwardRef((e,t)=>{const n=Gc(Zk,e.__scopeSelect),r=qM(Zk,e.__scopeSelect),[s,o]=E.useState(!1),i=ft(t,r.onScrollButtonChange);return Lr(()=>{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(uW,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});lW.displayName=Zk;var Xk="SelectScrollDownButton",cW=E.forwardRef((e,t)=>{const n=Gc(Xk,e.__scopeSelect),r=qM(Xk,e.__scopeSelect),[s,o]=E.useState(!1),i=ft(t,r.onScrollButtonChange);return Lr(()=>{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(uW,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});cW.displayName=Xk;var uW=E.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Gc("SelectScrollButton",n),i=E.useRef(null),a=H1(n),l=E.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return E.useEffect(()=>()=>l(),[l]),Lr(()=>{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(Be.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:ke(s.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:ke(s.onPointerMove,()=>{var u;(u=o.onItemLeave)==null||u.call(o),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:ke(s.onPointerLeave,()=>{l()})})}),iNe="SelectSeparator",dW=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c.jsx(Be.div,{"aria-hidden":!0,...r,ref:t})});dW.displayName=iNe;var Qk="SelectArrow",aNe=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=U1(n),o=Yc(Qk,n),i=Gc(Qk,n);return o.open&&i.position==="popper"?c.jsx(Lb,{...s,...r,ref:t}):null});aNe.displayName=Qk;function fW(e){return e===""||e===void 0}var hW=E.forwardRef((e,t)=>{const{value:n,...r}=e,s=E.useRef(null),o=ft(t,s),i=j1(n);return E.useEffect(()=>{const a=s.current,l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==n&&d){const f=new Event("change",{bubbles:!0});d.call(a,n),a.dispatchEvent(f)}},[i,n]),c.jsx(RD,{asChild:!0,children:c.jsx("select",{...r,ref:o,defaultValue:n})})});hW.displayName="BubbleSelect";function pW(e){const t=yr(e),n=E.useRef(""),r=E.useRef(0),s=E.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=E.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return E.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function mW(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=lNe(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 lNe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var cNe=BU,gW=HU,uNe=WU,dNe=qU,fNe=YU,bW=GU,hNe=QU,pNe=eW,xW=nW,yW=sW,mNe=oW,gNe=aW,vW=lW,wW=cW,SW=dW;const rt=cNe,CW=pNe,lt=uNe,Je=E.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(gW,{ref:r,className:J("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(dNe,{asChild:!0,children:c.jsx(Ys,{className:"h-4 w-4 opacity-50"})})]}));Je.displayName=gW.displayName;const NW=E.forwardRef(({className:e,...t},n)=>c.jsx(vW,{ref:n,className:J("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Km,{className:"h-4 w-4"})}));NW.displayName=vW.displayName;const jW=E.forwardRef(({className:e,...t},n)=>c.jsx(wW,{ref:n,className:J("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Ys,{className:"h-4 w-4"})}));jW.displayName=wW.displayName;const et=E.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>c.jsx(fNe,{children:c.jsx(va,{children:c.jsxs(bW,{ref:s,className:J("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(NW,{}),c.jsx(hNe,{className:J("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),c.jsx(jW,{})]})})}));et.displayName=bW.displayName;const YM=E.forwardRef(({className:e,...t},n)=>c.jsx(xW,{ref:n,className:J("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));YM.displayName=xW.displayName;const pe=E.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(yW,{ref:r,className:J("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(gNe,{children:c.jsx(Rr,{className:"h-4 w-4"})})}),c.jsx(mNe,{children:t})]}));pe.displayName=yW.displayName;const bNe=E.forwardRef(({className:e,...t},n)=>c.jsx(SW,{ref:n,className:J("-mx-1 my-1 h-px bg-muted",e),...t}));bNe.displayName=SW.displayName;function a5({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var Oe;const{searchQuery:a,debouncedSearchQuery:l,setSearchQuery:u}=$M(),d=_p(),f=Qd(),h=Dp(),p=Mp(),m=Tp(),g=Rp(),b=Wc(),x=L1(),y=FM(),v=Qb(),w=qc(),{data:S,isLoading:C}=K9({enabled:(n==null?void 0:n.type)==="organization"}),{groups:j,isLoading:D}=LU("tenant",(n==null?void 0:n.tenantId)||v),[k,_]=N.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");N.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(w.setCurrentContext("tenant-dialog"),w.setCurrentMode("specificTenantUsers")):(w.setCurrentContext("tenant-tab"),w.setCurrentMode("allTenants"))},[w,n==null?void 0:n.type]);const M=ue=>{var Ie,ht,xe,se;_(ue);let De;if(ue==="specific_tenant_users"?De="specific_users":ue==="all_tenant_users"||ue==="all_tenants"?De="all_users":ue==="groups"?De="groups":De="specific_users",r==null||r(De),ue==="groups"?(w.setCurrentContext("group-share"),w.setCurrentMode("specificGroups")):(n==null?void 0:n.type)==="tenant"?(w.setCurrentContext("tenant-dialog"),ue==="specific_tenant_users"?w.setCurrentMode("specificTenantUsers"):ue==="all_tenant_users"&&(w.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&w.setSelectedTenant(n.tenantId))):(w.setCurrentContext("tenant-tab"),ue==="specific_tenant_users"?w.setCurrentMode("specificTenantUsers"):ue==="all_tenant_users"?w.setCurrentMode("allTenantUsers"):ue==="all_tenants"&&w.setCurrentMode("allTenants")),ue==="all_tenant_users"){const de=(ht=(Ie=T==null?void 0:T.shares)==null?void 0:Ie.tenantWide)==null?void 0:ht[0];de&&de.role!==void 0&&w.setTenantWideRole(de.role)}else if(ue==="all_tenants"){const de=(se=(xe=T==null?void 0:T.shares)==null?void 0:xe.allTenantsOnly)==null?void 0:se[0];de&&de.role!==void 0&&w.setAllTenantsRole(de.role)}},R=ue=>{w.setSelectedTenant(ue)},{allUsers:O,existingShares:T,isLoadingUsers:I,isErrorLoadingUsers:F,isLoadingShares:z,isErrorLoadingShares:B}=Bh({debouncedSearchQuery:l,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),$=ue=>{var xe,se;const De=d.some(de=>de.id===ue),Ie=f.includes(ue),ht=(se=(xe=T==null?void 0:T.shares)==null?void 0:xe.specificTenantUsers)==null?void 0:se.some(de=>de.tenantUserId===ue);De?w.removeSelectedUser(ue):Ie?w.removeUserFromRemove(ue):ht||w.addSelectedUser({id:ue,role:"VIEWER"})},P=(ue,De)=>{w.updateSelectedUserRole(ue,De)},V=ue=>{w.addUserToRemove(ue),w.removeSelectedUser(ue)},L=ue=>{w.removeUserFromRemove(ue)},A=ue=>{w.removeUserFromUpdate(ue)},W=(ue,De,Ie)=>{w.addUserToUpdate({id:ue,currentRole:De,newRole:Ie})},U=(ue,De)=>{k==="all_tenant_users"?w.setTenantWideRole(De):k==="all_tenants"&&w.setAllTenantsRole(De)},Y=()=>{k==="all_tenant_users"?w.setTenantWideRole("VIEWER"):k==="all_tenants"&&w.setAllTenantsRole("VIEWER")},H=(()=>{var ue,De,Ie,ht;return b==="allTenants"?(De=(ue=T==null?void 0:T.shares)==null?void 0:ue.allTenantsOnly)==null?void 0:De[0]:b==="allTenantUsers"?(ht=(Ie=T==null?void 0:T.shares)==null?void 0:Ie.tenantWide)==null?void 0:ht[0]:null})();N.useEffect(()=>{var ue,De,Ie,ht;if(k==="all_tenant_users"){const xe=(De=(ue=T==null?void 0:T.shares)==null?void 0:ue.tenantWide)==null?void 0:De[0];xe&&xe.role!==void 0&&w.setTenantWideRole(xe.role)}else if(k==="all_tenants"){const xe=(ht=(Ie=T==null?void 0:T.shares)==null?void 0:Ie.allTenantsOnly)==null?void 0:ht[0];xe&&xe.role!==void 0&&w.setAllTenantsRole(xe.role)}},[k,T,w]);const q=O.filter(ue=>d.some(De=>De.id===ue.id)),X=ue=>{const De=p.some(xe=>xe.id===ue),Ie=m.includes(ue),ht=ie==null?void 0:ie.some(xe=>xe.groupId===ue);De?w.removeSelectedGroup(ue):Ie?w.removeGroupFromRemove(ue):ht||w.addSelectedGroup({id:ue,role:"VIEWER"})},Z=(ue,De)=>{w.updateSelectedGroupRole(ue,De)},G=ue=>{w.addGroupToRemove(ue),w.removeSelectedGroup(ue)},Q=(ue,De,Ie)=>{w.addGroupToUpdate({id:ue,currentRole:De,newRole:Ie})},ne=j.filter(ue=>p.some(De=>De.id===ue.id)),ae=N.useMemo(()=>k!=="groups"?[]:j.filter(ue=>ue.type!=="TENANT_GROUP"?!1:ue.name.toLowerCase().includes(a.toLowerCase())||ue.description&&ue.description.toLowerCase().includes(a.toLowerCase())),[j,k,a]),ie=N.useMemo(()=>{var De,Ie;const ue=((De=T==null?void 0:T.shares)==null?void 0:De.specificGroups)||((Ie=T==null?void 0:T.shares)==null?void 0:Ie.groups)||[];return!ue||ue.length===0?[]:ue.filter(ht=>{const xe=j.find(se=>se.id===ht.groupId);return(xe==null?void 0:xe.type)==="TENANT_GROUP"})},[T,j]),he=I||z||k==="groups"&&D,be=F||B,Ce=()=>(n==null?void 0:n.type)==="tenant"||k==="all_tenants"||k==="groups"?!0:v&&(k==="specific_tenant_users"||k==="all_tenant_users");return c.jsxs(c.Fragment,{children:[be&&c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsxs("div",{className:"text-center",children:[c.jsx(gd,{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(oe,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!be&&n&&c.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[c.jsx(BM,{shareType:k,onShareTypeChange:M,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(is,{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(xc,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:c.jsx(is,{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(XA,{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(Q_,{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(xc,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(k==="specific_tenant_users"||k==="all_tenant_users")&&c.jsxs("div",{className:"mt-4",children:[c.jsx(ce,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),c.jsxs(rt,{value:v||"",onValueChange:R,disabled:C,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),c.jsx(et,{className:"z-[51]",children:(Oe=S==null?void 0:S.tenants)==null?void 0:Oe.map(ue=>c.jsx(pe,{value:ue.id,children:ue.name},ue.id))})]})]}),Ce()?c.jsx(c.Fragment,{children:k==="specific_tenant_users"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(yv,{value:a,onChange:u}),c.jsx(AB,{selectedUsers:d,selectedUserObjects:q,onRemove:ue=>$(ue),onRoleChange:P,getRoleOptions:ui}),c.jsx(PB,{usersToRemove:f,allUsers:O,onRemove:L}),c.jsx(OB,{usersToUpdate:h,allUsers:O,onRemove:A,getRoleOptions:ui}),c.jsx(mU,{existingShares:T,isInitialLoading:!!he,isSearching:!1,resource:e,onShare:()=>{},getRoleOptions:ui,allUsers:O,currentUser:n,handleUserToggle:$,handleUserRoleChange:P,handleRemoveAccess:V,handleUpdateAccess:W})]}):k==="groups"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(yv,{value:a,onChange:u,placeholder:"Search groups..."}),c.jsx($U,{selectedGroups:p,groupObjects:ne,onRemove:X,onRoleChange:Z,getRoleOptions:ui}),m.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),c.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),g.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",g.length,")"]}),c.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),c.jsx(FU,{groups:ae,existingGroupShares:ie,isLoading:D,resource:e,getRoleOptions:ui,currentUser:n,handleGroupToggle:X,handleGroupRoleChange:Z,handleRemoveAccess:G,handleUpdateAccess:Q})]}):k==="all_tenant_users"||k==="all_tenants"?c.jsx("div",{className:"mt-6",children:c.jsx(OU,{currentUser:n,currentShare:H,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:U,onRemoveAccess:Y,allUsersToUpdate:b==="allTenantUsers"&&((H==null?void 0:H.role)===void 0||x!==H.role)||b==="allTenants"&&((H==null?void 0:H.role)===void 0||y!==H.role)?{currentRole:(H==null?void 0:H.role)||"VIEWER",newRole:b==="allTenantUsers"?x:y}:null,allUsersToRemove:b==="allTenantUsers"&&(H==null?void 0:H.role)===void 0||b==="allTenants"&&(H==null?void 0:H.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(k==="specific_tenant_users"||k==="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(XA,{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 xNe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var F,z;const{searchQuery:a,setSearchQuery:l}=$M(),u=Mp(),d=Tp(),f=Rp(),h=qc(),[p,m]=N.useState("org_groups"),[g,b]=N.useState(""),{data:x,isLoading:y}=K9({enabled:(n==null?void 0:n.type)==="organization"&&p==="tenant_groups"}),v=Array.isArray(x)?x:(x==null?void 0:x.tenants)||[],w=()=>{if((n==null?void 0:n.type)==="organization")return"organization";if((n==null?void 0:n.type)==="tenant")return"tenant"},{groups:S,isLoading:C}=LU(w(),p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"?g:n==null?void 0:n.tenantId),{existingShares:j}=Bh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t}),D=S.filter(B=>p==="org_groups"&&B.type!=="ORG_GROUP"||p==="tenant_groups"&&B.type!=="TENANT_GROUP"||p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&(!g||B.tenantId&&B.tenantId!==g)?!1:B.name.toLowerCase().includes(a.toLowerCase())||B.description&&B.description.toLowerCase().includes(a.toLowerCase())),k=((F=j==null?void 0:j.shares)==null?void 0:F.specificGroups)||((z=j==null?void 0:j.shares)==null?void 0:z.groups)||[];N.useEffect(()=>{h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},[h]);const _=B=>{const $=B;m($),$==="org_groups"&&b(""),r==null||r($==="org_groups"?"specific_groups":"all_groups"),h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},M=S.filter(B=>u.some($=>$.id===B.id)),R=B=>{const $=u.some(L=>L.id===B),P=d.includes(B),V=k==null?void 0:k.some(L=>L.groupId===B);$?h.removeSelectedGroup(B):P?h.removeGroupFromRemove(B):V||h.addSelectedGroup({id:B,role:"VIEWER"})},O=(B,$)=>{h.updateSelectedGroupRole(B,$)},T=B=>{h.addGroupToRemove(B),h.removeSelectedGroup(B)},I=(B,$,P)=>{h.addGroupToUpdate({id:B,currentRole:$,newRole:P})};return n?c.jsxs(c.Fragment,{children:[c.jsx(BM,{shareType:p,onShareTypeChange:_,currentUser:n,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:c.jsx(md,{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(is,{className:"mb-3 h-6 w-6 text-green-500"})}]}),p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsx(ce,{children:"Select Tenant"}),c.jsxs(rt,{value:g,onValueChange:b,disabled:y,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:y?"Loading tenants...":"Select a tenant to view its groups"})}),c.jsx(et,{className:"z-[51]",children:v.map(B=>c.jsx(pe,{className:"hover:bg-muted",value:B.id,children:B.name},B.id))})]})]}),c.jsx("div",{className:"mt-3 space-y-2",children:p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&!g?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(yv,{value:a,onChange:l,placeholder:"Search groups..."}),c.jsx($U,{selectedGroups:u,groupObjects:M,onRemove:R,onRoleChange:O,getRoleOptions:ui}),d.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",d.length,")"]}),c.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),f.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",f.length,")"]}),c.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),c.jsx(FU,{groups:D,existingGroupShares:k,isLoading:C,resource:e,getRoleOptions:ui,currentUser:n,handleGroupToggle:R,handleGroupRoleChange:O,handleRemoveAccess:T,handleUpdateAccess:I})]})})]}):null}const kW=()=>{const e=fU(),t=Wc(),n=_p(),r=Qd(),s=Dp(),o=Mp(),i=Tp(),a=Rp(),l=Qb(),u=OM(),d=FM(),f=L1(),h=hU(),p=N.useMemo(()=>()=>_pe({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]),m=N.useMemo(()=>b=>VB(b),[]),g=N.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:p,validateShareData:m,isCurrentStateValid:g,currentContext:e,currentMode:t,selectedUsers:n,usersToRemove:r,usersToUpdate:s,selectedTenant:l,orgWideRole:u,allTenantsRole:d,tenantWideRole:f}};function l5({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllUsersShare:l,onRemoveAccess:u}){const d=_p(),f=Qd(),h=Dp(),p=Qb(),m=OM(),g=FM(),b=L1(),{buildShareData:x,validateShareData:y,isCurrentStateValid:v}=kW(),w=n||r||s,S=()=>{var _,M,R,O;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 T=d.length+f.length+h.length;return T===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${T} user${T!==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 ${T} user${T!==1?"s":""}`}else if(a==="all_users"){if(!l||l.role===void 0)return"Share with All Users";const T=l.role;return m===T?"Remove Access":"Update Access"}else if(a==="all_tenants"){const T=(M=(_=t==null?void 0:t.shares)==null?void 0:_.allTenantsOnly)==null?void 0:M[0];if(!T||T.role===void 0)return"Share with All Tenants";const I=T.role;return g===I?"Remove Access":"Update Access"}else if(a==="all_tenant_users"){const T=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!T||T.role===void 0)return"Share with All Tenant Users";const I=T.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 T=d.length+f.length+h.length;return T===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${T} user${T!==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 ${T} user${T!==1?"s":""}`}return"Share"},C=()=>w||!e||a==="all_tenant_users"&&!p||a==="specific_tenant_users"&&!p?!0:!v,j=()=>{const _=x();_&&y(_)&&o(_)},D=()=>{var _,M,R,O;if(a==="all_users")if(!l||l.role===void 0){const T=x();T&&y(T)&&o(T)}else{const T=l.role;if(m===T)u==null||u();else{const F=x();if(F&&y(F)){const z={...F,updateAccess:!0};o(z)}}}else if(a==="all_tenants"){const T=(M=(_=t==null?void 0:t.shares)==null?void 0:_.allTenantsOnly)==null?void 0:M[0];if(!T||T.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=T.role;if(g===I)u==null||u();else{const z=x();if(z&&y(z)){const B={...z,updateAccess:!0};o(B)}}}}else if(a==="all_tenant_users"){const T=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!T||T.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=T.role;if(b===I)u==null||u();else{const z=x();if(z&&y(z)){const B={...z,updateAccess:!0};o(B)}}}}},k=()=>{var _,M,R,O;if(a==="all_users"){if(!l||l.role===void 0)return"default";const T=l.role;return m===T?"destructive":"default"}else if(a==="all_tenants"){const T=(M=(_=t==null?void 0:t.shares)==null?void 0:_.allTenantsOnly)==null?void 0:M[0];if(!T||T.role===void 0)return"default";const I=T.role;return g===I?"destructive":"default"}else if(a==="all_tenant_users"){const T=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!T||T.role===void 0)return"default";const I=T.role;return b===I?"destructive":"default"}return"default"};return c.jsxs(Ts,{children:[c.jsxs(oe,{variant:"outline",onClick:i,disabled:w,children:[c.jsx(vt,{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(oe,{onClick:j,disabled:!e||w,variant:"default",children:[w?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Qu,{className:"mr-2 h-4 w-4"}),!w&&S()]})}),(a==="all_users"||a==="all_tenants"||a==="all_tenant_users")&&c.jsxs(oe,{onClick:D,disabled:C(),variant:k(),children:[w?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(is,{className:"mr-2 h-4 w-4"}),!w&&S()]})]})}function yNe({resource:e,isSharing:t,isRemoving:n,isUpdating:r,onShare:s,onClose:o,shareTabType:i,currentAllUsersShare:a}){const l=_p(),u=Qd(),d=Dp(),f=Mp(),h=Tp(),p=Rp();Wc(),fU();const m=L1();Qb();const{buildShareData:g,validateShareData:b,isCurrentStateValid:x}=kW(),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 k=l.length+u.length+d.length;return k===0?"Select users to share with":l.length>0&&u.length>0?`Update access for ${k} user${k!==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 ${k} user${k!==1?"s":""}`}else if(i==="groups"){if(f.length===0&&h.length===0&&p.length===0)return"Select groups to share with";const k=f.length+h.length+p.length;return k===0?"Select groups to share with":f.length>0&&h.length>0?`Update access for ${k} group${k!==1?"s":""}`:h.length>0&&f.length===0&&p.length===0?`Remove access for ${h.length} group${h.length!==1?"s":""}`:f.length>0&&h.length===0&&p.length===0?`Share with ${f.length} group${f.length!==1?"s":""}`:p.length>0&&f.length===0&&h.length===0?`Update access for ${p.length} group${p.length!==1?"s":""}`:`Update access for ${k} group${k!==1?"s":""}`}else if(i==="all_users"){if(!a||a.role==="NONE")return"Share with All Users";const k=a.role;return m===k?"Remove Access":"Update Access"}return"Share"},w=()=>y||!e?!0:!x,S=()=>{const k=g();k&&b(k)&&s(k)},C=()=>{const k=g();k&&b(k)&&s(k)},j=()=>{if(!a||a.role==="NONE"){const k=g();k&&b(k)&&s(k)}else{const k=a.role;if(m===k){const M=g();if(M&&b(M)){const R={...M,removeAccess:!0};s(R)}}else{const M=g();if(M&&b(M)){const R={...M,updateAccess:!0};s(R)}}}},D=()=>!a||a.role==="NONE"?"default":"destructive";return c.jsxs(Ts,{children:[c.jsxs(oe,{variant:"outline",onClick:o,disabled:y,children:[c.jsx(vt,{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(oe,{onClick:S,disabled:!e||y,variant:"default",children:[y?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Qu,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="groups"&&c.jsx(c.Fragment,{children:(f.length>0||h.length>0||p.length>0)&&c.jsxs(oe,{onClick:C,disabled:!e||y,variant:"default",children:[y?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Qu,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="all_users"&&c.jsxs(oe,{onClick:j,disabled:w(),variant:D(),children:[y?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Qu,{className:"mr-2 h-4 w-4"}),!y&&v()]})]})}function vNe({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllGroupsShare:l,onRemoveAccess:u}){const d=Mp(),f=Tp(),h=Rp();hU(),Wc();const p=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:d,groupsToRemove:f,groupsToUpdate:h})},m=()=>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(oe,{variant:"outline",onClick:i,disabled:b,children:"Cancel"}),c.jsxs(oe,{onClick:p,disabled:!m()||b,children:[b&&c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),g()]})]})]})}function eo(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function Va(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function wNe(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(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));o(h,{onSuccess:()=>{l()}})}if(d&&d.length>0){const h=Va(r,s,d.map(p=>{var g,b;const m=(b=(g=a==null?void 0:a.shares)==null?void 0:g.specificOrgUsers)==null?void 0:b.find(x=>x.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(m==null?void 0:m.role)||"VIEWER"}}));i(h,{onSuccess:()=>{l()}})}f&&f.length>0&&f.forEach(h=>{const p=eo(r,s,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);o(p,{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 p=Va(r,s,d.map(m=>{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===m);return{scope:"specific_tenant_user",tenantUserId:m,tenantId:h,role:(g==null?void 0:g.role)||"VIEWER"}}));i(p,{onSuccess:()=>{l()}})}if(f&&f.length>0&&f.forEach(p=>{const m=eo(r,s,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.newRole}]);o(m,{onSuccess:()=>{l()}})}),u&&u.length>0){const p=eo(r,s,u.map(m=>({scope:"specific_tenant_user",tenantUserId:m.id,tenantId:h,role:m.role})));o(p,{onSuccess:()=>{l()}})}}break;case"tenant-dialog":if(e.mode==="allTenantUsers")if(e.removeAccess){const u=Va(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(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));o(h,{onSuccess:()=>{l()}})}if(d&&d.length>0){const h=Va(r,s,d.map(p=>{var g,b;const m=(b=(g=a==null?void 0:a.shares)==null?void 0:g.specificTenantUsers)==null?void 0:b.find(x=>x.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(m==null?void 0:m.role)||"VIEWER"}}));i(h,{onSuccess:()=>{l()}})}f&&f.length>0&&f.forEach(h=>{const p=eo(r,s,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);o(p,{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(p=>({scope:"group",groupId:p.id,role:p.role})));o(h,{onSuccess:()=>{var p;l(),(p=t.resetGroupSelections)==null||p.call(t),$e.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(d&&d.length>0){const h=Va(r,s,d.map(p=>({scope:"group",groupId:p,role:"VIEWER"})));i(h,{onSuccess:()=>{var p;l(),(p=t.resetGroupSelections)==null||p.call(t),$e.success(`Removed access from ${d.length} group${d.length!==1?"s":""}`)}})}f&&f.length>0&&f.forEach(h=>{const p=eo(r,s,[{scope:"group",groupId:h.id,role:h.newRole}]);o(p,{onSuccess:()=>{var m;l(),(m=t.resetGroupSelections)==null||m.call(t),$e.success("Updated access for group")}})})}break}}function SNe(e,t,n,r){var u,d,f,h,p,m;const{resourceType:s,resourceId:o,removeMutation:i,existingShares:a,resetUserSelections:l}=r;if(o)if(e.length>0){const g=Va(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=Va(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=Va(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=(m=(p=a==null?void 0:a.shares)==null?void 0:p.orgUsersOnly)==null?void 0:m[0];if(x){const y=Va(s,o,[{scope:"org_users_only",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove org-wide access failed:",v)}})}}}}function CNe(e,t,n){const r=qc(),s=Qd(),o=PM(),i=Wc(),{currentUser:a}=Ms(),{existingShares:l}=Bh({debouncedSearchQuery:"",resourceId:e||"",resourceType:At.DASHBOARD,userType:"tenant"}),u=N.useCallback(()=>{r.resetUserSelections()},[r]),d=N.useCallback(()=>{r.resetGroupSelections()},[r]),f=N.useCallback(p=>{if(!e)return;const m={resourceType:At.DASHBOARD,resourceId:e,shareMutation:t,removeMutation:n,existingShares:l,resetUserSelections:u,resetGroupSelections:d};wNe(p,m,a)},[e,t,n,l,u,d,a]),h=N.useCallback(()=>{if(!e)return;const p={resourceType:At.DASHBOARD,resourceId:e,removeMutation:n,existingShares:l,resetUserSelections:u};SNe(s,o||"",i||"",p)},[e,t,n,l,u,d,s,o,i]);return{handleShareSubmit:f,handleRemoveAccess:h}}function EW({resource:e,resourceType:t,onClose:n,onShareSuccess:r,onRemoveSuccess:s}){var O,T,I,F,z,B,$,P;const{currentUser:o}=Ms(),[i,a]=N.useState("specific_users"),[l,u]=N.useState("specific_users"),[d,f]=N.useState("specific_groups"),h=qc(),p=PM(),m=Wc(),g=X9(),b=Q9(),{handleShareSubmit:x,handleRemoveAccess:y}=CNe(e.id,(V,L)=>{g.mutate(V,{...L,onSuccess:()=>{var A;(A=L==null?void 0:L.onSuccess)==null||A.call(L),r==null||r()}})},(V,L)=>{b.mutate(V,{...L,onSuccess:()=>{var A;(A=L==null?void 0:L.onSuccess)==null||A.call(L),s==null||s()}})}),v=g.isPending,w=b.isPending,S=g.isPending,{existingShares:C}=Bh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant"}),{existingShares:j}=Bh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"organization"}),D=(T=(O=C==null?void 0:C.shares)==null?void 0:O.tenantWide)==null?void 0:T[0],k=(F=(I=j==null?void 0:j.shares)==null?void 0:I.orgUsersOnly)==null?void 0:F[0],_=()=>{if(p==="org")return l;switch(m){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},M=N.useCallback(()=>{h.resetShareState(),n()},[h,n]),R=(o==null?void 0:o.type)==="organization";return c.jsx(ls,{open:!0,onOpenChange:M,children:c.jsxs(Vr,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Qu,{className:"h-5 w-5"}),' Share "',e==null?void 0:e.title,'"']})}),c.jsx(Rs,{children:R?"Share this resource with org users or tenant users.":"Share this resource with other users in your tenant."})]}),R?c.jsxs(cs,{value:p,onValueChange:V=>{const L=V;h.setSelectedTab(L),h.resetUserSelections(),h.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[c.jsxs(Wr,{className:"mb-2 grid w-full grid-cols-3",children:[c.jsx(Ht,{value:"org",children:"Org Users"}),c.jsx(Ht,{value:"tenant",children:"Tenant Users"}),c.jsx(Ht,{value:"groups",children:"Groups"})]}),c.jsx(Gn,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(PCe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:u,isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx(Gn,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(a5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:V=>a(V),isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx(Gn,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(xNe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:f,isSharing:v,isUpdating:S,isRemoving:w})})})]}):c.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(a5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:V=>a(V),isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx("div",{className:"mt-auto flex-shrink-0",children:R?p==="org"?c.jsx(l5,{resource:e,existingShares:j,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:l,currentAllUsersShare:k,onRemoveAccess:y}):p==="tenant"?c.jsx(l5,{resource:e,existingShares:C,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:_(),currentAllUsersShare:D,onRemoveAccess:y}):c.jsx(vNe,{resource:e,existingShares:j,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:d,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(B=(z=j==null?void 0:j.shares)==null?void 0:z.allOrgGroups)==null?void 0:B[0]:(P=($=C==null?void 0:C.shares)==null?void 0:$.allTenantGroups)==null?void 0:P[0],onRemoveAccess:y}):c.jsx(yNe,{resource:e,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:i,currentAllUsersShare:D,onRemoveAccess:y})})]})})}const Nn=E.forwardRef(({className:e,type:t,...n},r)=>c.jsx("input",{type:t,className:J("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}));Nn.displayName="Input";function _W({open:e,resourceLabel:t,initialTitle:n,initialDescription:r="",onClose:s,onSave:o,isSaving:i=!1}){const[a,l]=N.useState(n),[u,d]=N.useState(r??"");N.useEffect(()=>{e&&(l(n),d(r??""))},[e,n,r]);const f=h=>{h.preventDefault();const p=a.trim();p&&o({title:p,description:u.trim()})};return c.jsx(ls,{open:e,onOpenChange:h=>h?null:s(),children:c.jsx(Vr,{className:"sm:max-w-md",children:c.jsxs("form",{onSubmit:f,className:"space-y-4",children:[c.jsxs(Hr,{children:[c.jsxs(Ur,{children:["Edit ",t]}),c.jsxs(Rs,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"resource-title",children:"Title"}),c.jsx(Nn,{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(ce,{htmlFor:"resource-description",children:"Description"}),c.jsx(Gd,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),c.jsxs(Ts,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[c.jsx(oe,{type:"button",variant:"outline",onClick:s,disabled:i,children:"Cancel"}),c.jsx(oe,{type:"submit",disabled:i||!a.trim(),children:i?"Saving...":"Save changes"})]})]})})})}function NNe({onDashboardSelect:e}){var K,H;const{authToken:t}=qe(),[n,r]=N.useState(!1),[s,o]=N.useState(!1),[i,a]=N.useState(null),[l,u]=N.useState(!1),[d,f]=N.useState(null),[h,p]=N.useState(null),[m,g]=N.useState(null),{data:b}=I7(),x=((K=b==null?void 0:b.preference)==null?void 0:K.defaultDashboardId)||null,y=Ss(q=>q.actions.selectDashboard),{userContext:v}=Ms(),w=((H=v==null?void 0:v.permissions)==null?void 0:H.canCreateDashboard)??!1,{onCreateSuccess:S}=n7({onDashboardSelect:e}),{resources:C,isLoading:j,isError:D,createResource:k,updateResource:_,deleteResource:M,duplicateResource:R,isCreating:O,isDeleting:T,refetch:I}=t7(()=>{u(!1),f(null)},q=>{r(!1),S(q,I)}),{startUpdating:F,stopUpdating:z,isUpdating:B}=e7(),$=q=>{const X=C.find(Z=>Z.id===q);X&&(y(X),e==null||e(q))},P=q=>{k({title:q.title,description:q.description,isPrivate:!1})},V=q=>{f(q),u(!0)},L=()=>{d&&M(d.id)},A=q=>{p(q),R(q,{onSettled:()=>p(null)})},W=(q,X,Z)=>{var ae;const G=Object.fromEntries(Object.entries(X).filter(([,ie])=>ie!==void 0));if(Object.keys(G).length===0){(ae=Z==null?void 0:Z.onSuccess)==null||ae.call(Z);return}const Q=Object.keys(G),ne=Q.length===1?Q[0]:void 0;F(q,ne),_({resourceId:q,data:G},{onSuccess:()=>{var ie;z(q,ne),(ie=Z==null?void 0:Z.onSuccess)==null||ie.call(Z)},onError:()=>{var ie;z(q,ne),(ie=Z==null?void 0:Z.onError)==null||ie.call(Z)}})},U=q=>{a(q),o(!0)},Y=q=>new Date(q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return t?j?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(On,{className:"h-8 w-8 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading dashboards..."})]})}):D?c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"text-center",children:[c.jsx(gd,{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(oe,{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"}),C.length>0&&w&&c.jsx("div",{className:"mt-6 flex gap-3",children:c.jsxs(oe,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Create New Dashboard"]})})]}),C.length>0&&c.jsxs("div",{className:"rounded-md bg-orange-500 px-3 py-1 text-sm font-medium text-white",children:[C.length," dashboard",C.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:C.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(T8,{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(oe,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(kr,{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:C.map(q=>c.jsx(_fe,{dashboard:q,isDefault:q.id===x,onView:$,isDeleting:T&&(d==null?void 0:d.id)===q.id,isDuplicating:h===q.id,onEditDetails:g,onDeleteClick:V,onDuplicateDashboard:A,onShareDashboard:U,formatDate:Y},q.id))})]})})}),c.jsx(R7,{open:n,onOpenChange:r,onSubmit:P,isCreating:O}),m&&c.jsx(_W,{open:!!m,resourceLabel:"Dashboard",initialTitle:m.title||"",initialDescription:m.description||"",onClose:()=>g(null),onSave:q=>{W(m.id,q,{onSuccess:()=>{g(null)}})},isSaving:B(m.id)}),c.jsx(Wb,{open:l,onOpenChange:u,children:c.jsxs(mp,{children:[c.jsxs(gp,{children:[c.jsx(xp,{children:"Delete Dashboard?"}),c.jsxs(yp,{children:['Are you sure you want to delete "',d==null?void 0:d.title,'"? This action cannot be undone.']})]}),c.jsxs(bp,{children:[c.jsx(wp,{disabled:T,children:"Cancel"}),c.jsx(vp,{onClick:L,disabled:T,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:T?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete"})]})]})}),i&&s&&c.jsx(EW,{resource:i,resourceType:At.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(gd,{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 sd=pl()(Sre(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})})),DW=e=>sd(t=>t.panels[e]),MW=()=>sd(e=>e.fullscreen),TW=e=>sd(t=>t.panels[e].container??null);function RW(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 jNe(e){const{selectedEntities:t}=e,n=t.map(r=>({...r,qualifiedEntityName:Lf(r)}));return{...e,selectedEntities:n}}const c5={selectedEntities:[]},Ai=pl()(Mb((e,t)=>({currentAIContext:c5,activeAssistantType:null,reasoningEffort:"low",showReasoning:!1,messageQueues:{dashboard:[],editor:[]},fileAttachments:{dashboard:[],editor:[]},uploadProgress:new Map,actions:{setCurrentAIContext:n=>{e(r=>{r.currentAIContext=jNe(n)})},setActiveAssistantType:n=>{e(r=>{r.activeAssistantType=n})},updateSelectedEntities:n=>{e(r=>{r.currentAIContext.selectedEntities=n})},clearAIContext:()=>{e(n=>{n.currentAIContext=c5})},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]}}))),Op=()=>Ai(e=>e.currentAIContext),GM=()=>Ai(e=>e.activeAssistantType),kNe=()=>Ai(e=>e.reasoningEffort),ENe=()=>Ai(e=>e.showReasoning),W1=()=>Ai(e=>e.actions),IW=e=>Ai(t=>t.messageQueues[e]),Fp=()=>Ai(e=>({queueMessage:e.actions.queueMessage,dequeueMessage:e.actions.dequeueMessage,removeFromQueue:e.actions.removeFromQueue,clearQueue:e.actions.clearQueue})),KM=e=>Ai(t=>t.fileAttachments[e]),ZM=()=>Ai(e=>({addFileAttachment:e.actions.addFileAttachment,removeFileAttachment:e.actions.removeFileAttachment,clearFileAttachments:e.actions.clearFileAttachments,updateUploadProgress:e.actions.updateUploadProgress,getFileAttachments:e.actions.getFileAttachments}));function AW(){const{tokenProps:e,id:t}=qe(),n=Ss(s=>s.selectedDashboard);return Ss(s=>s.showHub)?!1:!!(n!=null&&n.id||t||e!=null&&e.dashboard_id)}function XM({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:p,onFilterValuesChange:m,selectedSheetId:g,eventHandlers:b,type:x="dashboard",cardId:y,dashboardId:v,...w}){const{placeholders:S,tokenProps:C,id:j}=qe();Ss(O=>O.selectedDashboard);const D=ee(O=>O.themeStyle),k=ee(O=>O.isSessionExpired),{isLoading:_,isError:M}=oae({customStyle:t,currentTheme:u,onSave:n,onEvent:r,defaultFilterValues:p,onFilterValuesChange:m,selectedSheetId:g}),R=AW();return l&&!R&&!_?c.jsx(NNe,{}):_||!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(Ho,{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"})):k?(r==null||r({type:"error",message:"Session Expired"}),S!=null&&S.SessionExpired?c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsx("div",{children:S.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(wi,{children:"Session Expired"}),c.jsx("p",{className:"text-muted-foreground",children:"Please refresh your page to continue"})]})})):c.jsx("div",{className:J("isolate flex grow flex-col",{"h-full":x==="visual"},D==null?void 0:D.dashboardPanel,e),style:{},"data-role":"semaphor-container",...w})}var PW={exports:{}},ex={},Jk={exports:{}};(function(e,t){(function(n,r){r(t)})(Ua,function(n){function r(H){return function(X,Z,G,Q,ne,ae,ie){return H(X,Z,ie)}}function s(H){return function(X,Z,G,Q){if(!X||!Z||typeof X!="object"||typeof Z!="object")return H(X,Z,G,Q);var ne=Q.get(X),ae=Q.get(Z);if(ne&&ae)return ne===Z&&ae===X;Q.set(X,Z),Q.set(Z,X);var ie=H(X,Z,G,Q);return Q.delete(X),Q.delete(Z),ie}}function o(H,q){var X={};for(var Z in H)X[Z]=H[Z];for(var Z in q)X[Z]=q[Z];return X}function i(H){return H.constructor===Object||H.constructor==null}function a(H){return typeof H.then=="function"}function l(H,q){return H===q||H!==H&&q!==q}var u="[object Arguments]",d="[object Boolean]",f="[object Date]",h="[object RegExp]",p="[object Map]",m="[object Number]",g="[object Object]",b="[object Set]",x="[object String]",y=Object.prototype.toString;function v(H){var q=H.areArraysEqual,X=H.areDatesEqual,Z=H.areMapsEqual,G=H.areObjectsEqual,Q=H.areRegExpsEqual,ne=H.areSetsEqual,ae=H.createIsNestedEqual,ie=ae(he);function he(be,Ce,Oe){if(be===Ce)return!0;if(!be||!Ce||typeof be!="object"||typeof Ce!="object")return be!==be&&Ce!==Ce;if(i(be)&&i(Ce))return G(be,Ce,ie,Oe);var ue=Array.isArray(be),De=Array.isArray(Ce);if(ue||De)return ue===De&&q(be,Ce,ie,Oe);var Ie=y.call(be);return Ie!==y.call(Ce)?!1:Ie===f?X(be,Ce,ie,Oe):Ie===h?Q(be,Ce,ie,Oe):Ie===p?Z(be,Ce,ie,Oe):Ie===b?ne(be,Ce,ie,Oe):Ie===g||Ie===u?a(be)||a(Ce)?!1:G(be,Ce,ie,Oe):Ie===d||Ie===m||Ie===x?l(be.valueOf(),Ce.valueOf()):!1}return he}function w(H,q,X,Z){var G=H.length;if(q.length!==G)return!1;for(;G-- >0;)if(!X(H[G],q[G],G,G,H,q,Z))return!1;return!0}var S=s(w);function C(H,q){return l(H.valueOf(),q.valueOf())}function j(H,q,X,Z){var G=H.size===q.size;if(!G)return!1;if(!H.size)return!0;var Q={},ne=0;return H.forEach(function(ae,ie){if(G){var he=!1,be=0;q.forEach(function(Ce,Oe){!he&&!Q[be]&&(he=X(ie,Oe,ne,be,H,q,Z)&&X(ae,Ce,ie,Oe,H,q,Z))&&(Q[be]=!0),be++}),ne++,G=he}}),G}var D=s(j),k="_owner",_=Object.prototype.hasOwnProperty;function M(H,q,X,Z){var G=Object.keys(H),Q=G.length;if(Object.keys(q).length!==Q)return!1;for(var ne;Q-- >0;){if(ne=G[Q],ne===k){var ae=!!H.$$typeof,ie=!!q.$$typeof;if((ae||ie)&&ae!==ie)return!1}if(!_.call(q,ne)||!X(H[ne],q[ne],ne,ne,H,q,Z))return!1}return!0}var R=s(M);function O(H,q){return H.source===q.source&&H.flags===q.flags}function T(H,q,X,Z){var G=H.size===q.size;if(!G)return!1;if(!H.size)return!0;var Q={};return H.forEach(function(ne,ae){if(G){var ie=!1,he=0;q.forEach(function(be,Ce){!ie&&!Q[he]&&(ie=X(ne,be,ae,Ce,H,q,Z))&&(Q[he]=!0),he++}),G=ie}}),G}var I=s(T),F=Object.freeze({areArraysEqual:w,areDatesEqual:C,areMapsEqual:j,areObjectsEqual:M,areRegExpsEqual:O,areSetsEqual:T,createIsNestedEqual:r}),z=Object.freeze({areArraysEqual:S,areDatesEqual:C,areMapsEqual:D,areObjectsEqual:R,areRegExpsEqual:O,areSetsEqual:I,createIsNestedEqual:r}),B=v(F);function $(H,q){return B(H,q,void 0)}var P=v(o(F,{createIsNestedEqual:function(){return l}}));function V(H,q){return P(H,q,void 0)}var L=v(z);function A(H,q){return L(H,q,new WeakMap)}var W=v(o(z,{createIsNestedEqual:function(){return l}}));function U(H,q){return W(H,q,new WeakMap)}function Y(H){return v(o(F,H(F)))}function K(H){var q=v(o(z,H(z)));return function(X,Z,G){return G===void 0&&(G=new WeakMap),q(X,Z,G)}}n.circularDeepEqual=A,n.circularShallowEqual=U,n.createCustomCircularEqual=K,n.createCustomEqual=Y,n.deepEqual=$,n.sameValueZeroEqual=l,n.shallowEqual=V,Object.defineProperty(n,"__esModule",{value:!0})})})(Jk,Jk.exports);var QM=Jk.exports;const JM=v_(ane);var Pt={},_Ne=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(Pt,"__esModule",{value:!0});Pt.bottom=eT;Pt.childrenEqual=RNe;Pt.cloneLayout=OW;Pt.cloneLayoutItem=od;Pt.collides=q1;Pt.compact=$W;Pt.compactItem=LW;Pt.compactType=WNe;Pt.correctBounds=zW;Pt.fastPositionEqual=INe;Pt.fastRGLPropsEqual=void 0;Pt.getAllCollisions=BW;Pt.getFirstCollision=Pu;Pt.getLayoutItem=tT;Pt.getStatics=nT;Pt.modifyLayout=FW;Pt.moveElement=Lm;Pt.moveElementAwayFromCollision=tE;Pt.noop=void 0;Pt.perc=PNe;Pt.resizeItemInDirection=BNe;Pt.setTopLeft=HNe;Pt.setTransform=VNe;Pt.sortLayoutItems=lT;Pt.sortLayoutItemsByColRow=qW;Pt.sortLayoutItemsByRowCol=WW;Pt.synchronizeLayoutWithChildren=UNe;Pt.validateLayout=YW;Pt.withLayoutItem=TNe;var u5=QM,$m=DNe(N);function DNe(e){return e&&e.__esModule?e:{default:e}}const MNe=process.env.NODE_ENV==="production";function eT(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 OW(e){const t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=od(e[n]);return t}function FW(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 TNe(e,t,n){let r=tT(e,t);return r?(r=n(od(r)),e=FW(e,r),[e,r]):[e,null]}function od(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 RNe(e,t){return(0,u5.deepEqual)($m.default.Children.map(e,n=>n==null?void 0:n.key),$m.default.Children.map(t,n=>n==null?void 0:n.key))&&(0,u5.deepEqual)($m.default.Children.map(e,n=>n==null?void 0:n.props["data-grid"]),$m.default.Children.map(t,n=>n==null?void 0:n.props["data-grid"]))}Pt.fastRGLPropsEqual=_Ne;function INe(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function q1(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 $W(e,t,n,r){const s=nT(e),o=lT(e,t),i=Array(e.length);for(let a=0,l=o.length;a<l;a++){let u=od(o[a]);u.static||(u=LW(s,u,t,n,o,r),s.push(u)),i[e.indexOf(o[a])]=u,u.moved=!1}return i}const ANe={x:"w",y:"h"};function eE(e,t,n,r){const s=ANe[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;q1(t,a)&&eE(e,a,n+t[s],r)}}t[r]=n}function LW(e,t,n,r,s,o){const i=n==="vertical",a=n==="horizontal";if(i)for(t.y=Math.min(eT(e),t.y);t.y>0&&!Pu(e,t);)t.y--;else if(a)for(;t.x>0&&!Pu(e,t);)t.x--;let l;for(;(l=Pu(e,t))&&!(n===null&&o);)if(a?eE(s,t,l.x+l.w,"x"):eE(s,t,l.y+l.h,"y"),a&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!Pu(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function zW(e,t){const n=nT(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(;Pu(n,o);)o.y++}return e}function tT(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function Pu(e,t){for(let n=0,r=e.length;n<r;n++)if(q1(e[n],t))return e[n]}function BW(e,t){return e.filter(n=>q1(n,t))}function nT(e){return e.filter(t=>t.static)}function Lm(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=lT(e,i);(i==="vertical"&&typeof r=="number"?d>=r:i==="horizontal"&&typeof n=="number"?u>=n:!1)&&(f=f.reverse());const p=BW(f,t),m=p.length>0;if(m&&l)return OW(e);if(m&&o)return`${t.i}`,t.x=u,t.y=d,t.moved=!1,e;for(let g=0,b=p.length;g<b;g++){const x=p[g];`${t.i}${t.x}${t.y}${x.i}${x.x}${x.y}`,!x.moved&&(x.static?e=tE(e,x,t,s,i):e=tE(e,t,x,s,i))}return e}function tE(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=Pu(e,f),p=h&&h.y+h.h>t.y,m=h&&t.x+t.w>h.x;if(h){if(p&&a)return Lm(e,n,void 0,t.y+1,r,l,s);if(p&&s==null)return t.y=n.y,n.y=n.y+n.h,e;if(m&&i)return Lm(e,t,n.x,void 0,r,l,s)}else return`${n.i}${f.x}${f.y}`,Lm(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:Lm(e,n,i?n.x+1:void 0,a?n.y+1:void 0,r,l,s)}function PNe(e){return e*100+"%"}const VW=(e,t,n,r)=>e+n>r?t:n,HW=(e,t,n)=>e<0?t:n,UW=e=>Math.max(0,e),rT=e=>Math.max(0,e),sT=(e,t,n)=>{let{left:r,height:s,width:o}=t;const i=e.top-(s-e.height);return{left:r,width:o,height:HW(i,e.height,s),top:rT(i)}},oT=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{top:r,height:o,width:VW(e.left,e.width,i,n),left:UW(s)}},iT=(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:VW(e.left,e.width,o,n),top:rT(r),left:UW(i)}},aT=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{width:i,left:s,height:HW(r,e.height,o),top:rT(r)}},ONe=function(){return sT(arguments.length<=0?void 0:arguments[0],oT(...arguments))},FNe=function(){return sT(arguments.length<=0?void 0:arguments[0],iT(...arguments))},$Ne=function(){return aT(arguments.length<=0?void 0:arguments[0],oT(...arguments))},LNe=function(){return aT(arguments.length<=0?void 0:arguments[0],iT(...arguments))},zNe={n:sT,ne:ONe,e:oT,se:$Ne,s:aT,sw:LNe,w:iT,nw:FNe};function BNe(e,t,n,r){const s=zNe[e];return s?s(t,{...t,...n},r):n}function VNe(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 HNe(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 lT(e,t){return t==="horizontal"?qW(e):t==="vertical"?WW(e):e}function WW(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 qW(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 UNe(e,t,n,r,s){e=e||[];const o=[];$m.default.Children.forEach(t,a=>{if((a==null?void 0:a.key)==null)return;const l=tT(e,String(a.key)),u=a.props["data-grid"];l&&u==null?o.push(od(l)):u?(MNe||YW([u],"ReactGridLayout.children"),o.push(od({...u,i:a.key}))):o.push(od({w:1,h:1,x:0,y:eT(o),i:String(a.key)}))});const i=zW(o,{cols:n});return s?i:$W(i,r,n)}function YW(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 WNe(e){const{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}const qNe=()=>{};Pt.noop=qNe;var wa={};Object.defineProperty(wa,"__esModule",{value:!0});wa.calcGridColWidth=Y1;wa.calcGridItemPosition=YNe;wa.calcGridItemWHPx=nE;wa.calcWH=KNe;wa.calcXY=GNe;wa.clamp=Ou;function Y1(e){const{margin:t,containerPadding:n,containerWidth:r,cols:s}=e;return(r-t[0]*(s-1)-n[0]*2)/s}function nE(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function YNe(e,t,n,r,s,o){const{margin:i,containerPadding:a,rowHeight:l}=e,u=Y1(e),d={};return o&&o.resizing?(d.width=Math.round(o.resizing.width),d.height=Math.round(o.resizing.height)):(d.width=nE(r,u,i[0]),d.height=nE(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 GNe(e,t,n,r,s){const{margin:o,containerPadding:i,cols:a,rowHeight:l,maxRows:u}=e,d=Y1(e);let f=Math.round((n-i[0])/(d+o[0])),h=Math.round((t-i[1])/(l+o[1]));return f=Ou(f,0,a-r),h=Ou(h,0,u-s),{x:f,y:h}}function KNe(e,t,n,r,s,o){const{margin:i,maxRows:a,cols:l,rowHeight:u}=e,d=Y1(e);let f=Math.round((t+i[0])/(d+i[0])),h=Math.round((n+i[1])/(u+i[1])),p=Ou(f,0,l-r),m=Ou(h,0,a-s);return["sw","w","nw"].indexOf(o)!==-1&&(p=Ou(f,0,l)),["nw","n","ne"].indexOf(o)!==-1&&(m=Ou(h,0,a)),{w:p,h:m}}function Ou(e,t,n){return Math.max(Math.min(e,n),t)}var G1={},rE={exports:{}},P0={exports:{}},nn={};/** @license React v16.13.1
|
|
763
|
+
${R}`:R},color:D=>{if(f)return f;const k=D==null?void 0:D.raw,_=e5({raw:k,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a});return Bo(_)},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)||((S=u==null?void 0:u.font)==null?void 0:S.weight)||"bold",family:((j=(C=o==null?void 0:o.chart)==null?void 0:C.font)==null?void 0:j.family)||"Inter"}},backgroundColor:D=>{const k=D==null?void 0:D.raw;return e5({raw:k,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a})}}}function Y1e({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 J1e(o==null?void 0:o.raw,e)},label:s=>{const o=s==null?void 0:s.raw,i=KH(o,e),a=Number((o==null?void 0:o.v)??0),l=ZH(a,n),u=t||"Value";return i?`${i} — ${u}: ${l}`:`${u}: ${l}`}}}}}}function G1e(e){return e.reduce((t,n)=>ar(t,n||{}),{})}function K1e(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 Z1e(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))??Kd();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,p)=>{var m,g;if((g=(m=n==null?void 0:n.colorConfig)==null?void 0:m.segments)!=null&&g[h]){d.set(h,n.colorConfig.segments[h]);return}d.set(h,s[p%s.length])}),d})}function X1e(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!=="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 KH(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 Q1e(e._data,t);if(e.path){const r=e.path.split("."),s=r[r.length-1];if(s)return s}return""}function Q1e(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 J1e(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 ZH(e,t){return Fr(e,t.format,t.formatOptions)}function e5({raw:e,dimensionKeys:t,colorLookups:n,themeStyle:r,preferences:s,colorMode:o}){var m,g,b,x,y,v,w;if(!e)return"#999999";const i=((b=(g=(m=r==null?void 0:r.chart)==null?void 0:m.dataset)==null?void 0:g.backgroundColor)==null?void 0:b.filter(Boolean))??Kd(),a=eSe(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=MM(f,0,d);if(h===0||o==="category")return u;const p=tSe(e);return nSe(u,p,h)}function eSe(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 tSe(e){if(!e)return 1;const t=Number(e.v??0),n=Number(e.gs??e.s??0);return n>0&&Number.isFinite(t)?MM(t/n,0,1):1}function nSe(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=t5(e,"#ffffff",o);return a=t5(a,"#000000",i),a}function t5(e,t,n){const r=MM(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=n5(e),o=n5(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 rSe(i,a,l)}function n5(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 rSe(e,t,n){const r=s=>s.toString(16).padStart(2,"0");return`#${r(bN(e))}${r(bN(t))}${r(bN(n))}`}function bN(e){return Math.min(255,Math.max(0,Math.round(e)))}function MM(e,t,n){return Math.max(t,Math.min(n,e))}const XH=["poor","satisfactory","good"],xN={poor:"Poor",satisfactory:"Average",good:"Good"},sSe=["#F5F6F8","#E3E6EC","#CED4DD"],oSe=["#1F2933","#27323D","#303B47"];function iSe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s}){var ne,ae,ie,he,be,Ce,Oe;if(!e||e.length===0)return{type:"bar",data:{labels:[],datasets:[]}};const{dimensionKeys:o,metricKeys:i,keys:a}=rr(e),l=o[0]??a[0];if(!l)return{type:"bar",data:{labels:[],datasets:[]}};const u=i[0]??a.find(ue=>ue!==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(ue=>ue!==u),h=(d==null?void 0:d.comparativeMetricKey)??(d!=null&&d.disableAutoComparative?void 0:i.find(ue=>ue!==u&&ue!==f)),p=ee.getState(),m=s??p.themeStyle,g=p.theme==="dark",b=aSe({data:e,dimensionKey:l,actualKey:u,targetKey:f,comparativeKey:h,bulletConfig:d}),x=b.map(ue=>ue.label),y=(d==null?void 0:d.showRanges)??wSe(d),v=uSe(b,y),w=(ne=r==null?void 0:r.chartOptions)==null?void 0:ne.indexAxis,C=(w?w==="y"?"horizontal":"vertical":void 0)??(d==null?void 0:d.orientation)??"horizontal",j=C==="vertical"?"x":"y",D=r?{...r,chartOptions:{...r.chartOptions||{},indexAxis:j}}:{chartOptions:{indexAxis:j}},k=xSe(r),_=vSe(d),M=ySe(g),R=Kd().filter(Boolean),O=(((ie=(ae=m==null?void 0:m.chart)==null?void 0:ae.dataset)==null?void 0:ie.backgroundColor)||[]).filter(Boolean),T=(((be=(he=m==null?void 0:m.chart)==null?void 0:he.dataset)==null?void 0:be.borderColor)||[]).filter(Boolean),I=O.length>0?O:R.length>0?R:["#3b82f6"],F=T.length>0?T:I.length>0?I:["#111827"],z=vN({metricKey:u,metricIndex:0,preferences:r,backgroundPalette:I,borderPalette:F}),$=vN({metricKey:f||`${u}__target`,metricIndex:1,preferences:r,backgroundPalette:I,borderPalette:F}).borderColor||z.borderColor||"#111827",P=vN({metricKey:h,metricIndex:2,preferences:r,backgroundPalette:I,borderPalette:F}),V=y?dSe(b,M,C,g,_):[],L=fSe(b,z,C,u),A=hSe(b,P,C,h),W=[...V,L];A&&W.push(A);let U=pSe({orientation:C,chartMax:v,formatConfig:k,series:b,preferences:D,rangeLabelMap:_,showRanges:y});const Y=(Oe=(Ce=r==null?void 0:r.chartOptions)==null?void 0:Ce.plugins)==null?void 0:Oe.legend;U=XD(U,Y);const{plugins:K=[],options:H}=Vc((r==null?void 0:r.customVisualCode)||""),q=jSe([U,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,H]),X=b.some(ue=>ue.target!=null)&&v>0?bSe({series:b,orientation:C,color:$}):null,Z={type:"bar",data:{labels:x,datasets:W},options:q,plugins:X?[...K,X]:K},G=Yb("bullet",r),Q=(r==null?void 0:r.dataLabelsConfig)??G;return Z.options=Cp(Z.options||{},Q,D,"bar"),Z.options=Sp.applyAxisConfig(Z.options||{},"bar",D),Z.options=Z.options||{},Z.options.indexAxis=j,Z}function aSe({data:e,dimensionKey:t,actualKey:n,targetKey:r,comparativeKey:s,bulletConfig:o}){const i=e.map(l=>{const u=cSe(l[t]),d=zy(l[n]),f=r&&l[r]!=null?zy(l[r]):(o==null?void 0:o.targetValue)??null,h=s&&l[s]!=null?zy(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=lSe({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 lSe({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:yN("poor",e,o,i,a*.5,s,a),satisfactory:yN("satisfactory",e,o,i,a*.8,s,a),good:yN("good",e,o,i,a,s,a)};let u=0;return XH.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 yN(e,t,n,r,s,o,i){const a=n==null?void 0:n[e];if(a&&t[a]!=null)return zy(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 zy(e){const t=Number(e);return Number.isFinite(t)?t:0}function cSe(e){return e==null||e===""?"(Blank)":String(e)}function uSe(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 dSe(e,t,n,r,s){const o=[];return XH.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:CSe(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 fSe(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 hSe(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 pSe({orientation:e,chartMax:t,formatConfig:n,series:r,preferences:s,rangeLabelMap:o,showRanges:i}){var f,h,p,m,g,b,x,y,v;const a={type:"linear",stacked:!1,beginAtZero:!0,suggestedMax:t,ticks:{callback:w=>Fr(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:((p=(h=(f=s==null?void 0:s.chartOptions)==null?void 0:f.plugins)==null?void 0:h.legend)==null?void 0:p.display)??!0,position:((b=(g=(m=s==null?void 0:s.chartOptions)==null?void 0:m.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 S=w.dataset.customRole;return S?S!=="range":!0},callbacks:mSe(r,n,o,i)}},indexAxis:e==="vertical"?"x":"y"}}function mSe(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"}: ${Fr(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=Fr(o.target,t.format,t.options),d=o.actual-o.target,f=Fr(d,t.format,t.options),h=o.targetKey||"Target";i.push(`${h}: ${u} (${f})`)}const a=gSe(o,n);r&&a&&i.push(`Range: ${a}`);const l=o.comparative;return l!=null&&i.push(`Comparative: ${Fr(l,t.format,t.options)}`),i}}}function gSe(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 bSe({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],p=((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]),m=p?t==="horizontal"?p.height??p.width??20:p.width??p.height??20:20,g=Math.max(Math.min(m/2,12),6);if(t==="horizontal"){const S=o.getPixelForValue(d.target),C=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(S,C-g),s.lineTo(S,C+g),s.stroke(),s.beginPath(),s.moveTo(S-4,C-g),s.lineTo(S+4,C-g),s.moveTo(S-4,C+g),s.lineTo(S+4,C+g),s.stroke()}else{const S=o.getPixelForValue(d.target),C=i.getPixelForValue(h)??0;s.beginPath(),s.moveTo(C-g,S),s.lineTo(C+g,S),s.stroke(),s.beginPath(),s.moveTo(C-g,S-4),s.lineTo(C-g,S+4),s.moveTo(C+g,S-4),s.lineTo(C+g,S+4),s.stroke()}}),s.restore()}}}function xSe(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 ySe(e){return[...e?oSe:sSe]}function vSe(e){var n,r,s;const t=(e==null?void 0:e.rangeLabels)||{};return{poor:((n=t.poor)==null?void 0:n.trim())||xN.poor,satisfactory:((r=t.satisfactory)==null?void 0:r.trim())||xN.satisfactory,good:((s=t.good)==null?void 0:s.trim())||xN.good}}function wSe(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 SSe(e,t,n){const r=QH(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 NSe(i,a,l)}function CSe(e,t,n){return SSe(e,n?"#000000":"#ffffff",t)}function vN({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 NSe(e,t,n){return`#${wN(e)}${wN(t)}${wN(n)}`}function wN(e){return QH(Math.round(e),0,255).toString(16).padStart(2,"0")}function QH(e,t,n){return Math.max(t,Math.min(n,e))}function jSe(e){return e.reduce((t,n)=>ar(t,n||{}),{})}const Wk={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"}},JH=["#dcfce7","#15803d"],I0={type:"matrix",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function kSe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o}){var U,Y,K;if(!Array.isArray(e)||e.length===0)return I0;const{dimensionKeys:i,metricKeys:a,keys:l}=rr(e),u=i[0]??l[0];if(!u)return I0;const d=i[1],f=l.find(H=>H!==u&&!a.includes(H)&&H!==d)??d,h=!d&&(!f||typeof((U=e[0])==null?void 0:U[f])!="string")&&a.length>1,p=a[0]??l.find(H=>H!==u&&H!==f);if(!p&&!h)return I0;const m=r==null?void 0:r.heatmapConfig,g=(m==null?void 0:m.legendPosition)??"bottom",b=h?_Se({data:e,dimensionKey:u,metricKeys:a}):ESe({data:e,xKey:u,yKey:f||p,metricKey:p});if(b.length===0)return I0;const x=h?a.map(zh):SN(b.map(H=>H.x)),y=SN(h?e.map(H=>zh(H==null?void 0:H[u])):b.map(H=>H.y)),v=DSe(b),w=o??ee.getState().themeStyle,S=PSe({min:v.min,max:v.max,heatmapConfig:m,themeStyle:w}),C=MSe({points:b,xLabels:x,yLabels:y,fill:(m==null?void 0:m.fillMissingCells)!==!1}),j=zSe(r),k=["auto","number","currency","percent","none"].includes(j.format)?j.format:"auto",_=Yb("heatmap",r),M=_?{..._,format:_.format??k,formatOptions:_.formatOptions??j.options}:void 0,R=(r==null?void 0:r.dataLabelsConfig)??M,O=TSe({points:C,xLabels:x,yLabels:y,colorScale:S,datasetLabel:h?"Value":p||"Value",dataLabelPrefs:R,formatConfig:j}),T=RSe({xLabels:x,yLabels:y,heatmapConfig:m,formatConfig:j,themeStyle:w,legendPreferences:(K=(Y=r==null?void 0:r.chartOptions)==null?void 0:Y.plugins)==null?void 0:K.legend,cardType:s,legendPosition:g}),{plugins:I=[],options:F}=Vc((r==null?void 0:r.customVisualCode)||""),z=BSe([T,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,F]),B=(m==null?void 0:m.showLegend)===!1?null:OSe({stops:S.stops,min:v.min,max:v.max,formatConfig:j,position:g}),$={type:"matrix",data:{datasets:[O]},options:z,plugins:B?[...I,B]:I};$.options=Cp($.options||{},R,r,"matrix");const P=uk(s??"heatmap","x"),V=uk(s??"heatmap","y"),L=dk(P,r==null?void 0:r.xAxisConfig),A=dk(V,r==null?void 0:r.yAxisConfig),W=L||A||r?{...r||{},...L?{xAxisConfig:L}:{},...A?{yAxisConfig:A}:{}}:r;return $.options=Sp.applyAxisConfig($.options||{},"heatmap",W),$}function ESe({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=zh(i),u=zh(a),d=`${l}__${u}`,f=eU(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 _Se({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=zh(o);n.forEach(a=>{if(a===t)return;const l=eU(s==null?void 0:s[a]),u=zh(a);r.push({x:u,y:i,v:l,raw:{...s,_metricKey:a}})})}),r}function zh(e){return e==null||e===""?"Unknown":String(e)}function eU(e){const t=Number(e);return Number.isFinite(t)?t:null}function SN(e){const t=new Set,n=[];return e.forEach(r=>{t.has(r)||(t.add(r),n.push(r))}),n}function DSe(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 MSe({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 TSe({points:e,xLabels:t,yLabels:n,colorScale:r,datasetLabel:s,dataLabelPrefs:o,formatConfig:i}){const a=pme(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 LSe(h,.85)},borderWidth:1,borderColor:"rgba(255, 255, 255, 0.65)",width:({chart:d})=>{var f;return s5((f=d==null?void 0:d.chartArea)==null?void 0:f.width,t.length)},height:({chart:d})=>{var f;return s5((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)?"":TM(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 Bo($Se(h))},font:{size:Math.max(10,Math.min(14,120/l))}}}}function s5(e,t){return!e||t===0?0:Math.max(4,e/t-2)}function RSe({xLabels:e,yLabels:t,heatmapConfig:n,formatConfig:r,themeStyle:s,legendPreferences:o,cardType:i,legendPosition:a}){var p,m,g;const l=(n==null?void 0:n.showLegend)??!0,u=((g=(m=(p=s==null?void 0:s.chart)==null?void 0:p.options)==null?void 0:m.plugins)==null?void 0:g.tooltip)||{},d=QD(i??"heatmap"),f=JB(d,o);return{responsive:!0,maintainAspectRatio:!1,layout:{padding:ISe(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:ASe(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 ISe(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 ASe(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=TM(n.v,e);return s?`${s}: ${o}`:`${r}: ${o}`}}}function PSe({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"?Wk[i]??Wk.blue:void 0,l=n==null?void 0:n.colorRange,u=l&&l[0]&&l[1]?l:a?[a.start,a.end]:i==="custom"?JH:void 0,d=(u==null?void 0:u[0])??s[0]??o[0],f=(u==null?void 0:u[1])??s[1]??o[1],h=(n==null?void 0:n.colorMode)??"continuous",p=Math.max(3,(n==null?void 0:n.steps)??5),m=(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:du(d)},{offset:1,color:du(f)}]:Array.from({length:p}).map((w,S)=>{const C=p===1?0:S/(p-1||1);return{offset:C,color:o5(du(d),du(f),C)}}),x=h==="continuous"?null:b.map(w=>w.color);return{getColor(w){if(w==null||w===0)return m;if(h==="continuous"){const j=Gg((w-e)/g,0,1);return o5(du(d),du(f),j)}const S=Gg((w-e)/g,0,1),C=Math.min(p-1,Math.max(0,Math.floor(S*p)));return(x==null?void 0:x[C])??du(d)},stops:b}}function OSe({stops:e,min:t,max:n,formatConfig:r,position:s}){if(!e||e.length===0)return null;const o=i=>TM(i,r);return{id:"heatmapLegend",afterDraw(i){var m,g,b,x;const{ctx:a,chartArea:l}=i;if(!a||!l)return;a.save();const u=((x=(b=(g=(m=i.options)==null?void 0:m.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=Bo(nl()),p=24;if(a.font=`${d}px ${f}`,a.fillStyle=h,s==="bottom"||s==="top"){const v=l.left,w=l.right,S=s==="bottom"?l.bottom+p/2:l.top-10-p/2,C=a.createLinearGradient(v,0,w,0);e.forEach(D=>C.addColorStop(D.offset,D.color)),a.fillStyle=C,a.fillRect(v,S,w-v,10),a.fillStyle=h,a.textAlign="left",a.textBaseline=s==="bottom"?"top":"bottom";const j=s==="bottom"?S+10+4:S-4;a.fillText(o(t),v,j),a.textAlign="center",a.fillText(o(t+(n-t)/2),(v+w)/2,j),a.textAlign="right",a.fillText(o(n),w,j)}else{const v=l.top,w=l.bottom,S=s==="left"?l.left-10-p/2:l.right+p/2,C=a.createLinearGradient(0,v,0,w);e.forEach(D=>C.addColorStop(D.offset,D.color)),a.fillStyle=C,a.fillRect(S,v,10,w-v),a.fillStyle=h,a.textAlign=s==="left"?"right":"left",a.textBaseline="middle";const j=s==="left"?S-6:S+10+6;a.fillText(o(n),j,v),a.fillText(o(t+(n-t)/2),j,(v+w)/2),a.fillText(o(t),j,w)}a.restore()}}}function du(e){if(!e)return"#3b82f6";if(e.startsWith("rgb"))return e;if(e.startsWith("#")){const t=tU(e);return t?FSe(t.r,t.g,t.b,1):e}return e}function o5(e,t,n){const r=Wv(e),s=Wv(t);if(!r||!s)return e;const o=Gg(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 Wv(e){if(e.startsWith("#")){const n=tU(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 tU(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 FSe(e,t,n,r){return`rgba(${e}, ${t}, ${n}, ${r})`}function $Se(e){const t=Wv(e);return t?`#${CN(t.r)}${CN(t.g)}${CN(t.b)}`:"#000000"}function CN(e){return Gg(Math.round(e),0,255).toString(16).padStart(2,"0")}function LSe(e,t){const n=Wv(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${Gg(t,0,1)})`:e}function Gg(e,t,n){return Math.min(n,Math.max(t,e))}function TM(e,t){return e==null||Number.isNaN(e)?"—":Fr(e,t.format,t.options)}function zSe(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 BSe(e){return e.reduce((t,n)=>n?Nh({},t,n):t,{})}function RM({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,S,C,j;const f=e.config,h=d??!!e.sql;let p=t;const m=f&&f.pivotByColumns&&f.pivotByColumns.length>0,g=f&&f.groupByColumns&&f.groupByColumns.length>0;if(m&&g&&(p=ume(t,(f==null?void 0:f.metricColumns)||[])),n==="map"){if(!l)return null;const D=(b=a==null?void 0:a.mapVisualOptions)==null?void 0:b.objectKey;if(!D)return null;const k=u1e(l,(x=l==null?void 0:l.objects)==null?void 0:x[D]).features;if(!k)return null;const _={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:((S=a==null?void 0:a.mapVisualOptions)==null?void 0:S.colorScale)||"blues",quantize:5,legend:{position:"bottom-right",align:"right"}}}},{keys:M}=rr(p),R=k.map(B=>{var L;const $=M==null?void 0:M[0],P=M==null?void 0:M[1],V=(L=p.find(A=>(A==null?void 0:A[$])===B.properties.NAME||(A==null?void 0:A[$])===B.properties.name))==null?void 0:L[P];return{feature:B,value:V}}),T=Nd([{label:D,data:R,borderColor:"lightgray"}],s),I={type:"choropleth",data:{labels:k.map(B=>B.properties.NAME||B.properties.name),datasets:T},options:_},{options:F}=wv({cfg:I,preferences:a,customCfg:s,cardType:n});return{...I,options:F}}if(n==="bar"){const D=y1e(r);return ff({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}if(n==="horizontalBar"){const D=b1e(r);return ff({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}if(n==="funnel")return B1e({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="tornado"||n==="pyramid")return U1e({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="treemap")return W1e({data:p,cfg:r,customCfg:s,preferences:a});if(n==="heatmap")return kSe({data:p,cfg:r,customCfg:s,preferences:a,cardType:n});if(n==="bullet")return iSe({data:p,cfg:r,customCfg:s,preferences:a});if(n==="stackedBar"||n==="stackedLine"){const D=qB(p),k=w1e(r,n,D),{keys:_}=rr(p);return!D&&(!m||!g)&&(p=E1({dataArray:p,groupKey:_[0],pivotKey:_[1],valueKey:_[2],sortChart:a==null?void 0:a.sortChart})),ff({card:e,data:p,cfg:k,customCfg:s,cardType:n,preferences:a})}if(n==="line"){const D=S1e(r);return ff({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}if(n==="range")return V1e({data:p,cfg:r,customCfg:s,preferences:a,card:e});if(n==="pie"||n==="doughnut"||n==="polarArea"){const D=C1e(n,r),{keys:k}=rr(p),_=k.slice(0,1),M=k.slice(1),R=GB(M,p,a,_==null?void 0:_[0]),O=Nd(R,s),{plugins:T,options:I}=Vc((a==null?void 0:a.customVisualCode)||""),F=_[0],z=qb(p,F),B=ar((D==null?void 0:D.options)||{},(s==null?void 0:s.options)||{}),$=ar(B,(a==null?void 0:a.chartOptions)||{}),P={...$,plugins:{...$.plugins,datalabels:{...(C=$.plugins)==null?void 0:C.datalabels,formatter:(Y,K)=>{var H,q,X,Z;return Cs({number:Number(Y),decimalPlaces:((H=a==null?void 0:a.numberAxisFormat)==null?void 0:H.decimalPlaces)||0,useSuffix:!!((q=a==null?void 0:a.numberAxisFormat)!=null&&q.suffix),customSuffix:"",locale:((X=a==null?void 0:a.numberAxisFormat)==null?void 0:X.locale)||"",currency:((Z=a==null?void 0:a.numberAxisFormat)==null?void 0:Z.currency)||""})}},tooltip:{...(j=$.plugins)==null?void 0:j.tooltip,callbacks:{label:function(Y){var G,Q,ne,ae;Y.dataset.label;const H=Y.dataset.data.reduce((ie,he)=>ie+he,0),q=Y.parsed,X=Cs({number:Number(q),decimalPlaces:((G=a==null?void 0:a.numberAxisFormat)==null?void 0:G.decimalPlaces)||0,useSuffix:!!((Q=a==null?void 0:a.numberAxisFormat)!=null&&Q.suffix),customSuffix:"",locale:((ne=a==null?void 0:a.numberAxisFormat)==null?void 0:ne.locale)||"",currency:((ae=a==null?void 0:a.numberAxisFormat)==null?void 0:ae.currency)||""}),Z=(q/H*100).toFixed(2);return X+` (${Z}%)`},footer:function(Y){var H,q,X,Z;return(((q=(H=e==null?void 0:e.interactionConfig)==null?void 0:H.drillHierarchies)==null?void 0:q.length)??0)>0||(((Z=(X=e==null?void 0:e.interactionConfig)==null?void 0:X.interactions)==null?void 0:Z.some(G=>G.mode==="drillDown"||G.mode==="drillToDetail"||G.mode==="drillThrough"||G.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},V=ar($,P),{options:L}=wv({cfg:{options:V},preferences:a,customCfg:s,cardType:n,card:e}),A=ar(L,I);return{type:n,data:{labels:z,datasets:O},options:A,plugins:[n==="doughnut"?{id:"doughnutLabel",beforeDatasetsDraw:function(Y,K,H){var he,be,Ce,Oe;const{ctx:q,data:X}=Y;q.save();const Z=Y.getDatasetMeta(0).data[0].x,G=Y.getDatasetMeta(0).data[0].y,Q=Bo(nl()),ne=window.getComputedStyle(q.canvas).fontFamily;q.font=`1em ${ne}`,q.fontWeight="bolder",q.fillStyle=Q,q.textAlign="center",q.textBaseline="middle";const ae=X.datasets[0].data.reduce((ue,De)=>ue+De,0),ie=Cs({number:Number(ae),decimalPlaces:((he=a==null?void 0:a.numberAxisFormat)==null?void 0:he.decimalPlaces)||0,useSuffix:!!((be=a==null?void 0:a.numberAxisFormat)!=null&&be.suffix),customSuffix:"",locale:((Ce=a==null?void 0:a.numberAxisFormat)==null?void 0:Ce.locale)||"",currency:((Oe=a==null?void 0:a.numberAxisFormat)==null?void 0:Oe.currency)||""});q.fillText(ie,Z,G)}}:"",...T]}}if(n==="radar"){const D=N1e(r);return ff({card:e,data:p,cfg:D,customCfg:s,cardType:n,preferences:a})}return n==="bubble"||n==="scatter"?E1e({data:p,cfg:r,customCfg:s,preferences:a,cardType:n,cardConfig:f,isDevMode:h,card:e}):ff({card:e,data:p,cfg:r,customCfg:s,cardType:n,preferences:a})}function VSe({chart:e,elementIndex:t,datasetIndex:n,cardType:r,cfg:s,apply:o}){const i=ee.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)&&USe(e,t,s,o,a),["pie","doughnut","polarArea","funnel"].includes(r)&&WSe(e,t,s,o,a),["stackedBar","pyramid"].includes(r)&&HSe({chart:e,elementIndex:t,datasetIndex:n,cfg:s,apply:o,blurColor:a})}function HSe(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 p,m;typeof f.backgroundColor=="string"&&(f.backgroundColor=new Array(f.data.length).fill(f.backgroundColor),f.borderColor=new Array(f.data.length).fill(f.borderColor)),f.backgroundColor=(p=f==null?void 0:f.backgroundColor)==null?void 0:p.map((g,b)=>b===n&&h===r?g:i),f.borderColor=(m=f==null?void 0:f.borderColor)==null?void 0:m.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 p,m,g,b,x,y;f.backgroundColor=new Array(f.data.length).fill((g=(m=(p=s==null?void 0:s.data)==null?void 0:p.datasets)==null?void 0:m[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 USe(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,p)=>p===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,p)=>p===t?h:s)}):(l=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||l.forEach((u,d)=>{var f,h,p,m,g,b;u.backgroundColor=new Array(u.data.length).fill((p=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:p.backgroundColor),u.borderColor=new Array(u.data.length).fill((b=(g=(m=n==null?void 0:n.data)==null?void 0:m.datasets)==null?void 0:g[d])==null?void 0:b.borderColor)}),e==null||e.update()}function WSe(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,p)=>p===t?h:s),u.borderColor=(f=u==null?void 0:u.borderColor)==null?void 0:f.map((h,p)=>p===t?h:s)}):(l=(a=e==null?void 0:e.data)==null?void 0:a.datasets)==null||l.forEach((u,d)=>{var f,h,p,m,g,b,x,y;typeof u.backgroundColor=="string"&&(u.backgroundColor=(p=(h=(f=n==null?void 0:n.data)==null?void 0:f.datasets)==null?void 0:h[d])==null?void 0:p.backgroundColor,u.borderColor=(b=(g=(m=n==null?void 0:n.data)==null?void 0:m.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 S;return(S=n.data.datasets[d].backgroundColor)==null?void 0:S[w]}),u.borderColor=(y=u==null?void 0:u.borderColor)==null?void 0:y.map((v,w)=>{var S;return(S=n.data.datasets[d].borderColor)==null?void 0:S[w]})}),e==null||e.update()}function qSe({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}=rr(t);if(e.type==="map"){const p=h[0],m=((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:p,columnValue:m}]}if(["bar","horizontalBar","line","pie","doughnut","radar","polarArea","funnel"].includes(e.type)){const p=h[0],m=h.slice(1),g=(u=t[r])==null?void 0:u[p];return[{columnName:p,columnValue:g,metric:m[n],value:s}]}if(["stackedBar","pyramid"].includes(e.type)){const p=E1({dataArray:t,groupKey:h[0],pivotKey:h[1],valueKey:h[2]}),m=h[0],g=(d=p[r])==null?void 0:d[m],b=h[1],{keys:x}=rr(p),v=x.slice(1)[n];return[{columnName:m,columnValue:g,metric:h[2],value:s},{columnName:b,columnValue:v,metric:h[2],value:s}]}if(e.type==="bubble"||e.type==="scatter"){const p=h[0],m=(f=t[n])==null?void 0:f[p];return console.log(s,"bubble"),[{columnName:p,columnValue:m,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 YSe(e,t){var r,s;if((((r=e.data.datasets)==null?void 0:r.filter(o=>!!o.fill))||[]).length>0){const o=(s=e==null?void 0:e.data.datasets)==null?void 0:s.map(a=>({...a,backgroundColor:[a.backgroundColor].map(l=>{const u=t.createLinearGradient(0,0,0,400);return u.addColorStop(0,l),u.addColorStop(.7,cme("--semaphor-background")),u})}));return{...e,data:{...e.data,datasets:o}}}return e}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}=un({queryKey:["topojson",t],queryFn:()=>fetch(t).then(p=>p.json()),enabled:n,staleTime:1/0});return{data:r,isLoading:s,isFetching:o,isError:i}}function Ii(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,r=Ee(h=>h.selectedConnectionId),s=Ee(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.connectionId}),o=r||s,{refetch:i,isPending:a,data:l,isLoading:u,isError:d}=un({queryKey:[t.project_id,"connections"],queryFn:()=>Vn(`${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 GSe(e){const{connections:t}=Ii(e),n=Ee(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}}function KSe(e){return e.flatMap(t=>t.columns.map(n=>({id:`${t.entityId}-${n.name}`,name:n.name,qualifiedFieldName:n.qualifiedFieldName,dataType:n.dataType,qualifiedEntityName:t.qualifiedEntityName,label:n.label||Yo(n.name),description:n.description,entityId:t.entityId,entityName:t.entityName,entityType:t.entityType})))}function Lf(e){if(gj.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 IM(e){var b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{hasSchemaSupport:r}=GSe(e),s=Ee(x=>{var y;return(y=x.card.dataSource)==null?void 0:y.connectionId}),o=Ee(x=>{var y,v;return(v=(y=x.card.dataSource)==null?void 0:y.selectedEntities)==null?void 0:v.filter(w=>w.type==="model")})||[],i=Ee(x=>{var y,v;return(v=(y=x.card.dataSource)==null?void 0:y.selectedEntities)==null?void 0:v.filter(w=>gj.includes(w.type))})||[],a=Ee(x=>{var y,v;return(v=(y=x.card.dataSource)==null?void 0:y.selectedEntities)==null?void 0:v.filter(w=>w.type==="dataset")})||[];function l(x){return x.type==="dataset"?!!s&&!!x.domainId&&!!x.name:x.type==="model"?!!s&&!!x.id:gj.includes(x.type)?r?!!s&&!!x.name&&!!x.database&&!!x.schema:["S3","API"].includes(x.connectionType)?!!s&&!!x.name:!!s&&!!x.name&&!!x.database:!1}const u=[...o,...i,...a],d=B_({queries:u.map(x=>{let y={};return x.type==="model"?y={connection_id:s,datamodel_id:x.id,database_name:"",schema_name:"",table_name:""}:x.type==="dataset"?y={connection_id:x.connectionId,domain_id:x.domainId,dataset_name:x.name}:y={connection_id:s,datamodel_id:"",database_name:x.database,schema_name:x.schema,table_name:x.name},{queryKey:["columns",s,x],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",y),enabled:!!s&&l(x)}})}),f=d.some(x=>x.isPending),h=d.some(x=>x.isError),p=(b=d.find(x=>x.isError))==null?void 0:b.error,m=d.map((x,y)=>{var S;const v=u[y],w=Lf(v);return{entityId:v.id||v.name,entityType:v.type,entityName:v.name,label:v.label,description:v.description,qualifiedEntityName:w,columns:(S=x.data)==null?void 0:S.columns.map(C=>({id:`${v.name}-${C.column_name}`,name:C.column_name,qualifiedFieldName:C.qualifiedFieldName||C.column_name,dataType:C.data_type,label:C.label||P_(C.column_name),description:C.description||"",qualifiedEntityName:w,entityId:v.id||v.id||v.name,entityName:v.name,entityType:v.type}))}}).filter(x=>{var y;return((y=x==null?void 0:x.columns)==null?void 0:y.length)>0})||[],g=KSe(m);return{columnGroups:m,columns:g,isLoading:f,hasError:h,error:p,refetch:()=>{d.forEach(x=>x.refetch())}}}function ZSe(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 AM(e,t){var m,g,b,x,y,v,w;const{joinabilityMap:n,selectedFields:r,cardConfig:s,autoJoinMetadata:o,baseEntityName:i}=t;if(!n)return{state:"draggable"};if(r.length===0)return{state:"draggable",tooltip:"Select to establish base dataset"};let a;const l=(g=(m=s==null?void 0:s.joinPlan)==null?void 0:m.baseEntity)==null?void 0:g.name,u=(x=(b=o==null?void 0:o.resolvedJoinPlan)==null?void 0:b.baseEntity)==null?void 0:x.name;l?a=l:u?a=u:i?a=i:a=[...new Set(r.map(C=>C.entityName))].filter(Boolean)[0];const d=r.some(S=>S.entityName===e.entityName&&(S.name===e.name||S.id===e.id));if(e.entityName===a)return{state:"base",tooltip:d?"Field already in query (base dataset)":"From base dataset",isSelected:d};const f=n[a];if(!f)return{state:"unreachable",tooltip:"No relationships defined for base dataset"};if(f.canJoinTo.includes(e.entityName))return{state:"draggable",tooltip:`Direct join from ${a}`,joinPath:[a,e.entityName],isSelected:d};const h=(y=f.indirectJoins)==null?void 0:y[e.entityName];if(h&&h.length>0){const S=[a,...h,e.entityName];return{state:"indirect",joinPath:S,tooltip:`Multi-hop join: ${S.join(" → ")}`,isSelected:d}}const p=n[e.entityName];if(p){if(p.canJoinTo.includes(a))return{state:"draggable",tooltip:`Direct join to ${a}`,joinPath:[e.entityName,a],isSelected:d};const S=(v=p.indirectJoins)==null?void 0:v[a];if(S&&S.length>0){const C=[e.entityName,...S,a];return{state:"indirect",joinPath:C,tooltip:`Multi-hop join: ${C.join(" → ")}`,isSelected:d}}}return(w=s==null?void 0:s.joinPlan)!=null&&w.joins&&s.joinPlan.joins.length>0&&ZSe(a,e.entityName,s.joinPlan.joins)?{state:"draggable",tooltip:"Manual join configured",isSelected:d}:{state:"unreachable",tooltip:`Cannot join ${e.entityName} to ${a}`,isSelected:d}}function rU(e,t,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:e===t||e===Lf(n.baseEntity)||t===Lf(n.baseEntity)?!0:n.joins.some(s=>{const o=Lf(s.source),i=Lf(s.target);return o===e&&i===t||o===t&&i===e})}function XSe(e,t,n){var a;const{joinPlan:r,joinabilityMap:s,semanticDomainId:o}=n;if(t.length===0)return{isValid:!0};const i=t[0].qualifiedEntityName;if(!i)return{isValid:!0};if(i===e.qualifiedEntityName)return{isValid:!0};if(e.qualifiedEntityName){if(o&&s)return AM(e,{joinabilityMap:s,selectedFields:t,baseEntityName:(a=r==null?void 0:r.baseEntity)==null?void 0:a.name}).state==="unreachable"?{isValid:!1,showError:!0}:{isValid:!0};if(!r)return{isValid:!1,showError:!0};if(!rU(i,e.qualifiedEntityName,r))return{isValid:!1,showError:!0}}return{isValid:!0}}function sU(){$e.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 oU(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 QSe(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 JSe(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 iU(e,t){return`${e}-${t.qualifiedEntityName}-${t.name}-${Date.now()}`}function aU(e,t){const n=Yo(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 eCe(e,t,n){const r=Ks(e.dataType);return n==="kpi"?r==="date"?"groupBy":"metrics":t.length===0||r==="number"?"metrics":r==="date"||r==="string"||r==="boolean"?"groupBy":"metrics"}function lU(e,t,n=[]){const r=iU(t,e),s=Ks(e.dataType),o=s==="date",i={id:r,name:e.name,dataType:e.dataType,label:P_(e.name),qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityId:e.entityId,entityName:e.entityName,entityType:e.entityType};if(t==="metrics"){const a=s==="number"?"SUM":"COUNT",l=aU(e.label,a),u=JSe({...i,label:l},n,t);return{...i,role:"metric",label:u,aggregate:a}}return t==="groupBy"?{...i,role:"groupby",...o&&{granularity:"month",dateFormat:"YYYY-MM"}}:t==="pivotBy"?{...i,role:"pivotby"}:t==="sortBy"?{...i,role:"sortby",label:e.label,direction:"asc"}:null}function tCe(e){var s,o,i;const t=(s=e.config)==null?void 0:s.metricColumns,n=(o=e.config)==null?void 0:o.groupByColumns,r=(i=e.config)==null?void 0:i.pivotByColumns;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)}function nCe(e){var i,a;const[t]=N.useState({id:"",title:"",type:"bar"}),{getCard:n}=Yt(),r=n(e),s=Xb(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 Xb(e){var O;const{onChartElementClicked:t}=qe(),[n,r]=N.useState(0),s=ee(T=>T.themeStyle),o=ee(T=>T.filteringCards),i=ee(T=>T.selectedSheetId),a=ee(T=>T.selectedLensId),l=ee(T=>T.filterValues),u=N.useRef(l),d=(O=e==null?void 0:e.preferences)==null?void 0:O.onClickFilter,{addFilteringCard:f,addOrUpdateFilterValues:h,removeFilterValues:p,removeFilteringCard:m}=Yt(),{data:g,isLoading:b,isFetching:x,isError:y,isPending:v,queryKey:w,isFilteringCard:S,isSingleCardFrame:C,pagination:j,comparisonMetadata:D}=fa(e),{data:k}=nU(e);let _;_=N.useMemo(()=>{if(!(!(g!=null&&g.records)||!(g!=null&&g.records.length)))return RM({card:e,data:g==null?void 0:g.records,cardType:e.type,queryConfig:e.queryConfig,customCfg:e.customCfg,preferences:e.preferences,topoJson:k})},[g==null?void 0:g.records,e,k,s]);const M=N.useRef({filteringCards:o});N.useEffect(()=>{e.connectionId&&!S&&(u.current=l)},[l,a,e.connectionId,S]),N.useEffect(()=>{var I;S&&(M.current.filteringCards=[...o||[]]),!S&&((I=M.current.filteringCards)==null?void 0:I.find(F=>F.id===e.id))&&C&&r(F=>F+1)},[S,C,e.id,o]);function R(T,I,F,z){var P;if(tCe(e))return;let B=!1;if(!(g!=null&&g.records))return;const $=qSe({card:e,data:g==null?void 0:g.records,datasetIndex:I,clickIndex:F,value:z});if(console.log("fieldValues",$),t==null||t(e,$),!!(((P=e==null?void 0:e.preferences)==null?void 0:P.onClickFilter)??[]).length){if(S){const V=e.id;p(V),m(e)}else{if(B=!0,!$)return;const V=[];$.forEach((L,A)=>{const W=d==null?void 0:d.find(Y=>Y.columnIndex===A);if(!W)return;const U={filterId:e.id+"-"+L.columnName+"-"+i,connectionId:e==null?void 0:e.connectionId,tableName:e.lastSelectedTable,name:L.columnName,expression:W.expression,valueType:I_($[W.columnIndex].columnValue),operation:"=",values:[$[W.columnIndex].columnValue]};V.push(U)}),h(V),f(e)}VSe({chart:T,elementIndex:F,datasetIndex:I,cardType:e.type,cfg:_,apply:B})}}return{isPending:v,isError:y,isLoading:b,isFetching:x,data:g,visualKey:n,handleDatapointClick:R,cfg:_,queryKey:w,pagination:j,comparisonMetadata:D}}function cU(e){var x;const{tokenProps:t}=qe(),n=ee(y=>y.authToken)||e,r=Ee(y=>y.selectedConnectionId),s=Ee(y=>y.selectedDatabaseName),o=Ee(y=>y.selectedDatamodelId),i=Ee(y=>y.selectedSchemaName),a=Ee(y=>y.selectedTableName),{selectedConnection:l}=Ii(),u=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:p,refetch:m}=un({queryKey:["columns",r,s,o,i,a],queryFn:()=>Vn(`${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:p,refetchColumns:m}}function lg(e,t){const[n,r]=N.useState(e);return N.useEffect(()=>{const s=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(s)}},[e,t]),n}var rCe=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 uU=$c(rCe);function A0(e,t=uU){const[n,r]=N.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 sCe(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 uU(e,t)}const i5={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:""},us=pl()(Mb(e=>({...i5,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=>VB(t),resetShareState:()=>{e(t=>{Object.assign(t,i5)})},resetUserSelections:()=>{e(t=>{t.selectedUsers=[],t.usersToRemove=[],t.usersToUpdate=[]})},resetGroupSelections:()=>{e(t=>{t.selectedGroups=[],t.groupsToRemove=[],t.groupsToUpdate=[]})}}}))),dU=()=>us(e=>e.searchQuery),_p=()=>us(e=>e.selectedUsers),Qd=()=>us(e=>e.usersToRemove),Dp=()=>us(e=>e.usersToUpdate),Qb=()=>us(e=>e.selectedTenant),PM=()=>us(e=>e.selectedTab),fU=()=>us(e=>e.currentContext),Wc=()=>us(e=>e.currentMode),OM=()=>us(e=>e.orgWideRole),FM=()=>us(e=>e.allTenantsRole),L1=()=>us(e=>e.tenantWideRole),hU=()=>us(e=>e.groupWideRole),Mp=()=>us(e=>e.selectedGroups),Tp=()=>us(e=>e.groupsToRemove),Rp=()=>us(e=>e.groupsToUpdate),qc=()=>us(e=>e.actions),$M=()=>{const e=dU(),t=lg(e,300),n=qc();return N.useEffect(()=>{n.setDebouncedSearchQuery(t)},[t,n]),{searchQuery:e,debouncedSearchQuery:t,setSearchQuery:n.setSearchQuery}};function Li(e,t){var n;return((n=t.find(r=>r.value===e))==null?void 0:n.label)||e}function oCe(e){return["POWER_USER","ADMIN","EDITOR"].includes(e)}function pU(e){return"tenantId"in e&&e.tenantId?"tenant":"organization"}function iCe(e,t,n){const r=pU(e),s=(n==null?void 0:n.type)||"organization";if(!(!t||!t.shares))if(s==="organization")if(r==="organization"){if("specificOrgUsers"in t.shares)return(t.shares.specificOrgUsers||[]).find(a=>a.orgUserId===e.id)}else return(t.shares.specificTenantUsers||[]).find(a=>a.tenantUserId===e.id);else return(t.shares.specificTenantUsers||[]).find(a=>a.tenantUserId===e.id)}function aCe({user:e}){return pU(e)==="tenant"?c.jsx(Fe,{variant:"outline",className:"text-xs",children:e.role==="POWER_USER"?"Power User":"Viewer"}):c.jsx(Fe,{variant:"outline",className:"text-xs",children:e.role==="ADMIN"?"Admin":e.role==="POWER_USER"?"Power User":"Viewer"})}function lCe({user:e,userShare:t,usersToUpdate:n,currentUser:r,getRoleOptions:s,handleUpdateAccess:o}){if(!(t!=null&&t.role))return null;const i=oCe((r==null?void 0:r.type)||""),a=n.some(f=>f.id===e.id),l=n.find(f=>f.id===e.id),u=l?l.newRole:t==null?void 0:t.role,d=s(e.type);return t?c.jsx("div",{className:"flex items-center gap-2",children:i?c.jsx(Sd,{currentRole:u,onRoleChange:f=>{o(e.id,t.role,f)},roleOptions:d,disabled:!i,allowDropdown:i,className:a?"border-orange-300 bg-orange-100":""}):c.jsx(Fe,{variant:"outline",className:"text-xs",children:Li(u,d)})}):c.jsx(Fe,{variant:"outline",className:"text-xs",children:"Unknown"})}function cCe({hasAccess:e,isUserRemoving:t,isSelected:n,hasAccessFromAPI:r}){return c.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e&&!t&&c.jsxs(Fe,{variant:"outline",className:"border-green-200 bg-green-50 text-xs text-green-700",children:[c.jsx(bc,{className:"mr-1 h-3 w-3"}),"Has Access"]}),t&&c.jsxs(Fe,{variant:"outline",className:"border-red-200 bg-red-50 text-xs text-red-700",children:[c.jsx(vt,{className:"mr-1 h-3 w-3"}),"Remove Access"]}),n&&!r&&c.jsxs(Fe,{variant:"outline",className:"border-blue-200 bg-blue-50 text-xs text-blue-700",children:[c.jsx(Qu,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function uCe({isUserRemoving:e,isRemoving:t}){return c.jsx(c.Fragment,{children:e&&c.jsx("span",{className:"text-xs font-medium text-red-600",children:t?c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx(On,{className:"h-3 w-3 animate-spin"}),"Removing..."]}):"⚠ Will remove access"})})}function dCe({existingShares:e,allUsers:t,getRoleOptions:n,currentUser:r}){if(((r==null?void 0:r.type)||"organization")==="organization")if("specificOrgUsers"in e.shares){const i=e.shares,a=i.specificOrgUsers||[],l=i.specificTenantUsers||[],u=i.orgWide||[],d=i.orgUsersOnly||[],f=i.allTenantsOnly||[];return c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"font-medium",children:"Current Access"}),c.jsxs("div",{className:"space-y-2",children:[a.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Org Users (",a.length,")"]}),c.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[a.slice(0,3).map((h,p)=>{var x,y;const m=((x=t.find(v=>v.id===h.orgUserId))==null?void 0:x.name)||"Unknown User",g=((y=t.find(v=>v.id===h.orgUserId))==null?void 0:y.type)||"",b=Li(h.role,n(g));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:m}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},p)}),a.length>3&&c.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",a.length-3," more users"]})]})]}),l.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-xs font-medium text-green-600",children:["Specific Tenant Users (",l.length,")"]}),c.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[l.slice(0,3).map((h,p)=>{var x,y;const m=((x=t.find(v=>v.id===h.tenantUserId))==null?void 0:x.name)||"Unknown User",g=((y=t.find(v=>v.id===h.tenantUserId))==null?void 0:y.type)||"",b=Li(h.role,n(g));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:m}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:b})]},p)}),l.length>3&&c.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",l.length-3," more users"]})]})]}),u.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-purple-600",children:"All Org Users"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:u.map((h,p)=>{const m=Li(h.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"All Organization Users"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},p)})})]}),d.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-orange-600",children:"Org Users Only"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:d.map((h,p)=>{const m=Li(h.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"Org Users Only"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},p)})})]}),f.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-indigo-600",children:"All Tenants"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:f.map((h,p)=>{const m=Li(h.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"All Tenants"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:m})]},p)})})]}),!a.length&&!l.length&&!u.length&&!d.length&&!f.length&&c.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const i=e.shares.specificTenantUsers||[],a=e.shares.tenantWide||[];return c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"font-medium",children:"Current Access"}),c.jsxs("div",{className:"space-y-2",children:[i.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",i.length,")"]}),c.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[i.slice(0,3).map((l,u)=>{var p,m;const d=((p=t.find(g=>g.id===l.tenantUserId))==null?void 0:p.name)||"Unknown User",f=((m=t.find(g=>g.id===l.tenantUserId))==null?void 0:m.type)||"",h=Li(l.role,n(f));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:d}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:h})]},u)}),i.length>3&&c.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",i.length-3," more users"]})]})]}),a.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:a.map((l,u)=>{const d=Li(l.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:d})]},u)})})]}),!i.length&&!a.length&&c.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}else{const o=e.shares.specificTenantUsers||[],i=e.shares.tenantWide||[];return c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"font-medium",children:"Current Access"}),c.jsxs("div",{className:"space-y-2",children:[o.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-xs font-medium text-blue-600",children:["Specific Users (",o.length,")"]}),c.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[o.slice(0,3).map((a,l)=>{var h,p;const u=((h=t.find(m=>m.id===a.tenantUserId))==null?void 0:h.name)||"Unknown User",d=((p=t.find(m=>m.id===a.tenantUserId))==null?void 0:p.type)||"",f=Li(a.role,n(d));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"truncate text-muted-foreground",children:u}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:f})]},l)}),o.length>3&&c.jsxs("div",{className:"text-xs italic text-muted-foreground",children:["+",o.length-3," more users"]})]})]}),i.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"text-xs font-medium text-green-600",children:"All Users"}),c.jsx("div",{className:"grid grid-cols-1 gap-1",children:i.map((a,l)=>{const u=Li(a.role,n(""));return c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsx("span",{className:"text-muted-foreground",children:"All Tenant Users"}),c.jsx(Fe,{variant:"outline",className:"ml-2 shrink-0 px-2 py-0.5 text-xs",children:u})]},l)})})]}),!o.length&&!i.length&&c.jsx("div",{className:"text-xs italic text-muted-foreground",children:"No users currently have access"})]})]})}}function fCe({isInitialLoading:e,searchQuery:t,availableUsers:n}){return e?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading users..."})]})}):n.length===0?c.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:t?"No users found matching your search.":"No users available to share with."}):null}function hCe({user:e,userShare:t,isUserRemoving:n,hasAccess:r,hasAccessFromAPI:s,isSelected:o,selectedUser:i,roleOptions:a,currentUser:l,usersToUpdate:u,handleUserToggle:d,handleRemoveAccess:f,handleUpdateAccess:h,handleUserRoleChange:p}){return c.jsxs("div",{className:J("flex items-center space-x-3 rounded-lg p-2 transition-colors",r&&!n?"border border-green-200 bg-green-50":n?"border border-red-200 bg-red-50":o?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[c.jsx(dn,{checked:s?!n:o,onCheckedChange:()=>{s?n?d(e.id):f(e.id):d(e.id)}}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("p",{className:"truncate text-sm font-medium",children:e.name}),c.jsx(aCe,{user:e})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?c.jsx(Sd,{currentRole:t==null?void 0:t.role,onRoleChange:m=>h(e.id,t.role,m),roleOptions:a,disabled:!1,allowDropdown:!0}):c.jsx(lCe,{user:e,userShare:t,usersToUpdate:u,currentUser:l,getRoleOptions:()=>a,handleUpdateAccess:h}),o&&!s&&c.jsx("div",{onClick:m=>m.stopPropagation(),children:c.jsx(Sd,{currentRole:(i==null?void 0:i.role)||"VIEWER",onRoleChange:m=>p(e.id,m),roleOptions:a,disabled:!1})})]})]}),c.jsx("p",{className:"truncate text-xs text-muted-foreground",children:e.email}),c.jsx(cCe,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:s}),c.jsx(uCe,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function mU({existingShares:e,isInitialLoading:t,isSearching:n,getRoleOptions:r,allUsers:s=[],currentUser:o,handleUserToggle:i,handleUserRoleChange:a,handleRemoveAccess:l,handleUpdateAccess:u}){const d=_p(),f=Qd(),h=Dp(),p=dU(),m=qc(),g=i||(S=>{const C=d.some(D=>D.id===S),j=f.includes(S);C?m.removeSelectedUser(S):j?m.removeUserFromRemove(S):m.addSelectedUser({id:S,role:"VIEWER"})}),b=a||m.updateSelectedUserRole,x=l||m.addUserToRemove,y=u||((S,C,j)=>{m.addUserToUpdate({id:S,currentRole:C,newRole:j})}),v=s.filter(S=>S.id!==(o==null?void 0:o.id)),w=f;return c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs(ce,{className:"text-sm font-medium",children:["All Users (",(v??[]).length,")"]}),c.jsx(Yn,{children:c.jsxs(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:c.jsx(xr,{className:"h-4 w-4"})})}),c.jsx(Cn,{className:"w-48 max-w-sm",children:c.jsx(dCe,{existingShares:e,allUsers:s,getRoleOptions:r,currentUser:o})})]})})]}),(v==null?void 0:v.length)>0&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>{d.length===v.length?m.setSelectedUsers([]):m.setSelectedUsers(v.map(S=>({id:S.id,role:"VIEWER"})))},className:"h-7 text-xs",children:d.length===v.length?"Deselect all":"Select all"})]}),c.jsxs("div",{className:"max-h-60 space-y-1 overflow-y-auto rounded-md border p-2",children:[c.jsx(fCe,{isInitialLoading:t,isSearching:n,searchQuery:p,availableUsers:v||[]}),!t&&!n&&(v==null?void 0:v.length)>0&&v.map(S=>{const C=e?iCe(S,e,o):void 0,j=w.includes(S.id),D=!!C,k=D&&!j,_=d.some(O=>O.id===S.id),M=d.find(O=>O.id===S.id),R=r(S.type);return c.jsx(hCe,{user:S,userShare:C,isUserRemoving:j,hasAccess:k,hasAccessFromAPI:D,isSelected:_,selectedUser:M,roleOptions:R,currentUser:o,usersToUpdate:h,handleUserToggle:g,handleRemoveAccess:x,handleUpdateAccess:y,handleUserRoleChange:b},S.id)})]})]})}var LM="Radio",[pCe,gU]=_r(LM),[mCe,gCe]=pCe(LM),bU=E.forwardRef((e,t)=>{const{__scopeRadio:n,name:r,checked:s=!1,required:o,disabled:i,value:a="on",onCheck:l,form:u,...d}=e,[f,h]=E.useState(null),p=ft(t,b=>h(b)),m=E.useRef(!1),g=f?u||!!f.closest("form"):!0;return c.jsxs(mCe,{scope:n,checked:s,disabled:i,children:[c.jsx(Be.button,{type:"button",role:"radio","aria-checked":s,"data-state":vU(s),"data-disabled":i?"":void 0,disabled:i,value:a,...d,ref:p,onClick:ke(e.onClick,b=>{s||l==null||l(),g&&(m.current=b.isPropagationStopped(),m.current||b.stopPropagation())})}),g&&c.jsx(bCe,{control:f,bubbles:!m.current,name:r,value:a,checked:s,required:o,disabled:i,form:u,style:{transform:"translateX(-100%)"}})]})});bU.displayName=LM;var xU="RadioIndicator",yU=E.forwardRef((e,t)=>{const{__scopeRadio:n,forceMount:r,...s}=e,o=gCe(xU,n);return c.jsx(sr,{present:r||o.checked,children:c.jsx(Be.span,{"data-state":vU(o.checked),"data-disabled":o.disabled?"":void 0,...s,ref:t})})});yU.displayName=xU;var bCe=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=E.useRef(null),i=j1(n),a=h1(t);return E.useEffect(()=>{const l=o.current,u=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(u,"checked").set;if(i!==n&&f){const h=new Event("click",{bubbles:r});f.call(l,n),l.dispatchEvent(h)}},[i,n,r]),c.jsx("input",{type:"radio","aria-hidden":!0,defaultChecked:n,...s,tabIndex:-1,ref:o,style:{...e.style,...a,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})};function vU(e){return e?"checked":"unchecked"}var xCe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],zM="RadioGroup",[yCe]=_r(zM,[up,gU]),wU=up(),SU=gU(),[vCe,wCe]=yCe(zM),CU=E.forwardRef((e,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:s,value:o,required:i=!1,disabled:a=!1,orientation:l,dir:u,loop:d=!0,onValueChange:f,...h}=e,p=wU(n),m=Vd(u),[g,b]=$r({prop:o,defaultProp:s,onChange:f});return c.jsx(vCe,{scope:n,name:r,required:i,disabled:a,value:g,onValueChange:b,children:c.jsx(wD,{asChild:!0,...p,orientation:l,dir:m,loop:d,children:c.jsx(Be.div,{role:"radiogroup","aria-required":i,"aria-orientation":l,"data-disabled":a?"":void 0,dir:m,...h,ref:t})})})});CU.displayName=zM;var NU="RadioGroupItem",jU=E.forwardRef((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...s}=e,o=wCe(NU,n),i=o.disabled||r,a=wU(n),l=SU(n),u=E.useRef(null),d=ft(t,u),f=o.value===s.value,h=E.useRef(!1);return E.useEffect(()=>{const p=g=>{xCe.includes(g.key)&&(h.current=!0)},m=()=>h.current=!1;return document.addEventListener("keydown",p),document.addEventListener("keyup",m),()=>{document.removeEventListener("keydown",p),document.removeEventListener("keyup",m)}},[]),c.jsx(SD,{asChild:!0,...a,focusable:!i,active:f,children:c.jsx(bU,{disabled:i,required:o.required,checked:f,...l,...s,name:o.name,ref:d,onCheck:()=>o.onValueChange(s.value),onKeyDown:ke(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:ke(s.onFocus,()=>{var p;h.current&&((p=u.current)==null||p.click())})})})});jU.displayName=NU;var SCe="RadioGroupIndicator",kU=E.forwardRef((e,t)=>{const{__scopeRadioGroup:n,...r}=e,s=SU(n);return c.jsx(yU,{...s,...r,ref:t})});kU.displayName=SCe;var EU=CU,_U=jU,CCe=kU;const ma=E.forwardRef(({className:e,...t},n)=>c.jsx(EU,{className:J("grid gap-2",e),...t,ref:n}));ma.displayName=EU.displayName;const Nr=E.forwardRef(({className:e,...t},n)=>c.jsx(_U,{ref:n,className:J("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:c.jsx(CCe,{className:"flex items-center justify-center",children:c.jsx(X_,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Nr.displayName=_U.displayName;function BM({shareType:e,onShareTypeChange:t,currentUser:n,options:r}){const s=(n==null?void 0:n.role)&&["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role);return c.jsxs("div",{className:"space-y-3",children:[c.jsx(ma,{value:e,onValueChange:t,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>c.jsxs("div",{children:[c.jsx(Nr,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),c.jsxs(ce,{htmlFor:o.value,className:`flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary peer-data-[state=checked]:bg-primary/5 [&:has([data-state=checked])]:border-primary [&:has([data-state=checked])]:bg-primary/5 ${o.disabled?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[o.icon||c.jsx(xc,{className:"mb-3 h-6 w-6"}),c.jsxs("div",{className:"space-y-1 text-center",children:[c.jsx("p",{className:"text-sm font-medium leading-none",children:o.label}),c.jsx("p",{className:"text-xs text-muted-foreground",children:o.description})]})]})]},o.value))}),!s&&r.some(o=>o.value==="all_users")&&c.jsx("p",{className:"text-xs text-muted-foreground",children:"Only admins, authors, power users, can share with all users."})]})}var NN,VM="HoverCard",[DU]=_r(VM,[ya]),z1=ya(),[NCe,B1]=DU(VM),MU=e=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:s,onOpenChange:o,openDelay:i=700,closeDelay:a=300}=e,l=z1(t),u=E.useRef(0),d=E.useRef(0),f=E.useRef(!1),h=E.useRef(!1),[p=!1,m]=$r({prop:r,defaultProp:s,onChange:o}),g=E.useCallback(()=>{clearTimeout(d.current),u.current=window.setTimeout(()=>m(!0),i)},[i,m]),b=E.useCallback(()=>{clearTimeout(u.current),!f.current&&!h.current&&(d.current=window.setTimeout(()=>m(!1),a))},[a,m]),x=E.useCallback(()=>m(!1),[m]);return E.useEffect(()=>()=>{clearTimeout(u.current),clearTimeout(d.current)},[]),c.jsx(NCe,{scope:t,open:p,onOpenChange:m,onOpen:g,onClose:b,onDismiss:x,hasSelectionRef:f,isPointerDownOnContentRef:h,children:c.jsx(lp,{...l,children:n})})};MU.displayName=VM;var TU="HoverCardTrigger",RU=E.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=B1(TU,n),o=z1(n);return c.jsx(cp,{asChild:!0,...o,children:c.jsx(Be.a,{"data-state":s.open?"open":"closed",...r,ref:t,onPointerEnter:ke(e.onPointerEnter,Yv(s.onOpen)),onPointerLeave:ke(e.onPointerLeave,Yv(s.onClose)),onFocus:ke(e.onFocus,s.onOpen),onBlur:ke(e.onBlur,s.onClose),onTouchStart:ke(e.onTouchStart,i=>i.preventDefault())})})});RU.displayName=TU;var HM="HoverCardPortal",[jCe,kCe]=DU(HM,{forceMount:void 0}),IU=e=>{const{__scopeHoverCard:t,forceMount:n,children:r,container:s}=e,o=B1(HM,t);return c.jsx(jCe,{scope:t,forceMount:n,children:c.jsx(sr,{present:n||o.open,children:c.jsx(Ud,{asChild:!0,container:s,children:r})})})};IU.displayName=HM;var qv="HoverCardContent",AU=E.forwardRef((e,t)=>{const n=kCe(qv,e.__scopeHoverCard),{forceMount:r=n.forceMount,...s}=e,o=B1(qv,e.__scopeHoverCard);return c.jsx(sr,{present:r||o.open,children:c.jsx(ECe,{"data-state":o.open?"open":"closed",...s,onPointerEnter:ke(e.onPointerEnter,Yv(o.onOpen)),onPointerLeave:ke(e.onPointerLeave,Yv(o.onClose)),ref:t})})});AU.displayName=qv;var ECe=E.forwardRef((e,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:i,...a}=e,l=B1(qv,n),u=z1(n),d=E.useRef(null),f=ft(t,d),[h,p]=E.useState(!1);return E.useEffect(()=>{if(h){const m=document.body;return NN=m.style.userSelect||m.style.webkitUserSelect,m.style.userSelect="none",m.style.webkitUserSelect="none",()=>{m.style.userSelect=NN,m.style.webkitUserSelect=NN}}},[h]),E.useEffect(()=>{if(d.current){const m=()=>{p(!1),l.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var b;((b=document.getSelection())==null?void 0:b.toString())!==""&&(l.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",m),()=>{document.removeEventListener("pointerup",m),l.hasSelectionRef.current=!1,l.isPointerDownOnContentRef.current=!1}}},[l.isPointerDownOnContentRef,l.hasSelectionRef]),E.useEffect(()=>{d.current&&MCe(d.current).forEach(g=>g.setAttribute("tabindex","-1"))}),c.jsx(Hd,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:i,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:ke(o,m=>{m.preventDefault()}),onDismiss:l.onDismiss,children:c.jsx($b,{...u,...a,onPointerDown:ke(a.onPointerDown,m=>{m.currentTarget.contains(m.target)&&p(!0),l.hasSelectionRef.current=!1,l.isPointerDownOnContentRef.current=!0}),ref:f,style:{...a.style,userSelect:h?"text":void 0,WebkitUserSelect:h?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),_Ce="HoverCardArrow",DCe=E.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=z1(n);return c.jsx(Lb,{...s,...r,ref:t})});DCe.displayName=_Ce;function Yv(e){return t=>t.pointerType==="touch"?void 0:e()}function MCe(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;n.nextNode();)t.push(n.currentNode);return t}var TCe=MU,RCe=RU,PU=AU;const Ip=TCe,Ap=RCe,Jd=E.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>c.jsx(PU,{ref:s,align:t,sideOffset:n,className:J("z-50 w-64 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}));Jd.displayName=PU.displayName;const ui=()=>[{value:"VIEWER",label:"Viewer",description:"Can view only"},{value:"EDITOR",label:"Editor",description:"Can view and edit"},{value:"CONTRIBUTOR",label:"Contributor",description:"Can view, edit, and share"},{value:"OWNER",label:"Owner",description:"Full access (view, edit, share, delete)"}];function ICe({currentUser:e,currentShare:t,isSharing:n,onUpdateAccess:r,allUsersToUpdate:s=null,allUsersToRemove:o=!1,isUpdating:i=!1,isRemoving:a=!1}){const l=Wc(),u=ui().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),p=s!==null&&s.newRole!==d,m=o,g=d==="NONE"||!d,b=y=>{switch(y){case"VIEWER":return c.jsx(bc,{className:"h-4 w-4"});case"EDITOR":return c.jsx(a1,{className:"h-4 w-4"});case"CONTRIBUTOR":return c.jsx(Eae,{className:"h-4 w-4"});default:return c.jsx(bc,{className:"h-4 w-4"})}},x=y=>{r(d,y)};return c.jsx("div",{className:"space-y-4",children:c.jsxs(xo,{className:J("pb-6",p&&!m&&!g?"border-orange-300 bg-orange-50":h?"border-green-300 bg-green-50":m||g?"border-destructive bg-destructive/10":""),children:[c.jsxs(vi,{children:[c.jsxs(wi,{className:"flex items-center gap-2 text-base",children:[c.jsx(is,{className:"h-5 w-5"}),"Share with All"," ",l==="allOrgUsers"?"Organization":l==="allTenantUsers"?"Tenant":l==="specificOrgUsers"?"Org":"Tenant"," ","Users",h&&c.jsx(Fe,{variant:"default",className:"ml-2 border-green-400 bg-green-100 text-green-800",children:"Active"}),p&&c.jsx(Fe,{variant:"secondary",className:"ml-2 border-orange-400 bg-orange-100 text-orange-800",children:"Pending Update"}),(m||g)&&c.jsx(Fe,{variant:"destructive",className:"ml-2",children:"No Access"})]}),c.jsx(o8,{children:m||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(Si,{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(Ip,{children:[c.jsx(Ap,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"sm",className:"h-4 w-4 p-0 text-muted-foreground hover:text-foreground",children:c.jsx(xr,{className:"h-3 w-3"})})}),c.jsx(Jd,{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(oe,{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 OU({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,p=(g,b)=>{o(g,b)},m=()=>{i()};return c.jsx(ICe,{currentUser:e,currentShare:f,isSharing:n,isUpdating:r,isRemoving:s,onUpdateAccess:p,onRemoveAccess:m,allUsersToUpdate:h,allUsersToRemove:l})}const ACe=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 Vn(s,t,r)};function UM(e={}){var o,i,a;const{authToken:t,tokenProps:n}=qe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=un({queryKey:["unified-users",e],queryFn:()=>ACe(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 Bh(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=At.DASHBOARD,userType:s,tenantId:o}=e,i=N.useMemo(()=>({search:t,active:!0,...s?{type:s}:{},...s==="tenant"&&o?{tenantId:o}:{}}),[t,s,o]),{users:a,isLoading:l,isError:u}=UM(i),d=Bfe(r,n);return{allUsers:a,isLoadingUsers:l,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function PCe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var L,A;const a=PM(),l=Qb(),{searchQuery:u,setSearchQuery:d,debouncedSearchQuery:f}=$M(),h=_p(),p=Qd(),m=Dp(),g=Wc(),b=OM(),x=qc(),[y,v]=N.useState("specific_users"),w=()=>{if(a==="org")return"organization";if(a==="tenant")return"tenant"},S=()=>{if(a==="tenant"&&l)return l},{allUsers:C,existingShares:j,isLoadingUsers:D}=Bh({debouncedSearchQuery:f,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:w(),tenantId:S()});N.useEffect(()=>{x.setCurrentContext("org-tab"),x.setCurrentMode(y==="all_users"?"allOrgUsers":"specificOrgUsers")},[x,y]);const k=W=>{var Y,K;const U=W;if(v(U),r==null||r(U),x.setCurrentContext("org-tab"),U==="specific_users")x.setCurrentMode("specificOrgUsers");else if(U==="all_users"){x.setCurrentMode("allOrgUsers");const H=(K=(Y=j==null?void 0:j.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:K[0];H&&H.role!==void 0&&x.setOrgWideRole(H.role)}},_=C.filter(W=>W.name.toLowerCase().includes(u.toLowerCase())||W.email.toLowerCase().includes(u.toLowerCase())),M=C.filter(W=>h.some(U=>U.id===W.id)),R=W=>{var H,q;const U=h.some(X=>X.id===W),Y=p.includes(W),K=(q=(H=j==null?void 0:j.shares)==null?void 0:H.specificOrgUsers)==null?void 0:q.some(X=>X.orgUserId===W);U?x.removeSelectedUser(W):Y?x.removeUserFromRemove(W):K||x.addSelectedUser({id:W,role:"VIEWER"})},O=(W,U)=>{x.updateSelectedUserRole(W,U)},T=W=>{x.addUserToRemove(W),x.removeSelectedUser(W)},I=W=>{x.removeUserFromRemove(W)},F=W=>{x.removeUserFromUpdate(W)},z=(W,U)=>{x.setOrgWideRole(U)},B=()=>{x.setOrgWideRole(($==null?void 0:$.role)||"NONE")},$=(A=(L=j==null?void 0:j.shares)==null?void 0:L.orgUsersOnly)==null?void 0:A[0];N.useEffect(()=>{y==="all_users"&&$&&$.role!==void 0&&x.setOrgWideRole($.role)},[y,$,x]);const P=D,V=!1;return n?c.jsxs(c.Fragment,{children:[c.jsx(BM,{shareType:y,onShareTypeChange:k,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:c.jsx(xc,{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(is,{className:"mb-3 h-6 w-6 text-indigo-500"}),disabled:!["POWER_USER","ADMIN","AUTHOR","SUPER_ADMIN"].includes(n.role??"")}]}),y==="specific_users"?c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsx(yv,{value:u,onChange:d}),c.jsx(AB,{selectedUsers:h,selectedUserObjects:M,onRemove:R,onRoleChange:O,getRoleOptions:ui}),c.jsx(PB,{usersToRemove:p,allUsers:_,onRemove:I}),c.jsx(OB,{usersToUpdate:m,allUsers:_,onRemove:F,getRoleOptions:ui}),c.jsx(mU,{existingShares:j,isInitialLoading:P,isSearching:V,resource:e,onShare:()=>{},getRoleOptions:ui,allUsers:_,currentUser:n,handleUserToggle:R,handleUserRoleChange:O,handleRemoveAccess:T,handleUpdateAccess:(W,U,Y)=>{x.addUserToUpdate({id:W,currentRole:U,newRole:Y})}})]}):c.jsx("div",{className:"mt-3",children:c.jsx(OU,{currentUser:n,currentShare:$,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:z,onRemoveAccess:B,allUsersToUpdate:g==="allOrgUsers"&&b!==(($==null?void 0:$.role)||"NONE")?{currentRole:($==null?void 0:$.role)||"NONE",newRole:b}:null,allUsersToRemove:g==="allOrgUsers"&&($==null?void 0:$.role)===void 0})})]}):null}function OCe(e){switch(e){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function FCe(e){switch(e){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function FU({groups:e,existingGroupShares:t,isLoading:n,resource:r,getRoleOptions:s,currentUser:o,handleGroupToggle:i,handleGroupRoleChange:a,handleRemoveAccess:l,handleUpdateAccess:u}){const d=Mp(),f=Tp(),h=Rp(),p=qc(),m=s(o==null?void 0:o.type);return n?c.jsx("div",{className:"flex items-center justify-center py-6",children:c.jsx(On,{className:"h-6 w-6 animate-spin"})}):e.length===0?c.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"No groups available to share with"}):c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{children:"Available Groups"}),c.jsx("div",{className:"max-h-[300px] space-y-2 overflow-y-auto rounded-md border p-3",children:e.map(g=>{const b=t==null?void 0:t.find(j=>j.groupId===g.id),x=d.some(j=>j.id===g.id),y=f.includes(g.id),v=h.find(j=>j.id===g.id),w=!!b&&!y;let C=(b==null?void 0:b.role)||"VIEWER";if(x){const j=d.find(D=>D.id===g.id);C=(j==null?void 0:j.role)||"VIEWER"}else v&&(C=v.newRole);return c.jsxs("div",{className:J("flex items-center justify-between rounded-lg p-2 transition-colors",w&&!y?"border border-green-200 bg-green-50":y?"border border-red-200 bg-red-50":x?"border border-blue-200 bg-blue-50":"hover:bg-muted/50"),children:[c.jsxs("div",{className:"flex items-center space-x-3",children:[c.jsx(dn,{id:`group-${g.id}`,checked:w?!y:x,disabled:!1,onCheckedChange:()=>{w?y?p.removeGroupFromRemove(g.id):l==null||l(g.id):i==null||i(g.id)}}),c.jsxs("label",{htmlFor:`group-${g.id}`,className:"flex cursor-pointer flex-col",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:g.name}),g.type==="ORG_GROUP"?c.jsx(md,{className:"h-3 w-3 text-blue-600"}):c.jsx(is,{className:"h-3 w-3 text-green-600"}),c.jsxs(Fe,{variant:"secondary",className:"text-xs",children:[g.memberCount," members"]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:J("text-xs",FCe(g.type)),children:OCe(g.type)}),g.type==="TENANT_GROUP"&&g.tenantName&&c.jsxs("span",{className:"text-xs text-muted-foreground",children:["• ",g.tenantName]})]}),g.description&&c.jsx("span",{className:"text-xs text-muted-foreground",children:g.description})]})]}),c.jsxs("div",{className:"flex items-center space-x-2",children:[w&&!y?c.jsx(Sd,{currentRole:C,onRoleChange:j=>{b&&j!==b.role&&(u==null||u(g.id,b.role,j))},roleOptions:m,disabled:!1,allowDropdown:!0,className:v?"border-orange-300 bg-orange-100":""}):x&&!w&&c.jsx(Sd,{currentRole:C,onRoleChange:j=>a==null?void 0:a(g.id,j),roleOptions:m,disabled:!1}),w&&!y&&!v&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>l==null?void 0:l(g.id),children:c.jsx(vt,{className:"h-4 w-4"})}),y&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromRemove(g.id),children:"Undo"}),v&&c.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>p.removeGroupFromUpdate(g.id),children:"Cancel"})]})]},g.id)})})]})}function $U({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(md,{className:"h-4 w-4 text-blue-600"}):c.jsx(is,{className:"h-4 w-4 text-green-600"}),c.jsx("span",{className:"text-sm font-medium",children:a.name}),c.jsxs(Fe,{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(Sd,{currentRole:i.role,onRoleChange:l=>r(i.id,l),roleOptions:o}),c.jsx(oe,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>n(i.id),children:c.jsx(vt,{className:"h-3 w-3"})})]})]},i.id):null})})]})}const $Ce=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 Vn(s,t,r)},LCe=async(e,t,n)=>{const r=`${e}/management/v1/groups/${n}/members`;return await Vn(r,t)};function WM(e={}){var o,i,a;const{authToken:t,tokenProps:n}=qe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=un({queryKey:["groups",e],queryFn:()=>$Ce(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 zCe(e){const{authToken:t,tokenProps:n}=qe(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId);return un({queryKey:["group-members",e],queryFn:()=>LCe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r&&!!e,retry:1,staleTime:6e4})}function LU(e,t){const{tokenProps:n}=qe(),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)),WM(r)}function qk(e,[t,n]){return Math.min(n,Math.max(t,e))}var zU=E.forwardRef((e,t)=>{const{children:n,...r}=e,s=E.Children.toArray(n),o=s.find(VCe);if(o){const i=o.props.children,a=s.map(l=>l===o?E.Children.count(i)>1?E.Children.only(null):E.isValidElement(i)?i.props.children:null:l);return c.jsx(Yk,{...r,ref:t,children:E.isValidElement(i)?E.cloneElement(i,void 0,a):null})}return c.jsx(Yk,{...r,ref:t,children:n})});zU.displayName="Slot";var Yk=E.forwardRef((e,t)=>{const{children:n,...r}=e;if(E.isValidElement(n)){const s=UCe(n),o=HCe(r,n.props);return n.type!==E.Fragment&&(o.ref=t?Es(t,s):s),E.cloneElement(n,o)}return E.Children.count(n)>1?E.Children.only(null):null});Yk.displayName="SlotClone";var BCe=({children:e})=>c.jsx(c.Fragment,{children:e});function VCe(e){return E.isValidElement(e)&&e.type===BCe}function HCe(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)=>{o(...a),s(...a)}:s&&(n[r]=s):r==="style"?n[r]={...s,...o}:r==="className"&&(n[r]=[s,o].filter(Boolean).join(" "))}return{...e,...n}}function UCe(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 WCe=[" ","Enter","ArrowUp","ArrowDown"],qCe=[" ","Enter"],Jb="Select",[V1,H1,YCe]=l1(Jb),[Pp]=_r(Jb,[YCe,ya]),U1=ya(),[GCe,Yc]=Pp(Jb),[KCe,ZCe]=Pp(Jb),BU=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:p,form:m}=e,g=U1(t),[b,x]=E.useState(null),[y,v]=E.useState(null),[w,S]=E.useState(!1),C=Vd(u),[j=!1,D]=$r({prop:r,defaultProp:s,onChange:o}),[k,_]=$r({prop:i,defaultProp:a,onChange:l}),M=E.useRef(null),R=b?m||!!b.closest("form"):!0,[O,T]=E.useState(new Set),I=Array.from(O).map(F=>F.props.value).join(";");return c.jsx(lp,{...g,children:c.jsxs(GCe,{required:p,scope:t,trigger:b,onTriggerChange:x,valueNode:y,onValueNodeChange:v,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:nr(),value:k,onValueChange:_,open:j,onOpenChange:D,dir:C,triggerPointerDownPosRef:M,disabled:h,children:[c.jsx(V1.Provider,{scope:t,children:c.jsx(KCe,{scope:e.__scopeSelect,onNativeOptionAdd:E.useCallback(F=>{T(z=>new Set(z).add(F))},[]),onNativeOptionRemove:E.useCallback(F=>{T(z=>{const B=new Set(z);return B.delete(F),B})},[]),children:n})}),R?c.jsxs(hW,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:k,onChange:F=>_(F.target.value),disabled:h,form:m,children:[k===void 0?c.jsx("option",{value:""}):null,Array.from(O)]},I):null]})})};BU.displayName=Jb;var VU="SelectTrigger",HU=E.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=U1(n),i=Yc(VU,n),a=i.disabled||r,l=ft(t,i.onTriggerChange),u=H1(n),d=E.useRef("touch"),[f,h,p]=pW(g=>{const b=u().filter(v=>!v.disabled),x=b.find(v=>v.value===i.value),y=mW(b,g,x);y!==void 0&&i.onValueChange(y.value)}),m=g=>{a||(i.onOpenChange(!0),p()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return c.jsx(cp,{asChild:!0,...o,children:c.jsx(Be.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":fW(i.value)?"":void 0,...s,ref:l,onClick:ke(s.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&m(g)}),onPointerDown:ke(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"&&(m(g),g.preventDefault())}),onKeyDown:ke(s.onKeyDown,g=>{const b=f.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(b&&g.key===" ")&&WCe.includes(g.key)&&(m(),g.preventDefault())})})})});HU.displayName=VU;var UU="SelectValue",WU=E.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:i="",...a}=e,l=Yc(UU,n),{onValueNodeHasChildrenChange:u}=l,d=o!==void 0,f=ft(t,l.onValueNodeChange);return Lr(()=>{u(d)},[u,d]),c.jsx(Be.span,{...a,ref:f,style:{pointerEvents:"none"},children:fW(l.value)?c.jsx(c.Fragment,{children:i}):o})});WU.displayName=UU;var XCe="SelectIcon",qU=E.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return c.jsx(Be.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});qU.displayName=XCe;var QCe="SelectPortal",YU=e=>c.jsx(Ud,{asChild:!0,...e});YU.displayName=QCe;var Td="SelectContent",GU=E.forwardRef((e,t)=>{const n=Yc(Td,e.__scopeSelect),[r,s]=E.useState();if(Lr(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?gc.createPortal(c.jsx(KU,{scope:e.__scopeSelect,children:c.jsx(V1.Slot,{scope:e.__scopeSelect,children:c.jsx("div",{children:e.children})})}),o):null}return c.jsx(ZU,{...e,ref:t})});GU.displayName=Td;var oi=10,[KU,Gc]=Pp(Td),JCe="SelectContentImpl",ZU=E.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:p,sticky:m,hideWhenDetached:g,avoidCollisions:b,...x}=e,y=Yc(Td,n),[v,w]=E.useState(null),[S,C]=E.useState(null),j=ft(t,K=>w(K)),[D,k]=E.useState(null),[_,M]=E.useState(null),R=H1(n),[O,T]=E.useState(!1),I=E.useRef(!1);E.useEffect(()=>{if(v)return zb(v)},[v]),c1();const F=E.useCallback(K=>{const[H,...q]=R().map(G=>G.ref.current),[X]=q.slice(-1),Z=document.activeElement;for(const G of K)if(G===Z||(G==null||G.scrollIntoView({block:"nearest"}),G===H&&S&&(S.scrollTop=0),G===X&&S&&(S.scrollTop=S.scrollHeight),G==null||G.focus(),document.activeElement!==Z))return},[R,S]),z=E.useCallback(()=>F([D,v]),[F,D,v]);E.useEffect(()=>{O&&z()},[O,z]);const{onOpenChange:B,triggerPointerDownPosRef:$}=y;E.useEffect(()=>{if(v){let K={x:0,y:0};const H=X=>{var Z,G;K={x:Math.abs(Math.round(X.pageX)-(((Z=$.current)==null?void 0:Z.x)??0)),y:Math.abs(Math.round(X.pageY)-(((G=$.current)==null?void 0:G.y)??0))}},q=X=>{K.x<=10&&K.y<=10?X.preventDefault():v.contains(X.target)||B(!1),document.removeEventListener("pointermove",H),$.current=null};return $.current!==null&&(document.addEventListener("pointermove",H),document.addEventListener("pointerup",q,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",H),document.removeEventListener("pointerup",q,{capture:!0})}}},[v,B,$]),E.useEffect(()=>{const K=()=>B(!1);return window.addEventListener("blur",K),window.addEventListener("resize",K),()=>{window.removeEventListener("blur",K),window.removeEventListener("resize",K)}},[B]);const[P,V]=pW(K=>{const H=R().filter(Z=>!Z.disabled),q=H.find(Z=>Z.ref.current===document.activeElement),X=mW(H,K,q);X&&setTimeout(()=>X.ref.current.focus())}),L=E.useCallback((K,H,q)=>{const X=!I.current&&!q;(y.value!==void 0&&y.value===H||X)&&(k(K),X&&(I.current=!0))},[y.value]),A=E.useCallback(()=>v==null?void 0:v.focus(),[v]),W=E.useCallback((K,H,q)=>{const X=!I.current&&!q;(y.value!==void 0&&y.value===H||X)&&M(K)},[y.value]),U=r==="popper"?Gk:XU,Y=U===Gk?{side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:b}:{};return c.jsx(KU,{scope:n,content:v,viewport:S,onViewportChange:C,itemRefCallback:L,selectedItem:D,onItemLeave:A,itemTextRefCallback:W,focusSelectedItem:z,selectedItemText:_,position:r,isPositioned:O,searchRef:P,children:c.jsx(dp,{as:zU,allowPinchZoom:!0,children:c.jsx(op,{asChild:!0,trapped:y.open,onMountAutoFocus:K=>{K.preventDefault()},onUnmountAutoFocus:ke(s,K=>{var H;(H=y.trigger)==null||H.focus({preventScroll:!0}),K.preventDefault()}),children:c.jsx(Hd,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:K=>K.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:c.jsx(U,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:K=>K.preventDefault(),...x,...Y,onPlaced:()=>T(!0),ref:j,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:ke(x.onKeyDown,K=>{const H=K.ctrlKey||K.altKey||K.metaKey;if(K.key==="Tab"&&K.preventDefault(),!H&&K.key.length===1&&V(K.key),["ArrowUp","ArrowDown","Home","End"].includes(K.key)){let X=R().filter(Z=>!Z.disabled).map(Z=>Z.ref.current);if(["ArrowUp","End"].includes(K.key)&&(X=X.slice().reverse()),["ArrowUp","ArrowDown"].includes(K.key)){const Z=K.target,G=X.indexOf(Z);X=X.slice(G+1)}setTimeout(()=>F(X)),K.preventDefault()}})})})})})})});ZU.displayName=JCe;var eNe="SelectItemAlignedPosition",XU=E.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=Yc(Td,n),i=Gc(Td,n),[a,l]=E.useState(null),[u,d]=E.useState(null),f=ft(t,j=>d(j)),h=H1(n),p=E.useRef(!1),m=E.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:x,focusSelectedItem:y}=i,v=E.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&u&&g&&b&&x){const j=o.trigger.getBoundingClientRect(),D=u.getBoundingClientRect(),k=o.valueNode.getBoundingClientRect(),_=x.getBoundingClientRect();if(o.dir!=="rtl"){const Z=_.left-D.left,G=k.left-Z,Q=j.left-G,ne=j.width+Q,ae=Math.max(ne,D.width),ie=window.innerWidth-oi,he=qk(G,[oi,Math.max(oi,ie-ae)]);a.style.minWidth=ne+"px",a.style.left=he+"px"}else{const Z=D.right-_.right,G=window.innerWidth-k.right-Z,Q=window.innerWidth-j.right-G,ne=j.width+Q,ae=Math.max(ne,D.width),ie=window.innerWidth-oi,he=qk(G,[oi,Math.max(oi,ie-ae)]);a.style.minWidth=ne+"px",a.style.right=he+"px"}const M=h(),R=window.innerHeight-oi*2,O=g.scrollHeight,T=window.getComputedStyle(u),I=parseInt(T.borderTopWidth,10),F=parseInt(T.paddingTop,10),z=parseInt(T.borderBottomWidth,10),B=parseInt(T.paddingBottom,10),$=I+F+O+B+z,P=Math.min(b.offsetHeight*5,$),V=window.getComputedStyle(g),L=parseInt(V.paddingTop,10),A=parseInt(V.paddingBottom,10),W=j.top+j.height/2-oi,U=R-W,Y=b.offsetHeight/2,K=b.offsetTop+Y,H=I+F+K,q=$-H;if(H<=W){const Z=M.length>0&&b===M[M.length-1].ref.current;a.style.bottom="0px";const G=u.clientHeight-g.offsetTop-g.offsetHeight,Q=Math.max(U,Y+(Z?A:0)+G+z),ne=H+Q;a.style.height=ne+"px"}else{const Z=M.length>0&&b===M[0].ref.current;a.style.top="0px";const Q=Math.max(W,I+g.offsetTop+(Z?L:0)+Y)+q;a.style.height=Q+"px",g.scrollTop=H-W+g.offsetTop}a.style.margin=`${oi}px 0`,a.style.minHeight=P+"px",a.style.maxHeight=R+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[h,o.trigger,o.valueNode,a,u,g,b,x,o.dir,r]);Lr(()=>v(),[v]);const[w,S]=E.useState();Lr(()=>{u&&S(window.getComputedStyle(u).zIndex)},[u]);const C=E.useCallback(j=>{j&&m.current===!0&&(v(),y==null||y(),m.current=!1)},[v,y]);return c.jsx(nNe,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:C,children:c.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:w},children:c.jsx(Be.div,{...s,ref:f,style:{boxSizing:"border-box",maxHeight:"100%",...s.style}})})})});XU.displayName=eNe;var tNe="SelectPopperPosition",Gk=E.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=oi,...o}=e,i=U1(n);return c.jsx($b,{...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)"}})});Gk.displayName=tNe;var[nNe,qM]=Pp(Td,{}),Kk="SelectViewport",QU=E.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Gc(Kk,n),i=qM(Kk,n),a=ft(t,o.onViewportChange),l=E.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(V1.Slot,{scope:n,children:c.jsx(Be.div,{"data-radix-select-viewport":"",role:"presentation",...s,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...s.style},onScroll:ke(s.onScroll,u=>{const d=u.currentTarget,{contentWrapper:f,shouldExpandOnScrollRef:h}=i;if(h!=null&&h.current&&f){const p=Math.abs(l.current-d.scrollTop);if(p>0){const m=window.innerHeight-oi*2,g=parseFloat(f.style.minHeight),b=parseFloat(f.style.height),x=Math.max(g,b);if(x<m){const y=x+p,v=Math.min(m,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})})})]})});QU.displayName=Kk;var JU="SelectGroup",[rNe,sNe]=Pp(JU),eW=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=nr();return c.jsx(rNe,{scope:n,id:s,children:c.jsx(Be.div,{role:"group","aria-labelledby":s,...r,ref:t})})});eW.displayName=JU;var tW="SelectLabel",nW=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=sNe(tW,n);return c.jsx(Be.div,{id:s.id,...r,ref:t})});nW.displayName=tW;var Gv="SelectItem",[oNe,rW]=Pp(Gv),sW=E.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...i}=e,a=Yc(Gv,n),l=Gc(Gv,n),u=a.value===r,[d,f]=E.useState(o??""),[h,p]=E.useState(!1),m=ft(t,y=>{var v;return(v=l.itemRefCallback)==null?void 0:v.call(l,y,r,s)}),g=nr(),b=E.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(oNe,{scope:n,value:r,disabled:s,textId:g,isSelected:u,onItemTextChange:E.useCallback(y=>{f(v=>v||((y==null?void 0:y.textContent)??"").trim())},[]),children:c.jsx(V1.ItemSlot,{scope:n,value:r,disabled:s,textValue:d,children:c.jsx(Be.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:m,onFocus:ke(i.onFocus,()=>p(!0)),onBlur:ke(i.onBlur,()=>p(!1)),onClick:ke(i.onClick,()=>{b.current!=="mouse"&&x()}),onPointerUp:ke(i.onPointerUp,()=>{b.current==="mouse"&&x()}),onPointerDown:ke(i.onPointerDown,y=>{b.current=y.pointerType}),onPointerMove:ke(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:ke(i.onPointerLeave,y=>{var v;y.currentTarget===document.activeElement&&((v=l.onItemLeave)==null||v.call(l))}),onKeyDown:ke(i.onKeyDown,y=>{var w;((w=l.searchRef)==null?void 0:w.current)!==""&&y.key===" "||(qCe.includes(y.key)&&x(),y.key===" "&&y.preventDefault())})})})})});sW.displayName=Gv;var Fm="SelectItemText",oW=E.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,i=Yc(Fm,n),a=Gc(Fm,n),l=rW(Fm,n),u=ZCe(Fm,n),[d,f]=E.useState(null),h=ft(t,x=>f(x),l.onItemTextChange,x=>{var y;return(y=a.itemTextRefCallback)==null?void 0:y.call(a,x,l.value,l.disabled)}),p=d==null?void 0:d.textContent,m=E.useMemo(()=>c.jsx("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:g,onNativeOptionRemove:b}=u;return Lr(()=>(g(m),()=>b(m)),[g,b,m]),c.jsxs(c.Fragment,{children:[c.jsx(Be.span,{id:l.textId,...o,ref:h}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?gc.createPortal(o.children,i.valueNode):null]})});oW.displayName=Fm;var iW="SelectItemIndicator",aW=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return rW(iW,n).isSelected?c.jsx(Be.span,{"aria-hidden":!0,...r,ref:t}):null});aW.displayName=iW;var Zk="SelectScrollUpButton",lW=E.forwardRef((e,t)=>{const n=Gc(Zk,e.__scopeSelect),r=qM(Zk,e.__scopeSelect),[s,o]=E.useState(!1),i=ft(t,r.onScrollButtonChange);return Lr(()=>{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(uW,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});lW.displayName=Zk;var Xk="SelectScrollDownButton",cW=E.forwardRef((e,t)=>{const n=Gc(Xk,e.__scopeSelect),r=qM(Xk,e.__scopeSelect),[s,o]=E.useState(!1),i=ft(t,r.onScrollButtonChange);return Lr(()=>{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(uW,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});cW.displayName=Xk;var uW=E.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Gc("SelectScrollButton",n),i=E.useRef(null),a=H1(n),l=E.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return E.useEffect(()=>()=>l(),[l]),Lr(()=>{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(Be.div,{"aria-hidden":!0,...s,ref:t,style:{flexShrink:0,...s.style},onPointerDown:ke(s.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:ke(s.onPointerMove,()=>{var u;(u=o.onItemLeave)==null||u.call(o),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:ke(s.onPointerLeave,()=>{l()})})}),iNe="SelectSeparator",dW=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c.jsx(Be.div,{"aria-hidden":!0,...r,ref:t})});dW.displayName=iNe;var Qk="SelectArrow",aNe=E.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=U1(n),o=Yc(Qk,n),i=Gc(Qk,n);return o.open&&i.position==="popper"?c.jsx(Lb,{...s,...r,ref:t}):null});aNe.displayName=Qk;function fW(e){return e===""||e===void 0}var hW=E.forwardRef((e,t)=>{const{value:n,...r}=e,s=E.useRef(null),o=ft(t,s),i=j1(n);return E.useEffect(()=>{const a=s.current,l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==n&&d){const f=new Event("change",{bubbles:!0});d.call(a,n),a.dispatchEvent(f)}},[i,n]),c.jsx(RD,{asChild:!0,children:c.jsx("select",{...r,ref:o,defaultValue:n})})});hW.displayName="BubbleSelect";function pW(e){const t=yr(e),n=E.useRef(""),r=E.useRef(0),s=E.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=E.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return E.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function mW(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=lNe(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 lNe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var cNe=BU,gW=HU,uNe=WU,dNe=qU,fNe=YU,bW=GU,hNe=QU,pNe=eW,xW=nW,yW=sW,mNe=oW,gNe=aW,vW=lW,wW=cW,SW=dW;const rt=cNe,CW=pNe,lt=uNe,Je=E.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(gW,{ref:r,className:J("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(dNe,{asChild:!0,children:c.jsx(Ys,{className:"h-4 w-4 opacity-50"})})]}));Je.displayName=gW.displayName;const NW=E.forwardRef(({className:e,...t},n)=>c.jsx(vW,{ref:n,className:J("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Km,{className:"h-4 w-4"})}));NW.displayName=vW.displayName;const jW=E.forwardRef(({className:e,...t},n)=>c.jsx(wW,{ref:n,className:J("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Ys,{className:"h-4 w-4"})}));jW.displayName=wW.displayName;const et=E.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>c.jsx(fNe,{children:c.jsx(va,{children:c.jsxs(bW,{ref:s,className:J("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(NW,{}),c.jsx(hNe,{className:J("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),c.jsx(jW,{})]})})}));et.displayName=bW.displayName;const YM=E.forwardRef(({className:e,...t},n)=>c.jsx(xW,{ref:n,className:J("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));YM.displayName=xW.displayName;const pe=E.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(yW,{ref:r,className:J("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(gNe,{children:c.jsx(Rr,{className:"h-4 w-4"})})}),c.jsx(mNe,{children:t})]}));pe.displayName=yW.displayName;const bNe=E.forwardRef(({className:e,...t},n)=>c.jsx(SW,{ref:n,className:J("-mx-1 my-1 h-px bg-muted",e),...t}));bNe.displayName=SW.displayName;function a5({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var Oe;const{searchQuery:a,debouncedSearchQuery:l,setSearchQuery:u}=$M(),d=_p(),f=Qd(),h=Dp(),p=Mp(),m=Tp(),g=Rp(),b=Wc(),x=L1(),y=FM(),v=Qb(),w=qc(),{data:S,isLoading:C}=K9({enabled:(n==null?void 0:n.type)==="organization"}),{groups:j,isLoading:D}=LU("tenant",(n==null?void 0:n.tenantId)||v),[k,_]=N.useState((n==null?void 0:n.type)==="organization"?"all_tenants":"specific_tenant_users");N.useEffect(()=>{(n==null?void 0:n.type)==="tenant"?(w.setCurrentContext("tenant-dialog"),w.setCurrentMode("specificTenantUsers")):(w.setCurrentContext("tenant-tab"),w.setCurrentMode("allTenants"))},[w,n==null?void 0:n.type]);const M=ue=>{var Ie,ht,xe,se;_(ue);let De;if(ue==="specific_tenant_users"?De="specific_users":ue==="all_tenant_users"||ue==="all_tenants"?De="all_users":ue==="groups"?De="groups":De="specific_users",r==null||r(De),ue==="groups"?(w.setCurrentContext("group-share"),w.setCurrentMode("specificGroups")):(n==null?void 0:n.type)==="tenant"?(w.setCurrentContext("tenant-dialog"),ue==="specific_tenant_users"?w.setCurrentMode("specificTenantUsers"):ue==="all_tenant_users"&&(w.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&w.setSelectedTenant(n.tenantId))):(w.setCurrentContext("tenant-tab"),ue==="specific_tenant_users"?w.setCurrentMode("specificTenantUsers"):ue==="all_tenant_users"?w.setCurrentMode("allTenantUsers"):ue==="all_tenants"&&w.setCurrentMode("allTenants")),ue==="all_tenant_users"){const de=(ht=(Ie=T==null?void 0:T.shares)==null?void 0:Ie.tenantWide)==null?void 0:ht[0];de&&de.role!==void 0&&w.setTenantWideRole(de.role)}else if(ue==="all_tenants"){const de=(se=(xe=T==null?void 0:T.shares)==null?void 0:xe.allTenantsOnly)==null?void 0:se[0];de&&de.role!==void 0&&w.setAllTenantsRole(de.role)}},R=ue=>{w.setSelectedTenant(ue)},{allUsers:O,existingShares:T,isLoadingUsers:I,isErrorLoadingUsers:F,isLoadingShares:z,isErrorLoadingShares:B}=Bh({debouncedSearchQuery:l,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),$=ue=>{var xe,se;const De=d.some(de=>de.id===ue),Ie=f.includes(ue),ht=(se=(xe=T==null?void 0:T.shares)==null?void 0:xe.specificTenantUsers)==null?void 0:se.some(de=>de.tenantUserId===ue);De?w.removeSelectedUser(ue):Ie?w.removeUserFromRemove(ue):ht||w.addSelectedUser({id:ue,role:"VIEWER"})},P=(ue,De)=>{w.updateSelectedUserRole(ue,De)},V=ue=>{w.addUserToRemove(ue),w.removeSelectedUser(ue)},L=ue=>{w.removeUserFromRemove(ue)},A=ue=>{w.removeUserFromUpdate(ue)},W=(ue,De,Ie)=>{w.addUserToUpdate({id:ue,currentRole:De,newRole:Ie})},U=(ue,De)=>{k==="all_tenant_users"?w.setTenantWideRole(De):k==="all_tenants"&&w.setAllTenantsRole(De)},Y=()=>{k==="all_tenant_users"?w.setTenantWideRole("VIEWER"):k==="all_tenants"&&w.setAllTenantsRole("VIEWER")},H=(()=>{var ue,De,Ie,ht;return b==="allTenants"?(De=(ue=T==null?void 0:T.shares)==null?void 0:ue.allTenantsOnly)==null?void 0:De[0]:b==="allTenantUsers"?(ht=(Ie=T==null?void 0:T.shares)==null?void 0:Ie.tenantWide)==null?void 0:ht[0]:null})();N.useEffect(()=>{var ue,De,Ie,ht;if(k==="all_tenant_users"){const xe=(De=(ue=T==null?void 0:T.shares)==null?void 0:ue.tenantWide)==null?void 0:De[0];xe&&xe.role!==void 0&&w.setTenantWideRole(xe.role)}else if(k==="all_tenants"){const xe=(ht=(Ie=T==null?void 0:T.shares)==null?void 0:Ie.allTenantsOnly)==null?void 0:ht[0];xe&&xe.role!==void 0&&w.setAllTenantsRole(xe.role)}},[k,T,w]);const q=O.filter(ue=>d.some(De=>De.id===ue.id)),X=ue=>{const De=p.some(xe=>xe.id===ue),Ie=m.includes(ue),ht=ie==null?void 0:ie.some(xe=>xe.groupId===ue);De?w.removeSelectedGroup(ue):Ie?w.removeGroupFromRemove(ue):ht||w.addSelectedGroup({id:ue,role:"VIEWER"})},Z=(ue,De)=>{w.updateSelectedGroupRole(ue,De)},G=ue=>{w.addGroupToRemove(ue),w.removeSelectedGroup(ue)},Q=(ue,De,Ie)=>{w.addGroupToUpdate({id:ue,currentRole:De,newRole:Ie})},ne=j.filter(ue=>p.some(De=>De.id===ue.id)),ae=N.useMemo(()=>k!=="groups"?[]:j.filter(ue=>ue.type!=="TENANT_GROUP"?!1:ue.name.toLowerCase().includes(a.toLowerCase())||ue.description&&ue.description.toLowerCase().includes(a.toLowerCase())),[j,k,a]),ie=N.useMemo(()=>{var De,Ie;const ue=((De=T==null?void 0:T.shares)==null?void 0:De.specificGroups)||((Ie=T==null?void 0:T.shares)==null?void 0:Ie.groups)||[];return!ue||ue.length===0?[]:ue.filter(ht=>{const xe=j.find(se=>se.id===ht.groupId);return(xe==null?void 0:xe.type)==="TENANT_GROUP"})},[T,j]),he=I||z||k==="groups"&&D,be=F||B,Ce=()=>(n==null?void 0:n.type)==="tenant"||k==="all_tenants"||k==="groups"?!0:v&&(k==="specific_tenant_users"||k==="all_tenant_users");return c.jsxs(c.Fragment,{children:[be&&c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsxs("div",{className:"text-center",children:[c.jsx(gd,{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(oe,{variant:"outline",size:"sm",onClick:()=>window.location.reload(),children:"Retry"})]})}),!be&&n&&c.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[c.jsx(BM,{shareType:k,onShareTypeChange:M,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(is,{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(xc,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:c.jsx(is,{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(XA,{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(Q_,{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(xc,{className:"mb-3 h-6 w-6 text-orange-500"})}]}),(n==null?void 0:n.type)==="organization"&&(k==="specific_tenant_users"||k==="all_tenant_users")&&c.jsxs("div",{className:"mt-4",children:[c.jsx(ce,{className:"mb-1 block text-sm font-medium",children:"Select Tenant"}),c.jsxs(rt,{value:v||"",onValueChange:R,disabled:C,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:C?"Loading tenants...":"Select a tenant..."})}),c.jsx(et,{className:"z-[51]",children:(Oe=S==null?void 0:S.tenants)==null?void 0:Oe.map(ue=>c.jsx(pe,{value:ue.id,children:ue.name},ue.id))})]})]}),Ce()?c.jsx(c.Fragment,{children:k==="specific_tenant_users"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(yv,{value:a,onChange:u}),c.jsx(AB,{selectedUsers:d,selectedUserObjects:q,onRemove:ue=>$(ue),onRoleChange:P,getRoleOptions:ui}),c.jsx(PB,{usersToRemove:f,allUsers:O,onRemove:L}),c.jsx(OB,{usersToUpdate:h,allUsers:O,onRemove:A,getRoleOptions:ui}),c.jsx(mU,{existingShares:T,isInitialLoading:!!he,isSearching:!1,resource:e,onShare:()=>{},getRoleOptions:ui,allUsers:O,currentUser:n,handleUserToggle:$,handleUserRoleChange:P,handleRemoveAccess:V,handleUpdateAccess:W})]}):k==="groups"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(yv,{value:a,onChange:u,placeholder:"Search groups..."}),c.jsx($U,{selectedGroups:p,groupObjects:ne,onRemove:X,onRoleChange:Z,getRoleOptions:ui}),m.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",m.length,")"]}),c.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),g.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",g.length,")"]}),c.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),c.jsx(FU,{groups:ae,existingGroupShares:ie,isLoading:D,resource:e,getRoleOptions:ui,currentUser:n,handleGroupToggle:X,handleGroupRoleChange:Z,handleRemoveAccess:G,handleUpdateAccess:Q})]}):k==="all_tenant_users"||k==="all_tenants"?c.jsx("div",{className:"mt-6",children:c.jsx(OU,{currentUser:n,currentShare:H,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:U,onRemoveAccess:Y,allUsersToUpdate:b==="allTenantUsers"&&((H==null?void 0:H.role)===void 0||x!==H.role)||b==="allTenants"&&((H==null?void 0:H.role)===void 0||y!==H.role)?{currentRole:(H==null?void 0:H.role)||"VIEWER",newRole:b==="allTenantUsers"?x:y}:null,allUsersToRemove:b==="allTenantUsers"&&(H==null?void 0:H.role)===void 0||b==="allTenants"&&(H==null?void 0:H.role)===void 0})}):null}):(n==null?void 0:n.type)==="organization"&&(k==="specific_tenant_users"||k==="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(XA,{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 xNe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var F,z;const{searchQuery:a,setSearchQuery:l}=$M(),u=Mp(),d=Tp(),f=Rp(),h=qc(),[p,m]=N.useState("org_groups"),[g,b]=N.useState(""),{data:x,isLoading:y}=K9({enabled:(n==null?void 0:n.type)==="organization"&&p==="tenant_groups"}),v=Array.isArray(x)?x:(x==null?void 0:x.tenants)||[],w=()=>{if((n==null?void 0:n.type)==="organization")return"organization";if((n==null?void 0:n.type)==="tenant")return"tenant"},{groups:S,isLoading:C}=LU(w(),p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"?g:n==null?void 0:n.tenantId),{existingShares:j}=Bh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t}),D=S.filter(B=>p==="org_groups"&&B.type!=="ORG_GROUP"||p==="tenant_groups"&&B.type!=="TENANT_GROUP"||p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&(!g||B.tenantId&&B.tenantId!==g)?!1:B.name.toLowerCase().includes(a.toLowerCase())||B.description&&B.description.toLowerCase().includes(a.toLowerCase())),k=((F=j==null?void 0:j.shares)==null?void 0:F.specificGroups)||((z=j==null?void 0:j.shares)==null?void 0:z.groups)||[];N.useEffect(()=>{h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},[h]);const _=B=>{const $=B;m($),$==="org_groups"&&b(""),r==null||r($==="org_groups"?"specific_groups":"all_groups"),h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},M=S.filter(B=>u.some($=>$.id===B.id)),R=B=>{const $=u.some(L=>L.id===B),P=d.includes(B),V=k==null?void 0:k.some(L=>L.groupId===B);$?h.removeSelectedGroup(B):P?h.removeGroupFromRemove(B):V||h.addSelectedGroup({id:B,role:"VIEWER"})},O=(B,$)=>{h.updateSelectedGroupRole(B,$)},T=B=>{h.addGroupToRemove(B),h.removeSelectedGroup(B)},I=(B,$,P)=>{h.addGroupToUpdate({id:B,currentRole:$,newRole:P})};return n?c.jsxs(c.Fragment,{children:[c.jsx(BM,{shareType:p,onShareTypeChange:_,currentUser:n,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:c.jsx(md,{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(is,{className:"mb-3 h-6 w-6 text-green-500"})}]}),p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&c.jsxs("div",{className:"mt-3 space-y-2",children:[c.jsx(ce,{children:"Select Tenant"}),c.jsxs(rt,{value:g,onValueChange:b,disabled:y,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:y?"Loading tenants...":"Select a tenant to view its groups"})}),c.jsx(et,{className:"z-[51]",children:v.map(B=>c.jsx(pe,{className:"hover:bg-muted",value:B.id,children:B.name},B.id))})]})]}),c.jsx("div",{className:"mt-3 space-y-2",children:p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&!g?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(yv,{value:a,onChange:l,placeholder:"Search groups..."}),c.jsx($U,{selectedGroups:u,groupObjects:M,onRemove:R,onRoleChange:O,getRoleOptions:ui}),d.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-sm font-medium text-destructive",children:["Groups to Remove (",d.length,")"]}),c.jsx("div",{className:"text-xs text-muted-foreground",children:"These groups will lose access when you save"})]}),f.length>0&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"text-sm font-medium text-orange-600",children:["Groups to Update (",f.length,")"]}),c.jsx("div",{className:"text-xs text-muted-foreground",children:"Role changes will be applied when you save"})]}),c.jsx(FU,{groups:D,existingGroupShares:k,isLoading:C,resource:e,getRoleOptions:ui,currentUser:n,handleGroupToggle:R,handleGroupRoleChange:O,handleRemoveAccess:T,handleUpdateAccess:I})]})})]}):null}const kW=()=>{const e=fU(),t=Wc(),n=_p(),r=Qd(),s=Dp(),o=Mp(),i=Tp(),a=Rp(),l=Qb(),u=OM(),d=FM(),f=L1(),h=hU(),p=N.useMemo(()=>()=>_pe({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]),m=N.useMemo(()=>b=>VB(b),[]),g=N.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:p,validateShareData:m,isCurrentStateValid:g,currentContext:e,currentMode:t,selectedUsers:n,usersToRemove:r,usersToUpdate:s,selectedTenant:l,orgWideRole:u,allTenantsRole:d,tenantWideRole:f}};function l5({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllUsersShare:l,onRemoveAccess:u}){const d=_p(),f=Qd(),h=Dp(),p=Qb(),m=OM(),g=FM(),b=L1(),{buildShareData:x,validateShareData:y,isCurrentStateValid:v}=kW(),w=n||r||s,S=()=>{var _,M,R,O;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 T=d.length+f.length+h.length;return T===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${T} user${T!==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 ${T} user${T!==1?"s":""}`}else if(a==="all_users"){if(!l||l.role===void 0)return"Share with All Users";const T=l.role;return m===T?"Remove Access":"Update Access"}else if(a==="all_tenants"){const T=(M=(_=t==null?void 0:t.shares)==null?void 0:_.allTenantsOnly)==null?void 0:M[0];if(!T||T.role===void 0)return"Share with All Tenants";const I=T.role;return g===I?"Remove Access":"Update Access"}else if(a==="all_tenant_users"){const T=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!T||T.role===void 0)return"Share with All Tenant Users";const I=T.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 T=d.length+f.length+h.length;return T===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${T} user${T!==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 ${T} user${T!==1?"s":""}`}return"Share"},C=()=>w||!e||a==="all_tenant_users"&&!p||a==="specific_tenant_users"&&!p?!0:!v,j=()=>{const _=x();_&&y(_)&&o(_)},D=()=>{var _,M,R,O;if(a==="all_users")if(!l||l.role===void 0){const T=x();T&&y(T)&&o(T)}else{const T=l.role;if(m===T)u==null||u();else{const F=x();if(F&&y(F)){const z={...F,updateAccess:!0};o(z)}}}else if(a==="all_tenants"){const T=(M=(_=t==null?void 0:t.shares)==null?void 0:_.allTenantsOnly)==null?void 0:M[0];if(!T||T.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=T.role;if(g===I)u==null||u();else{const z=x();if(z&&y(z)){const B={...z,updateAccess:!0};o(B)}}}}else if(a==="all_tenant_users"){const T=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!T||T.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=T.role;if(b===I)u==null||u();else{const z=x();if(z&&y(z)){const B={...z,updateAccess:!0};o(B)}}}}},k=()=>{var _,M,R,O;if(a==="all_users"){if(!l||l.role===void 0)return"default";const T=l.role;return m===T?"destructive":"default"}else if(a==="all_tenants"){const T=(M=(_=t==null?void 0:t.shares)==null?void 0:_.allTenantsOnly)==null?void 0:M[0];if(!T||T.role===void 0)return"default";const I=T.role;return g===I?"destructive":"default"}else if(a==="all_tenant_users"){const T=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!T||T.role===void 0)return"default";const I=T.role;return b===I?"destructive":"default"}return"default"};return c.jsxs(Ts,{children:[c.jsxs(oe,{variant:"outline",onClick:i,disabled:w,children:[c.jsx(vt,{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(oe,{onClick:j,disabled:!e||w,variant:"default",children:[w?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Qu,{className:"mr-2 h-4 w-4"}),!w&&S()]})}),(a==="all_users"||a==="all_tenants"||a==="all_tenant_users")&&c.jsxs(oe,{onClick:D,disabled:C(),variant:k(),children:[w?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(is,{className:"mr-2 h-4 w-4"}),!w&&S()]})]})}function yNe({resource:e,isSharing:t,isRemoving:n,isUpdating:r,onShare:s,onClose:o,shareTabType:i,currentAllUsersShare:a}){const l=_p(),u=Qd(),d=Dp(),f=Mp(),h=Tp(),p=Rp();Wc(),fU();const m=L1();Qb();const{buildShareData:g,validateShareData:b,isCurrentStateValid:x}=kW(),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 k=l.length+u.length+d.length;return k===0?"Select users to share with":l.length>0&&u.length>0?`Update access for ${k} user${k!==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 ${k} user${k!==1?"s":""}`}else if(i==="groups"){if(f.length===0&&h.length===0&&p.length===0)return"Select groups to share with";const k=f.length+h.length+p.length;return k===0?"Select groups to share with":f.length>0&&h.length>0?`Update access for ${k} group${k!==1?"s":""}`:h.length>0&&f.length===0&&p.length===0?`Remove access for ${h.length} group${h.length!==1?"s":""}`:f.length>0&&h.length===0&&p.length===0?`Share with ${f.length} group${f.length!==1?"s":""}`:p.length>0&&f.length===0&&h.length===0?`Update access for ${p.length} group${p.length!==1?"s":""}`:`Update access for ${k} group${k!==1?"s":""}`}else if(i==="all_users"){if(!a||a.role==="NONE")return"Share with All Users";const k=a.role;return m===k?"Remove Access":"Update Access"}return"Share"},w=()=>y||!e?!0:!x,S=()=>{const k=g();k&&b(k)&&s(k)},C=()=>{const k=g();k&&b(k)&&s(k)},j=()=>{if(!a||a.role==="NONE"){const k=g();k&&b(k)&&s(k)}else{const k=a.role;if(m===k){const M=g();if(M&&b(M)){const R={...M,removeAccess:!0};s(R)}}else{const M=g();if(M&&b(M)){const R={...M,updateAccess:!0};s(R)}}}},D=()=>!a||a.role==="NONE"?"default":"destructive";return c.jsxs(Ts,{children:[c.jsxs(oe,{variant:"outline",onClick:o,disabled:y,children:[c.jsx(vt,{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(oe,{onClick:S,disabled:!e||y,variant:"default",children:[y?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Qu,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="groups"&&c.jsx(c.Fragment,{children:(f.length>0||h.length>0||p.length>0)&&c.jsxs(oe,{onClick:C,disabled:!e||y,variant:"default",children:[y?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Qu,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="all_users"&&c.jsxs(oe,{onClick:j,disabled:w(),variant:D(),children:[y?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Qu,{className:"mr-2 h-4 w-4"}),!y&&v()]})]})}function vNe({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllGroupsShare:l,onRemoveAccess:u}){const d=Mp(),f=Tp(),h=Rp();hU(),Wc();const p=()=>{o({context:"group-share",mode:"specificGroups",selectedGroups:d,groupsToRemove:f,groupsToUpdate:h})},m=()=>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(oe,{variant:"outline",onClick:i,disabled:b,children:"Cancel"}),c.jsxs(oe,{onClick:p,disabled:!m()||b,children:[b&&c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),g()]})]})]})}function eo(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function Va(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function wNe(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(p=>({scope:"specific_org_user",orgUserId:p.id,role:p.role})));o(h,{onSuccess:()=>{l()}})}if(d&&d.length>0){const h=Va(r,s,d.map(p=>{var g,b;const m=(b=(g=a==null?void 0:a.shares)==null?void 0:g.specificOrgUsers)==null?void 0:b.find(x=>x.orgUserId===p);return{scope:"specific_org_user",orgUserId:p,role:(m==null?void 0:m.role)||"VIEWER"}}));i(h,{onSuccess:()=>{l()}})}f&&f.length>0&&f.forEach(h=>{const p=eo(r,s,[{scope:"specific_org_user",orgUserId:h.id,role:h.newRole}]);o(p,{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 p=Va(r,s,d.map(m=>{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===m);return{scope:"specific_tenant_user",tenantUserId:m,tenantId:h,role:(g==null?void 0:g.role)||"VIEWER"}}));i(p,{onSuccess:()=>{l()}})}if(f&&f.length>0&&f.forEach(p=>{const m=eo(r,s,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.newRole}]);o(m,{onSuccess:()=>{l()}})}),u&&u.length>0){const p=eo(r,s,u.map(m=>({scope:"specific_tenant_user",tenantUserId:m.id,tenantId:h,role:m.role})));o(p,{onSuccess:()=>{l()}})}}break;case"tenant-dialog":if(e.mode==="allTenantUsers")if(e.removeAccess){const u=Va(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(p=>({scope:"specific_tenant_user",tenantUserId:p.id,role:p.role})));o(h,{onSuccess:()=>{l()}})}if(d&&d.length>0){const h=Va(r,s,d.map(p=>{var g,b;const m=(b=(g=a==null?void 0:a.shares)==null?void 0:g.specificTenantUsers)==null?void 0:b.find(x=>x.tenantUserId===p);return{scope:"specific_tenant_user",tenantUserId:p,role:(m==null?void 0:m.role)||"VIEWER"}}));i(h,{onSuccess:()=>{l()}})}f&&f.length>0&&f.forEach(h=>{const p=eo(r,s,[{scope:"specific_tenant_user",tenantUserId:h.id,role:h.newRole}]);o(p,{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(p=>({scope:"group",groupId:p.id,role:p.role})));o(h,{onSuccess:()=>{var p;l(),(p=t.resetGroupSelections)==null||p.call(t),$e.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(d&&d.length>0){const h=Va(r,s,d.map(p=>({scope:"group",groupId:p,role:"VIEWER"})));i(h,{onSuccess:()=>{var p;l(),(p=t.resetGroupSelections)==null||p.call(t),$e.success(`Removed access from ${d.length} group${d.length!==1?"s":""}`)}})}f&&f.length>0&&f.forEach(h=>{const p=eo(r,s,[{scope:"group",groupId:h.id,role:h.newRole}]);o(p,{onSuccess:()=>{var m;l(),(m=t.resetGroupSelections)==null||m.call(t),$e.success("Updated access for group")}})})}break}}function SNe(e,t,n,r){var u,d,f,h,p,m;const{resourceType:s,resourceId:o,removeMutation:i,existingShares:a,resetUserSelections:l}=r;if(o)if(e.length>0){const g=Va(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=Va(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=Va(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=(m=(p=a==null?void 0:a.shares)==null?void 0:p.orgUsersOnly)==null?void 0:m[0];if(x){const y=Va(s,o,[{scope:"org_users_only",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove org-wide access failed:",v)}})}}}}function CNe(e,t,n){const r=qc(),s=Qd(),o=PM(),i=Wc(),{currentUser:a}=Ms(),{existingShares:l}=Bh({debouncedSearchQuery:"",resourceId:e||"",resourceType:At.DASHBOARD,userType:"tenant"}),u=N.useCallback(()=>{r.resetUserSelections()},[r]),d=N.useCallback(()=>{r.resetGroupSelections()},[r]),f=N.useCallback(p=>{if(!e)return;const m={resourceType:At.DASHBOARD,resourceId:e,shareMutation:t,removeMutation:n,existingShares:l,resetUserSelections:u,resetGroupSelections:d};wNe(p,m,a)},[e,t,n,l,u,d,a]),h=N.useCallback(()=>{if(!e)return;const p={resourceType:At.DASHBOARD,resourceId:e,removeMutation:n,existingShares:l,resetUserSelections:u};SNe(s,o||"",i||"",p)},[e,t,n,l,u,d,s,o,i]);return{handleShareSubmit:f,handleRemoveAccess:h}}function EW({resource:e,resourceType:t,onClose:n,onShareSuccess:r,onRemoveSuccess:s}){var O,T,I,F,z,B,$,P;const{currentUser:o}=Ms(),[i,a]=N.useState("specific_users"),[l,u]=N.useState("specific_users"),[d,f]=N.useState("specific_groups"),h=qc(),p=PM(),m=Wc(),g=X9(),b=Q9(),{handleShareSubmit:x,handleRemoveAccess:y}=CNe(e.id,(V,L)=>{g.mutate(V,{...L,onSuccess:()=>{var A;(A=L==null?void 0:L.onSuccess)==null||A.call(L),r==null||r()}})},(V,L)=>{b.mutate(V,{...L,onSuccess:()=>{var A;(A=L==null?void 0:L.onSuccess)==null||A.call(L),s==null||s()}})}),v=g.isPending,w=b.isPending,S=g.isPending,{existingShares:C}=Bh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant"}),{existingShares:j}=Bh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"organization"}),D=(T=(O=C==null?void 0:C.shares)==null?void 0:O.tenantWide)==null?void 0:T[0],k=(F=(I=j==null?void 0:j.shares)==null?void 0:I.orgUsersOnly)==null?void 0:F[0],_=()=>{if(p==="org")return l;switch(m){case"specificTenantUsers":return"specific_tenant_users";case"allTenantUsers":return"all_tenant_users";case"allTenants":return"all_tenants";default:return"specific_tenant_users"}},M=N.useCallback(()=>{h.resetShareState(),n()},[h,n]),R=(o==null?void 0:o.type)==="organization";return c.jsx(ls,{open:!0,onOpenChange:M,children:c.jsxs(Vr,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Qu,{className:"h-5 w-5"}),' Share "',e==null?void 0:e.title,'"']})}),c.jsx(Rs,{children:R?"Share this resource with org users or tenant users.":"Share this resource with other users in your tenant."})]}),R?c.jsxs(cs,{value:p,onValueChange:V=>{const L=V;h.setSelectedTab(L),h.resetUserSelections(),h.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[c.jsxs(Wr,{className:"mb-2 grid w-full grid-cols-3",children:[c.jsx(Ht,{value:"org",children:"Org Users"}),c.jsx(Ht,{value:"tenant",children:"Tenant Users"}),c.jsx(Ht,{value:"groups",children:"Groups"})]}),c.jsx(Gn,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(PCe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:u,isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx(Gn,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(a5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:V=>a(V),isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx(Gn,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(xNe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:f,isSharing:v,isUpdating:S,isRemoving:w})})})]}):c.jsx("div",{className:"mb-4 min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(a5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:V=>a(V),isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx("div",{className:"mt-auto flex-shrink-0",children:R?p==="org"?c.jsx(l5,{resource:e,existingShares:j,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:l,currentAllUsersShare:k,onRemoveAccess:y}):p==="tenant"?c.jsx(l5,{resource:e,existingShares:C,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:_(),currentAllUsersShare:D,onRemoveAccess:y}):c.jsx(vNe,{resource:e,existingShares:j,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:d,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(B=(z=j==null?void 0:j.shares)==null?void 0:z.allOrgGroups)==null?void 0:B[0]:(P=($=C==null?void 0:C.shares)==null?void 0:$.allTenantGroups)==null?void 0:P[0],onRemoveAccess:y}):c.jsx(yNe,{resource:e,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:i,currentAllUsersShare:D,onRemoveAccess:y})})]})})}const Nn=E.forwardRef(({className:e,type:t,...n},r)=>c.jsx("input",{type:t,className:J("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}));Nn.displayName="Input";function _W({open:e,resourceLabel:t,initialTitle:n,initialDescription:r="",onClose:s,onSave:o,isSaving:i=!1}){const[a,l]=N.useState(n),[u,d]=N.useState(r??"");N.useEffect(()=>{e&&(l(n),d(r??""))},[e,n,r]);const f=h=>{h.preventDefault();const p=a.trim();p&&o({title:p,description:u.trim()})};return c.jsx(ls,{open:e,onOpenChange:h=>h?null:s(),children:c.jsx(Vr,{className:"sm:max-w-md",children:c.jsxs("form",{onSubmit:f,className:"space-y-4",children:[c.jsxs(Hr,{children:[c.jsxs(Ur,{children:["Edit ",t]}),c.jsxs(Rs,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{htmlFor:"resource-title",children:"Title"}),c.jsx(Nn,{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(ce,{htmlFor:"resource-description",children:"Description"}),c.jsx(Gd,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),c.jsxs(Ts,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[c.jsx(oe,{type:"button",variant:"outline",onClick:s,disabled:i,children:"Cancel"}),c.jsx(oe,{type:"submit",disabled:i||!a.trim(),children:i?"Saving...":"Save changes"})]})]})})})}function NNe({onDashboardSelect:e}){var K,H;const{authToken:t}=qe(),[n,r]=N.useState(!1),[s,o]=N.useState(!1),[i,a]=N.useState(null),[l,u]=N.useState(!1),[d,f]=N.useState(null),[h,p]=N.useState(null),[m,g]=N.useState(null),{data:b}=I7(),x=((K=b==null?void 0:b.preference)==null?void 0:K.defaultDashboardId)||null,y=Ss(q=>q.actions.selectDashboard),{userContext:v}=Ms(),w=((H=v==null?void 0:v.permissions)==null?void 0:H.canCreateDashboard)??!1,{onCreateSuccess:S}=n7({onDashboardSelect:e}),{resources:C,isLoading:j,isError:D,createResource:k,updateResource:_,deleteResource:M,duplicateResource:R,isCreating:O,isDeleting:T,refetch:I}=t7(()=>{u(!1),f(null)},q=>{r(!1),S(q,I)}),{startUpdating:F,stopUpdating:z,isUpdating:B}=e7(),$=q=>{const X=C.find(Z=>Z.id===q);X&&(y(X),e==null||e(q))},P=q=>{k({title:q.title,description:q.description,isPrivate:!1})},V=q=>{f(q),u(!0)},L=()=>{d&&M(d.id)},A=q=>{p(q),R(q,{onSettled:()=>p(null)})},W=(q,X,Z)=>{var ae;const G=Object.fromEntries(Object.entries(X).filter(([,ie])=>ie!==void 0));if(Object.keys(G).length===0){(ae=Z==null?void 0:Z.onSuccess)==null||ae.call(Z);return}const Q=Object.keys(G),ne=Q.length===1?Q[0]:void 0;F(q,ne),_({resourceId:q,data:G},{onSuccess:()=>{var ie;z(q,ne),(ie=Z==null?void 0:Z.onSuccess)==null||ie.call(Z)},onError:()=>{var ie;z(q,ne),(ie=Z==null?void 0:Z.onError)==null||ie.call(Z)}})},U=q=>{a(q),o(!0)},Y=q=>new Date(q).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return t?j?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(On,{className:"h-8 w-8 animate-spin text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading dashboards..."})]})}):D?c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"text-center",children:[c.jsx(gd,{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(oe,{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"}),C.length>0&&w&&c.jsx("div",{className:"mt-6 flex gap-3",children:c.jsxs(oe,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Create New Dashboard"]})})]}),C.length>0&&c.jsxs("div",{className:"rounded-md bg-orange-500 px-3 py-1 text-sm font-medium text-white",children:[C.length," dashboard",C.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:C.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(T8,{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(oe,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(kr,{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:C.map(q=>c.jsx(_fe,{dashboard:q,isDefault:q.id===x,onView:$,isDeleting:T&&(d==null?void 0:d.id)===q.id,isDuplicating:h===q.id,onEditDetails:g,onDeleteClick:V,onDuplicateDashboard:A,onShareDashboard:U,formatDate:Y},q.id))})]})})}),c.jsx(R7,{open:n,onOpenChange:r,onSubmit:P,isCreating:O}),m&&c.jsx(_W,{open:!!m,resourceLabel:"Dashboard",initialTitle:m.title||"",initialDescription:m.description||"",onClose:()=>g(null),onSave:q=>{W(m.id,q,{onSuccess:()=>{g(null)}})},isSaving:B(m.id)}),c.jsx(Wb,{open:l,onOpenChange:u,children:c.jsxs(mp,{children:[c.jsxs(gp,{children:[c.jsx(xp,{children:"Delete Dashboard?"}),c.jsxs(yp,{children:['Are you sure you want to delete "',d==null?void 0:d.title,'"? This action cannot be undone.']})]}),c.jsxs(bp,{children:[c.jsx(wp,{disabled:T,children:"Cancel"}),c.jsx(vp,{onClick:L,disabled:T,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:T?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete"})]})]})}),i&&s&&c.jsx(EW,{resource:i,resourceType:At.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(gd,{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 sd=pl()(Sre(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})})),DW=e=>sd(t=>t.panels[e]),MW=()=>sd(e=>e.fullscreen),TW=e=>sd(t=>t.panels[e].container??null);function RW(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 jNe(e){const{selectedEntities:t}=e,n=t.map(r=>({...r,qualifiedEntityName:Lf(r)}));return{...e,selectedEntities:n}}const c5={selectedEntities:[]},Ai=pl()(Mb((e,t)=>({currentAIContext:c5,activeAssistantType:null,reasoningEffort:"low",showReasoning:!1,messageQueues:{dashboard:[],editor:[]},fileAttachments:{dashboard:[],editor:[]},uploadProgress:new Map,actions:{setCurrentAIContext:n=>{e(r=>{r.currentAIContext=jNe(n)})},setActiveAssistantType:n=>{e(r=>{r.activeAssistantType=n})},updateSelectedEntities:n=>{e(r=>{r.currentAIContext.selectedEntities=n})},clearAIContext:()=>{e(n=>{n.currentAIContext=c5})},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]}}))),Op=()=>Ai(e=>e.currentAIContext),GM=()=>Ai(e=>e.activeAssistantType),kNe=()=>Ai(e=>e.reasoningEffort),ENe=()=>Ai(e=>e.showReasoning),W1=()=>Ai(e=>e.actions),IW=e=>Ai(t=>t.messageQueues[e]),Fp=()=>Ai(e=>({queueMessage:e.actions.queueMessage,dequeueMessage:e.actions.dequeueMessage,removeFromQueue:e.actions.removeFromQueue,clearQueue:e.actions.clearQueue})),KM=e=>Ai(t=>t.fileAttachments[e]),ZM=()=>Ai(e=>({addFileAttachment:e.actions.addFileAttachment,removeFileAttachment:e.actions.removeFileAttachment,clearFileAttachments:e.actions.clearFileAttachments,updateUploadProgress:e.actions.updateUploadProgress,getFileAttachments:e.actions.getFileAttachments}));function AW(){const{tokenProps:e,id:t}=qe(),n=Ss(s=>s.selectedDashboard);return Ss(s=>s.showHub)?!1:!!(n!=null&&n.id||t||e!=null&&e.dashboard_id)}function XM({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:p,onFilterValuesChange:m,selectedSheetId:g,eventHandlers:b,type:x="dashboard",cardId:y,dashboardId:v,...w}){const{placeholders:S,tokenProps:C,id:j}=qe();Ss(O=>O.selectedDashboard);const D=ee(O=>O.themeStyle),k=ee(O=>O.isSessionExpired),{isLoading:_,isError:M}=oae({customStyle:t,currentTheme:u,onSave:n,onEvent:r,defaultFilterValues:p,onFilterValuesChange:m,selectedSheetId:g}),R=AW();return l&&!R&&!_?c.jsx(NNe,{}):_||!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(Ho,{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"})):k?(r==null||r({type:"error",message:"Session Expired"}),S!=null&&S.SessionExpired?c.jsx("div",{className:"flex h-full w-full items-center justify-center",children:c.jsx("div",{children:S.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(wi,{children:"Session Expired"}),c.jsx("p",{className:"text-muted-foreground",children:"Please refresh your page to continue"})]})})):c.jsx("div",{className:J("isolate flex grow flex-col",{"h-full":x==="visual"},D==null?void 0:D.dashboardPanel,e),style:{},"data-role":"semaphor-container",...w})}var PW={exports:{}},ex={},Jk={exports:{}};(function(e,t){(function(n,r){r(t)})(Ua,function(n){function r(H){return function(X,Z,G,Q,ne,ae,ie){return H(X,Z,ie)}}function s(H){return function(X,Z,G,Q){if(!X||!Z||typeof X!="object"||typeof Z!="object")return H(X,Z,G,Q);var ne=Q.get(X),ae=Q.get(Z);if(ne&&ae)return ne===Z&&ae===X;Q.set(X,Z),Q.set(Z,X);var ie=H(X,Z,G,Q);return Q.delete(X),Q.delete(Z),ie}}function o(H,q){var X={};for(var Z in H)X[Z]=H[Z];for(var Z in q)X[Z]=q[Z];return X}function i(H){return H.constructor===Object||H.constructor==null}function a(H){return typeof H.then=="function"}function l(H,q){return H===q||H!==H&&q!==q}var u="[object Arguments]",d="[object Boolean]",f="[object Date]",h="[object RegExp]",p="[object Map]",m="[object Number]",g="[object Object]",b="[object Set]",x="[object String]",y=Object.prototype.toString;function v(H){var q=H.areArraysEqual,X=H.areDatesEqual,Z=H.areMapsEqual,G=H.areObjectsEqual,Q=H.areRegExpsEqual,ne=H.areSetsEqual,ae=H.createIsNestedEqual,ie=ae(he);function he(be,Ce,Oe){if(be===Ce)return!0;if(!be||!Ce||typeof be!="object"||typeof Ce!="object")return be!==be&&Ce!==Ce;if(i(be)&&i(Ce))return G(be,Ce,ie,Oe);var ue=Array.isArray(be),De=Array.isArray(Ce);if(ue||De)return ue===De&&q(be,Ce,ie,Oe);var Ie=y.call(be);return Ie!==y.call(Ce)?!1:Ie===f?X(be,Ce,ie,Oe):Ie===h?Q(be,Ce,ie,Oe):Ie===p?Z(be,Ce,ie,Oe):Ie===b?ne(be,Ce,ie,Oe):Ie===g||Ie===u?a(be)||a(Ce)?!1:G(be,Ce,ie,Oe):Ie===d||Ie===m||Ie===x?l(be.valueOf(),Ce.valueOf()):!1}return he}function w(H,q,X,Z){var G=H.length;if(q.length!==G)return!1;for(;G-- >0;)if(!X(H[G],q[G],G,G,H,q,Z))return!1;return!0}var S=s(w);function C(H,q){return l(H.valueOf(),q.valueOf())}function j(H,q,X,Z){var G=H.size===q.size;if(!G)return!1;if(!H.size)return!0;var Q={},ne=0;return H.forEach(function(ae,ie){if(G){var he=!1,be=0;q.forEach(function(Ce,Oe){!he&&!Q[be]&&(he=X(ie,Oe,ne,be,H,q,Z)&&X(ae,Ce,ie,Oe,H,q,Z))&&(Q[be]=!0),be++}),ne++,G=he}}),G}var D=s(j),k="_owner",_=Object.prototype.hasOwnProperty;function M(H,q,X,Z){var G=Object.keys(H),Q=G.length;if(Object.keys(q).length!==Q)return!1;for(var ne;Q-- >0;){if(ne=G[Q],ne===k){var ae=!!H.$$typeof,ie=!!q.$$typeof;if((ae||ie)&&ae!==ie)return!1}if(!_.call(q,ne)||!X(H[ne],q[ne],ne,ne,H,q,Z))return!1}return!0}var R=s(M);function O(H,q){return H.source===q.source&&H.flags===q.flags}function T(H,q,X,Z){var G=H.size===q.size;if(!G)return!1;if(!H.size)return!0;var Q={};return H.forEach(function(ne,ae){if(G){var ie=!1,he=0;q.forEach(function(be,Ce){!ie&&!Q[he]&&(ie=X(ne,be,ae,Ce,H,q,Z))&&(Q[he]=!0),he++}),G=ie}}),G}var I=s(T),F=Object.freeze({areArraysEqual:w,areDatesEqual:C,areMapsEqual:j,areObjectsEqual:M,areRegExpsEqual:O,areSetsEqual:T,createIsNestedEqual:r}),z=Object.freeze({areArraysEqual:S,areDatesEqual:C,areMapsEqual:D,areObjectsEqual:R,areRegExpsEqual:O,areSetsEqual:I,createIsNestedEqual:r}),B=v(F);function $(H,q){return B(H,q,void 0)}var P=v(o(F,{createIsNestedEqual:function(){return l}}));function V(H,q){return P(H,q,void 0)}var L=v(z);function A(H,q){return L(H,q,new WeakMap)}var W=v(o(z,{createIsNestedEqual:function(){return l}}));function U(H,q){return W(H,q,new WeakMap)}function Y(H){return v(o(F,H(F)))}function K(H){var q=v(o(z,H(z)));return function(X,Z,G){return G===void 0&&(G=new WeakMap),q(X,Z,G)}}n.circularDeepEqual=A,n.circularShallowEqual=U,n.createCustomCircularEqual=K,n.createCustomEqual=Y,n.deepEqual=$,n.sameValueZeroEqual=l,n.shallowEqual=V,Object.defineProperty(n,"__esModule",{value:!0})})})(Jk,Jk.exports);var QM=Jk.exports;const JM=v_(ane);var Pt={},_Ne=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(Pt,"__esModule",{value:!0});Pt.bottom=eT;Pt.childrenEqual=RNe;Pt.cloneLayout=OW;Pt.cloneLayoutItem=od;Pt.collides=q1;Pt.compact=$W;Pt.compactItem=LW;Pt.compactType=WNe;Pt.correctBounds=zW;Pt.fastPositionEqual=INe;Pt.fastRGLPropsEqual=void 0;Pt.getAllCollisions=BW;Pt.getFirstCollision=Pu;Pt.getLayoutItem=tT;Pt.getStatics=nT;Pt.modifyLayout=FW;Pt.moveElement=Lm;Pt.moveElementAwayFromCollision=tE;Pt.noop=void 0;Pt.perc=PNe;Pt.resizeItemInDirection=BNe;Pt.setTopLeft=HNe;Pt.setTransform=VNe;Pt.sortLayoutItems=lT;Pt.sortLayoutItemsByColRow=qW;Pt.sortLayoutItemsByRowCol=WW;Pt.synchronizeLayoutWithChildren=UNe;Pt.validateLayout=YW;Pt.withLayoutItem=TNe;var u5=QM,$m=DNe(N);function DNe(e){return e&&e.__esModule?e:{default:e}}const MNe=process.env.NODE_ENV==="production";function eT(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 OW(e){const t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=od(e[n]);return t}function FW(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 TNe(e,t,n){let r=tT(e,t);return r?(r=n(od(r)),e=FW(e,r),[e,r]):[e,null]}function od(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 RNe(e,t){return(0,u5.deepEqual)($m.default.Children.map(e,n=>n==null?void 0:n.key),$m.default.Children.map(t,n=>n==null?void 0:n.key))&&(0,u5.deepEqual)($m.default.Children.map(e,n=>n==null?void 0:n.props["data-grid"]),$m.default.Children.map(t,n=>n==null?void 0:n.props["data-grid"]))}Pt.fastRGLPropsEqual=_Ne;function INe(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function q1(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 $W(e,t,n,r){const s=nT(e),o=lT(e,t),i=Array(e.length);for(let a=0,l=o.length;a<l;a++){let u=od(o[a]);u.static||(u=LW(s,u,t,n,o,r),s.push(u)),i[e.indexOf(o[a])]=u,u.moved=!1}return i}const ANe={x:"w",y:"h"};function eE(e,t,n,r){const s=ANe[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;q1(t,a)&&eE(e,a,n+t[s],r)}}t[r]=n}function LW(e,t,n,r,s,o){const i=n==="vertical",a=n==="horizontal";if(i)for(t.y=Math.min(eT(e),t.y);t.y>0&&!Pu(e,t);)t.y--;else if(a)for(;t.x>0&&!Pu(e,t);)t.x--;let l;for(;(l=Pu(e,t))&&!(n===null&&o);)if(a?eE(s,t,l.x+l.w,"x"):eE(s,t,l.y+l.h,"y"),a&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!Pu(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function zW(e,t){const n=nT(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(;Pu(n,o);)o.y++}return e}function tT(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function Pu(e,t){for(let n=0,r=e.length;n<r;n++)if(q1(e[n],t))return e[n]}function BW(e,t){return e.filter(n=>q1(n,t))}function nT(e){return e.filter(t=>t.static)}function Lm(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=lT(e,i);(i==="vertical"&&typeof r=="number"?d>=r:i==="horizontal"&&typeof n=="number"?u>=n:!1)&&(f=f.reverse());const p=BW(f,t),m=p.length>0;if(m&&l)return OW(e);if(m&&o)return`${t.i}`,t.x=u,t.y=d,t.moved=!1,e;for(let g=0,b=p.length;g<b;g++){const x=p[g];`${t.i}${t.x}${t.y}${x.i}${x.x}${x.y}`,!x.moved&&(x.static?e=tE(e,x,t,s,i):e=tE(e,t,x,s,i))}return e}function tE(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=Pu(e,f),p=h&&h.y+h.h>t.y,m=h&&t.x+t.w>h.x;if(h){if(p&&a)return Lm(e,n,void 0,t.y+1,r,l,s);if(p&&s==null)return t.y=n.y,n.y=n.y+n.h,e;if(m&&i)return Lm(e,t,n.x,void 0,r,l,s)}else return`${n.i}${f.x}${f.y}`,Lm(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:Lm(e,n,i?n.x+1:void 0,a?n.y+1:void 0,r,l,s)}function PNe(e){return e*100+"%"}const VW=(e,t,n,r)=>e+n>r?t:n,HW=(e,t,n)=>e<0?t:n,UW=e=>Math.max(0,e),rT=e=>Math.max(0,e),sT=(e,t,n)=>{let{left:r,height:s,width:o}=t;const i=e.top-(s-e.height);return{left:r,width:o,height:HW(i,e.height,s),top:rT(i)}},oT=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{top:r,height:o,width:VW(e.left,e.width,i,n),left:UW(s)}},iT=(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:VW(e.left,e.width,o,n),top:rT(r),left:UW(i)}},aT=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{width:i,left:s,height:HW(r,e.height,o),top:rT(r)}},ONe=function(){return sT(arguments.length<=0?void 0:arguments[0],oT(...arguments))},FNe=function(){return sT(arguments.length<=0?void 0:arguments[0],iT(...arguments))},$Ne=function(){return aT(arguments.length<=0?void 0:arguments[0],oT(...arguments))},LNe=function(){return aT(arguments.length<=0?void 0:arguments[0],iT(...arguments))},zNe={n:sT,ne:ONe,e:oT,se:$Ne,s:aT,sw:LNe,w:iT,nw:FNe};function BNe(e,t,n,r){const s=zNe[e];return s?s(t,{...t,...n},r):n}function VNe(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 HNe(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 lT(e,t){return t==="horizontal"?qW(e):t==="vertical"?WW(e):e}function WW(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 qW(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 UNe(e,t,n,r,s){e=e||[];const o=[];$m.default.Children.forEach(t,a=>{if((a==null?void 0:a.key)==null)return;const l=tT(e,String(a.key)),u=a.props["data-grid"];l&&u==null?o.push(od(l)):u?(MNe||YW([u],"ReactGridLayout.children"),o.push(od({...u,i:a.key}))):o.push(od({w:1,h:1,x:0,y:eT(o),i:String(a.key)}))});const i=zW(o,{cols:n});return s?i:$W(i,r,n)}function YW(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 WNe(e){const{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}const qNe=()=>{};Pt.noop=qNe;var wa={};Object.defineProperty(wa,"__esModule",{value:!0});wa.calcGridColWidth=Y1;wa.calcGridItemPosition=YNe;wa.calcGridItemWHPx=nE;wa.calcWH=KNe;wa.calcXY=GNe;wa.clamp=Ou;function Y1(e){const{margin:t,containerPadding:n,containerWidth:r,cols:s}=e;return(r-t[0]*(s-1)-n[0]*2)/s}function nE(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function YNe(e,t,n,r,s,o){const{margin:i,containerPadding:a,rowHeight:l}=e,u=Y1(e),d={};return o&&o.resizing?(d.width=Math.round(o.resizing.width),d.height=Math.round(o.resizing.height)):(d.width=nE(r,u,i[0]),d.height=nE(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 GNe(e,t,n,r,s){const{margin:o,containerPadding:i,cols:a,rowHeight:l,maxRows:u}=e,d=Y1(e);let f=Math.round((n-i[0])/(d+o[0])),h=Math.round((t-i[1])/(l+o[1]));return f=Ou(f,0,a-r),h=Ou(h,0,u-s),{x:f,y:h}}function KNe(e,t,n,r,s,o){const{margin:i,maxRows:a,cols:l,rowHeight:u}=e,d=Y1(e);let f=Math.round((t+i[0])/(d+i[0])),h=Math.round((n+i[1])/(u+i[1])),p=Ou(f,0,l-r),m=Ou(h,0,a-s);return["sw","w","nw"].indexOf(o)!==-1&&(p=Ou(f,0,l)),["nw","n","ne"].indexOf(o)!==-1&&(m=Ou(h,0,a)),{w:p,h:m}}function Ou(e,t,n){return Math.max(Math.min(e,n),t)}var G1={},rE={exports:{}},P0={exports:{}},nn={};/** @license React v16.13.1
|
|
764
764
|
* react-is.production.min.js
|
|
765
765
|
*
|
|
766
766
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
@@ -1063,7 +1063,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
1063
1063
|
|
|
1064
1064
|
`)},flush(e){e.enqueue(`data: [DONE]
|
|
1065
1065
|
|
|
1066
|
-
`)}})}});var wXe=pZe(()=>WJ(Ar([Wn({type:ut("text-start"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("text-delta"),id:Le(),delta:Le(),providerMetadata:ir.optional()}),Wn({type:ut("text-end"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("error"),errorText:Le()}),Wn({type:ut("tool-input-start"),toolCallId:Le(),toolName:Le(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-delta"),toolCallId:Le(),inputTextDelta:Le()}),Wn({type:ut("tool-input-available"),toolCallId:Le(),toolName:Le(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-error"),toolCallId:Le(),toolName:Le(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional(),errorText:Le()}),Wn({type:ut("tool-output-available"),toolCallId:Le(),output:co(),providerExecuted:Sr().optional(),dynamic:Sr().optional(),preliminary:Sr().optional()}),Wn({type:ut("tool-output-error"),toolCallId:Le(),errorText:Le(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("reasoning-start"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-delta"),id:Le(),delta:Le(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-end"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("source-url"),sourceId:Le(),url:Le(),title:Le().optional(),providerMetadata:ir.optional()}),Wn({type:ut("source-document"),sourceId:Le(),mediaType:Le(),title:Le(),filename:Le().optional(),providerMetadata:ir.optional()}),Wn({type:ut("file"),url:Le(),mediaType:Le(),providerMetadata:ir.optional()}),Wn({type:zJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Le().optional(),data:co(),transient:Sr().optional()}),Wn({type:ut("start-step")}),Wn({type:ut("finish-step")}),Wn({type:ut("start"),messageId:Le().optional(),messageMetadata:co().optional()}),Wn({type:ut("finish"),messageMetadata:co().optional()}),Wn({type:ut("abort")}),Wn({type:ut("message-metadata"),messageMetadata:co()})])));function SXe(e){return e.type.startsWith("data-")}function JJ(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]=JJ(o,s):n[r]=s}return n}function CXe(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 eee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ow({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ow({text:CXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Uy(e){return e.type.startsWith("tool-")}function NXe(e){return e.type==="dynamic-tool"}function c_(e){return Uy(e)||NXe(e)}function vL(e){return e.type.split("-").slice(1).join("-")}function jXe({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 kXe({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,p,m;function g(w){const C=u.message.parts.filter(Uy).find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(w){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(w){var S;const C=u.message.parts.find(k=>Uy(k)&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=j.rawInput,D.preliminary=j.preliminary,D.providerExecuted=(S=j.providerExecuted)!=null?S:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var S;const C=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.toolName=w.toolName,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=(S=j.rawInput)!=null?S:D.rawInput,D.preliminary=j.preliminary,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function v(w){if(w!=null){const S=u.message.metadata!=null?JJ(u.message.metadata,w):w;t!=null&&await mL({value:S,schema:t}),u.message.metadata=S}}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=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m: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(Uy);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}):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:S}=await eee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,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,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:vL(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})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:vL(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}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":{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(SXe(a)){(n==null?void 0:n[a.type])!=null&&await mL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?u.message.parts.find(C=>w.type===C.type&&w.id===C.id):void 0;S!=null?S.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function EXe({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()}}Ox({prefix:"aitxt",size:24});Ox({prefix:"aiobj",size:24});var _Xe=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()})}};Ox({prefix:"aiobj",size:24});var DXe={};dXe(DXe,{object:()=>TXe,text:()=>MXe});var MXe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),TXe=({schema:e})=>{const t=cXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await eee(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 Ow({text:n});if(!s.success)throw new xL({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 EI({value:s.value,schema:t});if(!o.success)throw new xL({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}}},RXe=Hf({name:Le(),version:Le()}),DI=Hf({_meta:mr(Wt({}).loose())}),wb=DI,IXe=Wt({method:Le(),params:mr(DI)}),AXe=Hf({experimental:mr(Wt({}).loose()),logging:mr(Wt({}).loose()),prompts:mr(Hf({listChanged:mr(Sr())})),resources:mr(Hf({subscribe:mr(Sr()),listChanged:mr(Sr())})),tools:mr(Hf({listChanged:mr(Sr())}))});wb.extend({protocolVersion:Le(),capabilities:AXe,serverInfo:RXe,instructions:mr(Le())});var PXe=wb.extend({nextCursor:mr(Le())}),OXe=Wt({name:Le(),description:mr(Le()),inputSchema:Wt({type:ut("object"),properties:mr(Wt({}).loose())}).loose()}).loose();PXe.extend({tools:nu(OXe)});var FXe=Wt({type:ut("text"),text:Le()}).loose(),$Xe=Wt({type:ut("image"),data:AJ(),mimeType:Le()}).loose(),tee=Wt({uri:Le(),mimeType:mr(Le())}).loose(),LXe=tee.extend({text:Le()}),zXe=tee.extend({blob:AJ()}),BXe=Wt({type:ut("resource"),resource:Ar([LXe,zXe])}).loose();wb.extend({content:nu(Ar([FXe,$Xe,BXe])),isError:Sr().default(!1).optional()}).or(wb.extend({toolResult:co()}));var nC="2.0",VXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()])}).merge(IXe).strict(),HXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()]),result:wb}).strict(),UXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()]),error:Wt({code:yb().int(),message:Le(),data:mr(co())})}).strict(),WXe=Wt({jsonrpc:ut(nC)}).merge(Wt({method:Le(),params:mr(DI)})).strict();Ar([VXe,WXe,HXe,UXe]);async function qXe(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 YXe=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 kf(this.body),l=await kf(this.headers),u=await kf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},p=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:pL({"Content-Type":"application/json",...h},`ai-sdk/${yL}`,hL()),body:JSON.stringify(p),credentials:m,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await kf(this.body),a=await kf(this.headers),l=await kf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,m=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:pL(f,`ai-sdk/${yL}`,hL()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},MI=class extends YXe{constructor(e={}){super(e)}processResponseStream(e){return bZe({stream:e,schema:wXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},GXe=class{constructor({generateId:e=oZe,id:t=e(),transport:n=new MI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new _Xe,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await qXe(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:(m=x.role)!=null?m:"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 p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:p,output:m,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=>c_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>c_(w)&&w.toolCallId===p?{...w,state:f,output:m,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.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;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:jXe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let p;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}p=g}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await EXe({stream:kXe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function KXe({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(c_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function ZXe(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 XXe=ZXe;const QXe=$c(XXe);var nee=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(nee(e,t,"read from private field"),n?n.call(e):t.get(e)),zi=(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)},Ol=(e,t,n,r)=>(nee(e,t,"write to private field"),t.set(e,n),n);function JXe(e,t){return t!=null?QXe(e,t):e}var jo,Wy,qy,Wm,qm,Ym,Rf,u_,d_,eQe=class{constructor(e=[]){zi(this,jo,void 0),zi(this,Wy,"ready"),zi(this,qy,void 0),zi(this,Wm,new Set),zi(this,qm,new Set),zi(this,Ym,new Set),this.pushMessage=t=>{Ol(this,jo,Tn(this,jo).concat(t)),Tn(this,Rf).call(this)},this.popMessage=()=>{Ol(this,jo,Tn(this,jo).slice(0,-1)),Tn(this,Rf).call(this)},this.replaceMessage=(t,n)=>{Ol(this,jo,[...Tn(this,jo).slice(0,t),this.snapshot(n),...Tn(this,jo).slice(t+1)]),Tn(this,Rf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?JXe(t,n):t;return Tn(this,Wm).add(r),()=>{Tn(this,Wm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,qm).add(t),()=>{Tn(this,qm).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Ym).add(t),()=>{Tn(this,Ym).delete(t)}),zi(this,Rf,()=>{Tn(this,Wm).forEach(t=>t())}),zi(this,u_,()=>{Tn(this,qm).forEach(t=>t())}),zi(this,d_,()=>{Tn(this,Ym).forEach(t=>t())}),Ol(this,jo,e)}get status(){return Tn(this,Wy)}set status(e){Ol(this,Wy,e),Tn(this,u_).call(this)}get error(){return Tn(this,qy)}set error(e){Ol(this,qy,e),Tn(this,d_).call(this)}get messages(){return Tn(this,jo)}set messages(e){Ol(this,jo,[...e]),Tn(this,Rf).call(this)}};jo=new WeakMap;Wy=new WeakMap;qy=new WeakMap;Wm=new WeakMap;qm=new WeakMap;Ym=new WeakMap;Rf=new WeakMap;u_=new WeakMap;d_=new WeakMap;var If,wL=class extends GXe{constructor({messages:e,...t}){const n=new eQe(e);super({...t,state:n}),zi(this,If,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,If)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,If)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,If)["~registerErrorCallback"](r),Ol(this,If,n)}};If=new WeakMap;function ree({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new wL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new wL(n));const o="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=N.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=N.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return N.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.addToolResult}}function tQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function nQe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function rQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function sQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function see(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:sQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function oee(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 oQe(){var b;const{authToken:e,tokenProps:t}=qe(),n=ee(x=>x.dashboard.aiScopeTables),r=(b=Qw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=ree({transport:new MI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Ai.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:RW(x)}})}),onToolCall:p,sendAutomaticallyWhen:KXe,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 p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:see(n||[])}}),x.toolName==="getDashboardContext"){const y=ee.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=oee(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function iee(){var u;const{authToken:e,tokenProps:t}=qe(),n=(u=Qw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=un({queryKey:["assistant-profile",n],queryFn:()=>Vn(`${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 aee({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(S8,{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(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function Fw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(iD,{className:r});case"view":return c.jsx(bc,{className:r});case"materialized view":return c.jsx(mae,{className:r});case"model":return c.jsx(o1,{className:r});case"file":return c.jsx(Ni,{className:r});case"dataset":return c.jsx(rl,{className:r});case"upload":return c.jsx(uD,{className:r});case"url":return c.jsx(R8,{className:r});default:return c.jsx(s1,{className:r})}}const lee=E.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(ba,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(ds.Input,{ref:n,className:J("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})]}));lee.displayName=ds.Input.displayName;const my=e=>e.label||(e==null?void 0:e.name),SL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function iQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=qe(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=N.useState(""),[m,g]=N.useState(""),b=s.filter(C=>{if(!h)return!0;const j=my(C).toLowerCase(),D=SL(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||D.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(my(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>my(j)===m);C&&(o.some(D=>"id"in C&&"id"in D?C.id===D.id:C.name===D.name&&C.connectionId===D.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),w=o.length===s.length,S=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(PS,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(lee,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(kr,{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(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),l==null||l()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(OS,{className:"min-h-60",children:[c.jsx(FS,{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(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx($S,{children:b.map((C,j)=>{const D=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,_=my(C);return c.jsxs(LS,{value:_,onSelect:()=>{D?n==null||n(C):t(C)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:J("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:Fw(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:_}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:SL(C)})]}),D&&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(Rr,{className:"h-3 w-3 text-background"})})]},k)})})]})]})})}const f_=e=>e.name||e.name,aQe=e=>{const t=f_(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 lQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=N.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(Yn,{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(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{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:[Fw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:f_(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(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-w-xs",children:aQe(d)})]},h)}),u&&c.jsxs(bn,{open:s,onOpenChange:o,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(gae,{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(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{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:Fw(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:f_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{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(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function cee(e){return e.type==="dataset"&&e.label||e.name}function cQe(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 uQe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ce,{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(Fe,{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,"]"]}),cee(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(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function dQe(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;Ee(l=>l.selectedConnectionId),Ee(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}=un({queryKey:["semantic-domains"],queryFn:()=>Vn(`${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 fQe(e,t){const{tokenProps:n}=qe(),r=ee(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=un({queryKey:["datasets",e],queryFn:()=>Vn(`${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 hQe(e){var g,b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{connections:r}=Ii(e),s=Ee(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:p}=un({queryKey:["databases",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(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:m||[],refetch:p,label:l}}function pQe(e){var g;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=Ii(e),s=Ee(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ee(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:p}=un({queryKey:["schemas",s,o],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function uee(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=Ii(e),s=Ee(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.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}=un({queryKey:["dataModels",s],queryFn:()=>Vn(`${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 mQe(){var S,C,j;const e=Ee(D=>D.card.dataSource);Ee(D=>D.actions.updateDirectSource);const t=Ee(D=>D.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=Ii(),{databases:i,isPending:a,error:l,label:u}=hQe(),{schemas:d,isPending:f,error:h,label:p}=pQe(),{error:m}=uee(),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=p==null?void 0:p.toLowerCase(),v=D=>{e&&t({...e,dbSelection:{database:D,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=D=>{var _;if(!((_=e==null?void 0:e.dbSelection)!=null&&_.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:D},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&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:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(oe,{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(ce,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(et,{children:i.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(rt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(et,{children:d.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]})]})]})}function gQe(){const e=Ee(l=>l.card.dataSource),t=Ee(l=>l.actions.updateDataSource),[n,r]=N.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(ce,{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(uD,{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(oe,{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(ce,{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(Ni,{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(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function bQe(){const e=Ee(f=>f.card.dataSource),t=Ee(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.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(p=>p.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(ce,{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(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Nn,{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(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Nn,{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(ce,{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(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(kr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{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(s1,{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(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function xQe(e,t){var y,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:s}=Ii(t),o=Ee(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=Ee(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=Ee(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.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:p,isLoading:m,error:g,refetch:b}=un({queryKey:[e,o,i,a],queryFn:()=>Vn(`${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 S;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:(S=w==null?void 0:w.table_type)==null?void 0:S.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function $w({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(gd,{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 yQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ii(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=ur(),{entities:m,isLoading:g,error:b}=xQe("table"),{dataModels:x,isPending:y,error:v}=uee(),w=_=>{const M=s.find(O=>O.id===_);if(!M)return;const R=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:_,connectionType:M.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(_)},S=_=>{var T,I;const M=n||[],R=M.some(F=>F.name===_.name&&F.type===_.type);let O;if(R)O=M.filter(F=>!(F.name===_.name&&F.type===_.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:_.type,dbObjectType:_.dbObjectType,database:((T=e.dbSelection)==null?void 0:T.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:_.name,dialect:_.dialect};O=[...M,F]}t==null||t(O)},C=_=>{const M=n||[],R=M.some(T=>T.type==="model"&&T.name===_.name);let O;R?O=M.filter(T=>!(T.type==="model"&&T.name===_.name)):O=[...M,_],t==null||t(O)},j=m.filter(_=>_.name.toLowerCase().includes(i.toLowerCase())),D=x.filter(_=>_.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const _=n||[];let M=[..._];if(d==="tables"){const O=j.filter(T=>!_.some(I=>I.name===T.name&&I.type==="table")).map(T=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:T.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:T.name,dialect:T.dialect}});M=[..._,...O]}else if(d==="datamodels"){const R=D.filter(O=>!_.some(T=>T.name===O.name&&T.type==="model"));M=[..._,...R]}t(M)},[d,j,D,n,e,t]);return N.useEffect(()=>{r&&r(k)},[r,k]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(et,{children:s.map(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(rl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:_.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:_.type})]})},_.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(gQe,{}),e.connectionType==="url"&&c.jsx(bQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(mQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(cs,{defaultValue:"tables",value:d,onValueChange:_=>f(_),className:"w-full",children:[c.jsxs(Wr,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ht,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ht,{value:"datamodels",children:["Data Models (",D.length,")"]})]}),c.jsxs(Gn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:_=>a(_.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($w,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(_=>{const M=n.some(R=>R.name===_.name&&R.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(_),children:[c.jsx(dn,{id:`table-${_.name}`,checked:M,onCheckedChange:()=>S(_),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[_.name,_.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),_.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},_.name)})})]}),c.jsxs(Gn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:_=>u(_.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($w,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):D.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):D.map(_=>{const M=n.some(R=>R.name===_.name&&R.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(_),children:[c.jsx(dn,{id:`dataModel-${_.name}`,checked:M,onCheckedChange:()=>C(_),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:_.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:_.description})]})]},_.name)})})]})]})})})]})]})]})}function vQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,u]=N.useState(""),d=N.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);N.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=dQe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=fQe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],D=j.some(_=>_.id===C.id&&_.type==="dataset");let k;if(D)k=j.filter(_=>!(_.id===C.id&&_.type==="dataset"));else{const _={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};k=[...j,_]}n==null||n(k)},v=g.filter(C=>C.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],D=v.filter(_=>!C.some(M=>M.id===_.id&&M.type==="dataset")).map(_=>({id:_.id,datasetType:_.type,name:_.name||_.table,label:_.label,domainId:_.domainId,description:_.description,database:_.database,schema:_.schema,type:"dataset",connectionId:_.connectionId,connectionType:_.connectionType,dialect:_.dialect,datamodelId:_.datamodelId,sql:_.sql})),k=[...C,...D];n(k)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),c.jsx(et,{children:m.map(C=>c.jsx(pe,{className:"hover:bg-muted",value:C.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:C.label}),c.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),p&&c.jsx($w,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search datasets...",value:l,onChange:C=>u(C.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($w,{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(C=>{const j=r.some(D=>D.id===C.id&&D.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[c.jsx(dn,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:D=>D.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:C.label||C.name}),c.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function TI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=qe(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=ur(),d=ee(M=>M.isVisualEditing),f=ee(M=>M.dashboard.aiContext),{setAiContext:h}=Yt(),p=N.useRef(null),[m,g]=N.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=N.useCallback(M=>{const R=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:R,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...R!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=N.useCallback(M=>{u({...n,...M})},[n,u]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),N.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),N.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const S=M=>{const R=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(R)},C=()=>{l([])},j=N.useCallback(M=>{l(M)},[]),D=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(M=>{p.current=M,g(!0)},[]);function _(){var M,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,T=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:T,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsx(Vr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Hr,{className:"flex-shrink-0",children:[c.jsx(Ur,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Rs,{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(cs,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Wr,{className:"grid w-full grid-cols-2",children:[c.jsx(Ht,{value:"database",children:"Direct Source"}),c.jsx(Ht,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(vQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:k}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(yQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(uQe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ts,{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(oe,{variant:"outline",onClick:D,disabled:!m,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:_,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function wQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=N.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Fa-n;if(l.length>u){$e.error(`You can only attach ${Fa} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=qQ(l);if(f.forEach(({file:h,error:p})=>{$e.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>xI(p)));e(h)}catch(h){console.error("Failed to process files:",h),$e.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>=Fa}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Fa,title:n>=Fa?`Maximum ${Fa} files allowed`:"Attach files",children:c.jsx(tD,{className:"h-4 w-4 text-muted-foreground"})})]})}function SQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=N.useState(!1),a=N.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=N.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=N.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=N.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=Fa-r;if(h.length>p){$e.error(`You can only attach ${Fa} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=qQ(h);if(g.forEach(({file:b,error:x})=>{$e.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>xI(x)));t(b),$e.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),$e.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:J("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(uD,{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:[Fa-r," slot(s) available"]})]})})]})}const RI=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),b=N.useRef(null),x=Op();ENe(),kNe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=W1(),{queueMessage:C}=Fp(),{addFileAttachment:j,removeFileAttachment:D,clearFileAttachments:k,getFileAttachments:_}=ZM(),M=KM(l),R=Ee(H=>H.card.dataSource),O=ee(H=>H.dashboard.aiContext),T=ee(H=>{var q;return(q=H.dashboard.aiContext)==null?void 0:q.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const q=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${q}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const F=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(C(l,H,M),t(""),k(l)):r({preventDefault:()=>{}}))},z=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),F()),H.key==="@"&&(K(),f(!0))},B=N.useCallback(H=>{const q=OWe(H.nativeEvent);q.length>0&&(H.preventDefault(),q.forEach(async X=>{const Z=await xI(X);j(l,Z)}))},[j,l]),$=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),P=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),V=N.useCallback(H=>{D(l,H)},[D,l]),L=H=>{if(x.selectedEntities.some(X=>X.id&&X.id===H.id||X.name===H.name)){const X=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:X})}else{const X=[...x.selectedEntities,H];y({selectedEntities:X})}},A=H=>{L(H)},W=H=>{var Z;if(!x.selectedEntities.some(G=>G.id&&G.id===H.id||G.name===H.name)){const G=[...x.selectedEntities,H];y({selectedEntities:G})}const X="label"in H?H.label:H.name;t(e+`@${X} `),f(!1),(Z=b.current)==null||Z.focus()},U=H=>{const q=x.selectedEntities.filter(G=>!(G.id&&G.id===H.id||G.name===H.name));y({selectedEntities:q});const Z=`@${"label"in H?H.label:H.name}`;e.includes(Z)&&t(e.replace(Z,"").trim())},Y=H=>{const q=new Set(H.map(G=>G.id||G.name)),X=x.selectedEntities.filter(G=>!q.has(G.id||G.name));y({selectedEntities:X});let Z=e;H.forEach(G=>{const ne=`@${"label"in G?G.label:G.name}`;Z=Z.replace(ne,"").trim()}),t(Z)},K=N.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(SQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(lQe,{entities:x.selectedEntities,availableEntities:T||[],onRemoveEntity:U,onRemoveEntities:Y}),M.length>0&&c.jsx(FWe,{files:M,onRemove:V,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:z,onPaste:B,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(Ns,{open:d,onOpenChange:H=>{H&&K(),f(H)},children:[c.jsx(js,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(cae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(ks,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(iQe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:T||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{T&&y({selectedEntities:T})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(wQe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(kae,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:F,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(L8,{className:"size-4"})})]})]})]}),c.jsx(TI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||JS,dialogMode:"aiContext"})]})});RI.displayName="ChatInputWithContext";function dee({assistantType:e,className:t}){const n=IW(e),{removeFromQueue:r}=Fp();return n.length===0?null:c.jsxs("div",{className:J("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(ul,{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(oe,{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(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function fee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=IW(e),{dequeueMessage:o}=Fp();N.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 hee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=N.useRef(null),[a,l]=N.useState(!0),[u,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(0),b=N.useRef(!1),x=N.useRef(0),y=N.useRef(a),v=N.useRef(),w=N.useRef({key:null,count:0,length:0}),S=N.useCallback(()=>{const k=i.current;return k?k.scrollHeight-k.scrollTop-k.clientHeight:0},[]),C=N.useCallback((k={})=>{if(!i.current)return;const{force:M=!1,instant:R=!1}=k;if(!M&&!y.current||!a&&!M)return;const O=R||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 T=i.current;if(!T){b.current=!1,v.current=void 0;return}const I=T.scrollHeight;O==="smooth"&&"scrollTo"in T?T.scrollTo({top:I,behavior:O}):T.scrollTop=I,g.current=T.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),j=N.useCallback(()=>{const k=i.current;if(!k)return;const _=g.current,M=k.scrollTop,R=M-_;if(g.current=M,R<-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 O=S()<=n;d(O),l(O),y.current=O,O&&(h(!1),m(0))},[S,n]),D=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>{y.current=a},[a]),N.useEffect(()=>{const k=i.current;if(!k||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=k?k.scrollTop:0,x.current=k?k.scrollHeight:0;return}g.current=k.scrollTop,x.current=k.scrollHeight;const _=w.current,M=e[e.length-1],R=(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,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,T=e.length>_.count,I=R!==_.key,F=O>_.length,z=s&&(M==null?void 0:M.role)==="assistant"&&!T&&(I||F),B=o||z;if(w.current={key:R,count:e.length,length:O},a&&(T||I||F||B)){C({force:!1,instant:B});return}if(!a&&T){const $=e.length-_.count;$>0&&(h(!0),m(P=>P+$))}else!a&&F&&(h(!0),m($=>$>0?$:1))},[e,C,a,s,o]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>{if(typeof ResizeObserver>"u")return;const k=i.current;if(!k)return;x.current=k.scrollHeight;const _=new ResizeObserver(()=>{const M=i.current;if(!M)return;const R=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return _.observe(k),()=>{_.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:D}}function pee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=N.useState(r),a=N.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=N.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=N.useCallback(()=>{i(r)},[r]);return N.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 mee(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:YQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const CQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function NQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Yw),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=pp(),y=N.useRef(null);ee(Ve=>Ve.dashboard.aiScopeTables),ee(Ve=>Ve.isDashboardEditing);const v=ee(Ve=>Ve.selectedSheetId),{setDataSource:w}=ur(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Yt(),D=Op(),{setCurrentAIContext:k,updateSelectedEntities:_,setReasoningEffort:M,setShowReasoning:R}=W1(),{clearQueue:O}=Fp(),{clearFileAttachments:T,getFileAttachments:I}=ZM(),F=KM("dashboard"),z=ee(Ve=>Ve.dashboard.aiContext),B=Ee(Ve=>Ve.card.dataSource),{assistantProfile:$}=iee(),P=ee(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:V,isLoading:L,messages:A,setMessages:W,status:U,stop:Y,errorMessage:K,clearError:H}=oQe(),q=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),X=N.useCallback(()=>{q(!g)},[g,q]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&q(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,q]);const[Z,G]=N.useState(""),Q=Ve=>{G(Ve.target.value)};function ne({sql:Ve,data:Ue,cardTitle:pt,connectionId:He,cardType:Ze,python:ve,cardConfig:je,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:pt,connectionId:He,cardType:Ze,python:ve,cardConfig:je,dataSource:Te}),!v)return;const ze={id:jr(),title:pt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ze==="horizontalBar"?"y":"x"}},type:Ze,sql:Ve,python:ve,dataSource:Te,config:je,connectionId:He},nt={id:jr(),cards:[ze],activeCardId:ze.id};j(!0),S(v,nt,"end"),C(nt.id)}const ae=Ve=>{Ve.preventDefault();const Ue=Z.trim();if(!Ue&&F.length===0)return;const pt=[];Ue&&pt.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&pt.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),V({role:"user",parts:pt}),G(""),T("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),fee({assistantType:"dashboard",status:U,isLoading:L,sendMessage:V});const{hasActiveTools:ie}=mee(A),{visibleMessages:he,hasMoreMessages:be,totalMessageCount:Ce,loadMoreMessages:Oe,resetMessageWindow:ue}=pee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:De,isAtBottom:Ie,hasNewMessages:ht,newMessageCount:xe,scrollToBottom:se,handleScroll:de,resetNewMessageCount:we}=hee(he,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ke();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};V(Ue)}function Pe(Ve){Ke(),V({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ke(),V({role:"user",parts:[{type:"text",text:Ve}]}),se({force:!0})}const Nt=N.useCallback(async()=>{const Ve=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ve),$e.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),$e.error("Unable to copy conversation")}},[A]);function Ke(){D.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const Lt=(Z==null?void 0:Z.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ne(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Dt(){return c.jsxs(fp,{children:[c.jsx(hp,{asChild:!0,children:c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(rp,{className:"size-3.5"})})}),c.jsxs(qd,{align:"end",children:[c.jsx(Xf,{children:"Options"}),c.jsx(yd,{}),c.jsx(Zm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Zm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Zm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const hn=c.jsxs("div",{"data-role":"dashboard-assistant",className:J("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:[Ne(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Dt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Nt,children:"Copy Conversation"}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:X,children:g?c.jsx(eD,{className:"size-4"}):c.jsx(i1,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),H(),ue()},children:c.jsx(a1,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(yl,{"data-role":"dashboard-assistant-scroll-area",ref:De,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:de,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[be&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:Oe,className:"text-xs",children:["Load ",Math.min(5,Ce-he.length)," ","more messages (",Ce-he.length," ","hidden)"]})}),c.jsx(KQ,{showTools:a,showSystemMessage:u,messages:he,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ie&&c.jsx(GQ,{status:U,errorMessage:K})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Ie&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ys,{className:"h-4 w-4"}),ht&&xe>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:xe>9?"9+":xe})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&Lt&&c.jsx(ZQ,{onClick:Se,placeholders:CQe}),c.jsx("div",{children:Lt&&$&&c.jsx(aee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(dee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(RI,{ref:y,setInput:G,stop:Y,input:Z,handleInputChange:Q,handleSubmit:Ve=>{Ke(),ae(Ve),se({force:!0})},isLoading:L,status:U,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(TI,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:B||JS,dialogMode:"aiContext"})]});return g&&s?In.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:hn})}),s):hn}function jQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Yt(),o=ee(d=>d.dashboard.sheets),a=ee(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=ee(d=>d.isDashboardEditing),u=ee(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),$e.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=sR(m),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),$e.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function kQe(e,t){switch(e.interactionMode){case"drillToDetail":EQe(e,t);break;case"drillThrough":_Qe(e,t);break;case"drillToURL":DQe(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 EQe(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 _Qe(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 DQe(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 MQe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Vr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:i||"Insight Detail"}),c.jsx(Rs,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(lZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(uZ,{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 TQe(){const e=Ft(w=>w.interactionStates),t=Ft(w=>w.setInteractionState),n=Ft(w=>w.clearLastInteractionEvent),r=Ft(w=>w.replaceCardWithInsight),s=Ft(w=>w.setPendingDrillThrough),o=Ft(w=>w.pendingDrillThrough),i=Ft(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Yt(),{selectDashboard:u}=Ab(),d=ee(w=>w.dashboard),f=ee(w=>w.filterValues),{data:h,isLoading:p}=Vfe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=dZ(m.insightId,{enabled:m.open&&!!m.insightId}),x=N.useRef(new Set),y=N.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:S,contextMode:C})=>{g({open:!0,insightId:w,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:w,insightId:S,filters:C,contextMode:j})=>{r(w,S,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D})=>{const _={sourceCardId:na,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Ao(),appliedClickFilters:[_],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D};t(na,M)}}),[a,r,f,l,d,s,t]);N.useEffect(()=>{Object.entries(e).forEach(([w,S])=>{if(S!=null&&S.lastInteractionEvent){const C=S.lastInteractionEvent,j=`${w}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{kQe(C,y)}catch(D){console.error("Error executing interaction event:",D)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),N.useEffect(()=>{if(!(!o||!h||p))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,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(MQe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&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(On,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function RQe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=IQe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function IQe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function AQe(e){return e?`Back to ${e}`:"Back"}function PQe(){var x,y,v,w,S;const e=Ft(C=>C.interactionStates[na]),t=ee(C=>C.actions.goBackFromDrill),n=ee(C=>C.actions.clearDrillContext),{selectDashboard:r}=Ab(),[s,o]=N.useState({x:16,y:16}),[i,a]=N.useState(!1),l=N.useRef({x:0,y:0});N.useEffect(()=>{if(!i)return;const C=D=>{o({x:D.clientX-l.current.x,y:D.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[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||!((S=e.appliedClickFilters)!=null&&S.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},m=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),l.current={x:C.clientX-s.x,y:C.clientY-s.y})};RQe(f);const b=AQe(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((C,j)=>{const D=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[D," = ",k]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(l8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function gee(){var G;const{showAssistant:e,tokenProps:t}=qe(),{preferences:n,isConsoleMode:r}=pp(),s=((G=n==null?void 0:n.cardDisplay)==null?void 0:G.mode)==="print",o=N.useRef(null),i=N.useRef(null),[a,l]=N.useState(!1),u=sd(Q=>Q.setFullscreen),d=sd(Q=>Q.setPanelOpen),f=sd(Q=>Q.setContainer),h=DW("dashboard"),p=MW(),m=TW("dashboard"),g=h.isOpen,b=p==="dashboard",x=ee(Q=>Q.isVisualEditing),y=ee(Q=>Q.themeStyle),v=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.sheets}),w=ee(Q=>Q.isDashboardEditing),S=ee(Q=>Q.selectedSheetId),C=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.id}),j=ee(Q=>Q.isDashboardPanelOpen),D=ee(Q=>Q.actions.setIsDashboardPanelOpen),{getDefaultSheetId:k,setDefaultSheetId:_,clearDefaultSheetId:M}=V6(C),[R,O]=N.useState(null);S1(At.DASHBOARD);const{setSelectedSheetId:T,setSheetTitle:I,addSheet:F,setSheets:z}=Yt();jQe(i);const{setActiveAssistantType:B}=W1();N.useEffect(()=>{if(C){const Q=k();O(Q)}},[C,k]),N.useEffect(()=>{g?B("dashboard"):p==="dashboard"&&u(null)},[g,B,p,u]);function $(Q){var ne,ae;Q?((ne=o.current)==null||ne.resize(40),d("dashboard",!0),B("dashboard")):(d("dashboard",!1),u(null),(ae=o.current)==null||ae.resize(0),B(null))}function P(){const Q={id:jr(),title:"New Sheet"};F(Q),T(Q.id)}function V(Q,ne){if(!C)return;R===Q?(M(),O(null),$e.success("Default sheet cleared")):(_(Q),O(Q),$e.success(`"${ne}" set as default sheet`))}function L(Q){Q<1?(d("dashboard",!1),u(null),B(null)):(g||d("dashboard",!0),B("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(Q,ne)=>{Q.dataTransfer.setData("tabIndex",ne.toString())},U=Q=>{Q.preventDefault()},Y=(Q,ne)=>{const ae=Q.dataTransfer.getData("tabIndex");if(ae===ne.toString())return;const ie=Array.from(v||[]),[he]=ie.splice(parseInt(ae),1);ie.splice(ne,0,he),z(ie)},K=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var Q,ne;if(v&&v.length>1||w)return c.jsxs(Wr,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&K&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{D(!j)},className:"h-8 p-2",children:j?c.jsx(v8,{className:"h-4 w-4"}):c.jsx(w8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ae,ie)=>{const he=S===ae.id,be=R===ae.id;return c.jsxs(Ht,{draggable:!0,onDragStart:Ce=>W(Ce,ie),onDragOver:U,onDrop:Ce=>Y(Ce,ie),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>T(ae.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ae.id,children:[c.jsx(tb,{enabled:w&&he,text:ae.title,onSave:Ce=>I(ae.id,Ce),children:ae.title},ae.id),!w&&he&&c.jsx("div",{title:be?"Clear default sheet":"Set as default sheet",children:c.jsx(oD,{className:J("ml-1 size-3 cursor-pointer transition-all",be?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ce=>{Ce.stopPropagation(),V(ae.id,ae.title||"Sheet")}})}),w&&he&&v.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ae.id)}),w&&c.jsx("div",{style:{borderRadius:(ne=(Q=y==null?void 0:y.chart)==null?void 0:Q.options)==null?void 0:ne.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(kr,{className:"size-3"})})]})}function q(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(Q=>c.jsx(Gn,{style:{backgroundColor:A()},className:J("mt-0",{}),value:Q.id,children:c.jsx(X6e,{sheet:Q})},Q.id))})}function X(){var Q;return c.jsxs(cs,{"data-role":"dashboard-tabs-container",className:J("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:ne=>{T(ne)},value:S||((Q=v==null?void 0:v[0])==null?void 0:Q.id),children:[H(),c.jsx(yl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:q()}),c.jsx(M8e,{open:a,setOpen:l})]})}const Z=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(TQe,{}),c.jsx(PQe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(TX,{className:J("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(HE,{children:X()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(D8e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(HE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:L,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(NQe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:Q=>u(Q?"dashboard":null),fullscreenContainer:m})})})]})]}),c.jsx("div",{ref:Z,className:J("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(sD,{className:"h-5 w-5"})})})]})]}):null}function II({children:e}){return c.jsx(va,{style:{height:"100%",width:"100%"},children:c.jsx(dse,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Yn,{delayDuration:0,children:e})})})}function bee({children:e,preferences:t}){const{currentUser:n}=Ms(),r=N.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(R9.Provider,{value:r,children:c.jsx(jR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function xee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(wl,{FallbackComponent:hS,children:c.jsx(V_,{dashboardProps:e,children:c.jsx(II,{children:c.jsx(bee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(XM,{...e,type:"dashboard",children:c.jsx(gee,{})})})})})})})}function AI(e){const{tokenProps:t,authToken:n}=qe(),r=t==null?void 0:t.apiServiceUrl;return un({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Vn(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 yee(e,t,n){if(t==="source")return{isValid:!0};const r=Ks(e.dataType);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 vee(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 wee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=AI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=ur(),h=Ee(T=>T.card.type),p=e==null?void 0:e.id,m=N.useCallback(T=>{if(!(e!=null&&e.config))return[];switch(T){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=N.useCallback((T,I)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:I});break}case"metrics":{r(p,{metricColumns:I});break}case"pivotBy":{r(p,{pivotByColumns:I});break}case"sortBy":{r(p,{sortByColumns:I});break}}},[p,r]),b=N.useCallback((T,I,F)=>{if(!p)return;const B=m(T)[I];if(B)switch(T){case"groupBy":s(p,B.id,{label:F});break;case"metrics":o(p,B.id,{label:F});break;case"pivotBy":i(p,B.id,{label:F});break;case"sortBy":a(p,B.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aggregate:I,label:aU(z.name,I)})},[p,m,o]),y=N.useCallback((T,I,F)=>{if(!p)return;const B=m("groupBy")[T];if(!B)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,B.id,$)},[p,m,s]),v=N.useCallback((T,I)=>{if(!p)return;const z=m("groupBy")[T];z&&s(p,z.id,{granularity:I})},[p,m,s]),w=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((T,I)=>{if(console.log("handleValueAliasesChange",T,I),!p)return;console.log("handleValueAliasesChange",T,I);const z=m("metrics")[T];z&&(console.log("handleValueAliasesChange",I),o(p,z.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(T=>{if(!p)return;if(m("metrics").length===0){$e.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,m]),j=N.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),D=N.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),k=N.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),_=N.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),M=N.useCallback(T=>{var V;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=XSe(T,I,{joinPlan:(V=e==null?void 0:e.config)==null?void 0:V.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&sU();return}const z=eCe(T,I,h);if(!z){$e.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=yee(T,z,h);if(!B.isValid){$e.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const $=m(z);if(oU(T,$))return;const P=lU(T,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&vee(h,e==null?void 0:e.config,r,p,L)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),R=N.useCallback((T,I)=>{if(!p)return;const z=m(T)[I];if(z){if(T!=="sortBy"){const B=m("sortBy"),$=B.filter(P=>!(P.name===z.name&&P.qualifiedEntityName===z.qualifiedEntityName));$.length!==B.length&&r(p,{sortByColumns:$})}switch(T){case"groupBy":l(p,z.id);break;case"metrics":u(p,z.id);break;case"pivotBy":d(p,z.id);break;case"sortBy":f(p,z.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:S,removeField:R,handleFieldClick:M,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:_,cardType:h}};function Fx(e,t){var Pe,Qe,Nt,Ke,Lt;const{tokenProps:n}=qe(),r=Zs(),s=qe().authToken||e,o=Ee(Ne=>Ne.selectedConnectionId),i=Ee(Ne=>Ne.card),{queryKey:a}=Wpe(i),l=Ee(Ne=>Ne.selectedDatamodelId),u=Ee(Ne=>Ne.isDevMode),d=Ee(Ne=>Ne.selectedDatabaseName),f=Ee(Ne=>Ne.selectedSchemaName),h=Ee(Ne=>Ne.selectedTableName),p=Ee(Ne=>Ne.actions.setSelectedConnectionId),m=Ee(Ne=>Ne.actions.setSelectedDatamodelId),g=Ee(Ne=>Ne.actions.setSelectedDatabaseName),b=Ee(Ne=>Ne.actions.setSelectedSchemaName),x=Ee(Ne=>Ne.actions.setSelectedTableName);Ee(Ne=>Ne.actions.setCardSql);const{setQueryConfig:y}=ur();function v(Ne){var hn;return o&&Ne==="API"?!1:o&&Ne==="S3"?!0:!(!o||!d||d==="NA"||((hn=k==null?void 0:k.capabilities)==null?void 0:hn.path.includes("schema"))&&!f)}function w(Ne){return o&&Ne?!(Ne==="API"||Ne==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:D,selectedConnection:k}=Ii(e),{refetch:_,data:M,isLoading:R,isError:O}=un({queryKey:["models",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),T=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:z,isFetching:B,isError:$,refetch:P}=un({queryKey:["databases",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(T)}),{data:V,isLoading:L,isFetching:A,isError:W,refetch:U}=un({queryKey:["schemas",o,d],queryFn:()=>Vn(`${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:K,isFetching:H,isError:q,refetch:X}=un({queryKey:["tables",o,d,f],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(T)}),{columns:Z,isColumnsLoading:G,isColumnsFetching:Q,isColumnsError:ne,refetchColumns:ae}=cU(e);N.useEffect(()=>{(T==="S3"||T==="API")&&(g(""),b(""),m(""),T==="API"&&x("api"))},[T,x,g,b,m]);const ie=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",he=I?"":f||"";function be(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(Ne){b(Ne),x("")}function Oe(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&m("")}function ue(Ne){p(Ne)}function De(Ne){m(Ne==="none"?"":Ne),Ne!=="none"&&Ne!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,V&&((Nt=V==null?void 0:V.schemas)==null?void 0:Nt.length)>0;const Ie=C==null?void 0:C.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),ht=(Ke=M==null?void 0:M.datamodels)==null?void 0:Ke.map(Ne=>({id:Ne.id,name:Ne.name})),xe=F==null?void 0:F.databases.map(Ne=>({id:Ne.database_name,name:Ne.database_name})),se=V==null?void 0:V.schemas.map(Ne=>({id:Ne.schema_name,name:Ne.schema_name})),de=Y==null?void 0:Y.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),we=(Lt=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:Lt.name,Se=Xy({schemaName:he,tableName:ie,modelName:we,connectionType:T,databaseName:d||""});return{connectionItems:Ie,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:D,modelItems:ht,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:xe,isDatabasesLoadingOrFetching:z||B,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:de,selectedTableName:h,isTableLoadingOrFetching:K||H,isTableError:q,columns:Z,isColumnsLoadingOrFetching:G||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:T,tableName:ie,formattedTableName:Se,schemaName:he,refetchConnections:S,refetchModels:_,refetchDatabases:P,refetchSchemas:U,refetchTables:X,refetchColumns:ae,handleConnectionChange:ue,handleDatamodelChange:De,handleDatabaseChange:Oe,handleSchemaChange:Ce,handleTableChange:be}}function gy(e){return`${e}-${jr()}`}function CL(e,t){const n=Yo(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 OQe(e,t){const n=Yo(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 PI(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 See(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Cee(){const e=Ee(C=>C.sqlGen),t=Ee(C=>C.isDevMode),n=Ee(C=>C.card.dataSource),r=Ee(C=>{var j,D;return(D=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:D.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=PI(n),a=See(n),l=Ee(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=ur(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Fx(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var D;if(!t)return;const j=y(C);if(t&&a&&s){const k=R_(j,e);p(k);const _=(D=b==null?void 0:b.find(R=>R.id===l))==null?void 0:D.name,M=T_(k,fi(o||""),fi(s),_||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Rb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:gy(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:gy(j.column_name),name:j.column_name,label:CL(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Lc(j.data_type)){const k={...j,role:"groupby",id:gy(j.column_name),name:j.column_name,type:j.data_type,label:OQe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:gy(j.column_name),name:j.column_name,label:CL(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Xy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Xy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${C}`),h(!0)},isNumberField:C=>Vo(C.dataType)}}function Nee(){const e=Ee(m=>m.selectedConnectionId),t=Ee(m=>m.selectedDatamodelId),n=Ee(m=>m.selectedDatabaseName),r=Ee(m=>m.selectedSchemaName),s=Ee(m=>m.selectedTableName),o=ee(m=>m.dashboard.filters)||[],i=ee(m=>m.selectedSheetId),a=ee(m=>m.actions.addFilter),l=ee(m=>m.actions.removeFilter),{removeFilterValues:u}=Yt(),{modelItems:d,tableName:f,connectionType:h}=Fx();function p(m,g="sheet",b){var k;const x=fi(m.column_name),y=fi(n||""),v=fi(r||""),w=fi(f);let S=Gw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(_=>_.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${jg}.${j}.${x}`,S=`${jg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let D;if(g==="sheet"&&i?D=Dke(o,C,w,n||"",y,i):D=o==null?void 0:o.find(_=>_.column===C&&_.table===w&&(_.database===y||_.database===n)),D)u(D.id),l(D.id);else{const _=jr(),M=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:_,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:M,sql:W4(m.data_type,S,x)}),_):(a({id:_,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:M,sql:W4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),_)}}return{assignFilter:p}}function FQe({column:e}){const[t,n]=N.useState(!1),r=Ee(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=PI(r),a=Ee(x=>x.selectedDatamodelId),l=Ee(x=>x.sqlGen),{modelItems:u,connectionType:d}=Fx(),f=Ee(x=>x.actions.setSqlGen),h=Ee(x=>x.actions.setCardSql),p=Ee(x=>x.actions.setRunSql),m=See(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=R_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=T_(v,fi(o||""),fi(s),w||"",d,i||"");S&&(h(S),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(Ip,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Ap,{asChild:!0,children:c.jsx(rp,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Jd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function $Qe({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 LQe({field:e,context:t="editor",fieldState:n}){const r=Ee(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=ee(L=>L.dashboard.filters),a=ee(L=>L.selectedSheetId),l=ee(L=>L.actions.removeFilter),{removeFilterValues:u}=Yt(),{assignFilter:d}=Nee(),f=s?Zc(i,a):i,h=s?f==null?void 0:f.find(L=>{var A;return L.title===e.name||((A=L.column)==null?void 0:A.includes(e.name))}):void 0,p=!!h,m=h&&s?i==null?void 0:i.find(L=>L.id===h.id):void 0,g=m&&(m.applyToSheetIds&&m.applyToSheetIds.length>1||m.excludeSheetIds&&m.excludeSheetIds.length>0||!m.applyToSheetIds&&!m.excludeSheetIds&&!m.sheetId);s&&p&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:p,activeFilterOnSheet:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:a});const[b,x]=N.useState(!1),[y,v]=N.useState(null),{attributes:w,listeners:S,setNodeRef:C,transform:j,transition:D,isDragging:k}=IS({id:e.id,disabled:o}),[_,M]=N.useState(!1),R=Ee(L=>L.card),{handleFieldClick:O}=wee(R),{handleDevModeFieldClick:T,isNumberField:I}=Cee(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},z=()=>{if(s){const L={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};p&&g?(v({column:L,field:e}),x(!0)):d(L,"sheet",e)}else r?T(e):O(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:_i.Transform.toString(j),transition:D},V=(()=>{if(!n||s)return{};const A={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",...A},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...A},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...A}}[n.state]||A})();return c.jsxs("div",{ref:C,style:$,...o?{}:w,...o?{}:S,className:J("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",V.borderColor||"border-transparent",V.bgColor||"",V.hoverBorderColor,V.hoverBgColor||"hover:bg-muted",V.opacity,V.cursor,p&&"border-accent-foreground/20 bg-accent",{"cursor-pointer":r||s,"cursor-grab active:cursor-grabbing":!o&&!r&&!s}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:z,children:[ib(e.dataType),c.jsx(Yn,{children:c.jsxs(bn,{children:[c.jsx(xn,{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 ${_?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(Cn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx($Qe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(FQe,{column:B})})]}),_&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Si,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(z8,{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(Mae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Wb,{open:b,onOpenChange:x,children:c.jsxs(mp,{children:[c.jsxs(gp,{children:[c.jsx(xp,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(yp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(bp,{children:[c.jsx(wp,{children:"Cancel"}),c.jsx(vp,{onClick:F,children:"Remove Filter"})]})]})})]})}const zQe="SEMAPHOR_CALCULATED_FIELD",BQe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","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 jee(e){return!!e.expression}function VQe(e){return!!e.expression}function HQe(e){return!!e.expression}var kee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(kee||{}),jl="Accordion",UQe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[OI,WQe,qQe]=l1(jl),[rC]=_r(jl,[qQe,mZ]),FI=mZ(),Eee=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(OI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(ZQe,{...o,ref:t}):c.jsx(KQe,{...s,ref:t})})});Eee.displayName=jl;var[_ee,YQe]=rC(jl),[Dee,GQe]=rC(jl,{collapsible:!1}),KQe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=$r({prop:n,defaultProp:r,onChange:s});return c.jsx(_ee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Dee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Mee,{...i,ref:t})})})}),ZQe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=$r({prop:n,defaultProp:r,onChange:s}),l=N.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=N.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(_ee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Dee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Mee,{...o,ref:t})})})}),[XQe,sC]=rC(jl),Mee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=N.useRef(null),l=ft(a,t),u=WQe(n),f=Vd(s)==="ltr",h=ke(e.onKeyDown,p=>{var D;if(!UQe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var _;return!((_=k.ref.current)!=null&&_.disabled)}),b=g.findIndex(k=>k.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,S=()=>{y=b+1,y>w&&(y=v)},C=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?S():C());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?C():S());break;case"ArrowUp":o==="vertical"&&C();break}const j=y%x;(D=g[j].ref.current)==null||D.focus()});return c.jsx(XQe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(OI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Lw="AccordionItem",[QQe,$I]=rC(Lw),Tee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=sC(Lw,n),i=YQe(Lw,n),a=FI(n),l=nr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(QQe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(xZ,{"data-orientation":o.orientation,"data-state":Fee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Tee.displayName=Lw;var Ree="AccordionHeader",Iee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(jl,n),o=$I(Ree,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":Fee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Iee.displayName=Ree;var h_="AccordionTrigger",Aee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(jl,n),o=$I(h_,n),i=GQe(h_,n),a=FI(n);return c.jsx(OI.ItemSlot,{scope:n,children:c.jsx(e$e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Aee.displayName=h_;var Pee="AccordionContent",Oee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(jl,n),o=$I(Pee,n),i=FI(n);return c.jsx(t$e,{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}})});Oee.displayName=Pee;function Fee(e){return e?"open":"closed"}var JQe=Eee,eJe=Tee,tJe=Iee,$ee=Aee,Lee=Oee;const zee=JQe,LI=E.forwardRef(({className:e,...t},n)=>c.jsx(eJe,{ref:n,className:J("border-b",e),...t}));LI.displayName="AccordionItem";const zI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(tJe,{className:"flex",children:c.jsxs($ee,{ref:r,className:J("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(Ys,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));zI.displayName=$ee.displayName;const BI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(Lee,{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:J("pb-4 pt-0",e),children:t})}));BI.displayName=Lee.displayName;function nJe({context:e="editor"}={}){var _,M,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");Ee(T=>T.isDevMode);const o=Ee(T=>T.card.dataSource),i=Ee(T=>T.card.config),a=Ee(T=>T.card),{autoJoinMetadata:l}=fa(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=IM(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=AI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(M=(_=i==null?void 0:i.joinPlan)==null?void 0:_.baseEntity)==null||M.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,Cee();const b=u.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.label&&T.label.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=T=>{if(T.role==="metric"&&jee(T)||T.role==="groupby"&&T.expression)return"calculated";if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const I=Ks(T.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(T=>x(T)===r)).reduce((T,I)=>{const F=I.qualifiedEntityName||"Other Fields";return T[F]||(T[F]={label:P_(I.entityName),fields:[]}),T[F].fields.push(I),T},{}),S=Object.keys(v),C=b.filter(T=>x(T)==="dimensions").length,j=b.filter(T=>x(T)==="metrics").length,D=b.filter(T=>x(T)==="calculated").length,k=b.length>0;return f?c.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})}):h?c.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[c.jsx(rl,{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:h.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?c.jsx(Ds,{className:"h-[calc(100vh-200px)] w-[290px]",children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx(rl,{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:e==="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"})]})}):c.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&c.jsxs("div",{className:"relative mb-4",children:[c.jsx(ba,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Bn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:T=>n(T.target.value)}),t&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),k&&c.jsx(cs,{defaultValue:"all",value:r,onValueChange:T=>s(T),className:"mb-4",children:c.jsxs(Wr,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ht,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ht,{value:"dimensions",className:"text-xs",children:[c.jsx(o1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ht,{value:"metrics",className:"text-xs",children:[c.jsx(np,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ht,{value:"calculated",className:"text-xs",children:[c.jsx(K_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]})]})})]}),c.jsxs(yl,{className:"py-2",children:[c.jsx(zee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([T,I])=>{const F=d.find(z=>z.entityName===T)||{entityName:T,label:I.label};return c.jsxs(LI,{value:T,className:"border-none",children:[c.jsx(zI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:F.label||F.entityName,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||F.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx(BI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const B=AM(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(LQe,{field:z,context:e,fieldState:B},z.id)})})})]},T)})}),Object.keys(v).length===0&&u.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:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(v).length===0&&u.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function Bee({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(nJe,{context:e})," "]})}function Vee(){const e=Ee(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=ur();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=PI(e),d=(p=e.selectedEntities)==null?void 0:p[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 rJe(){Vee();const e=ee(l=>l.selectedSheetId),t=ee(l=>l.selectedFrameId),n=ee(l=>l.dashboard),r=ee(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Yt(),{setCard:o}=ur(),i=Ee(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.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 sJe(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=rJe();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(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(hZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(rl,{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(TS,{collisionDetection:ES,children:c.jsx(RS,{items:[],strategy:zR,children:c.jsx(Bee,{context:"filter"})})})})]})}function oJe(){const e=ee(r=>r.dashboard.filters),t=ee(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:J("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(ER,{filter:r}),c.jsx(CS,{filter:r})]},r.id))}):null}function iJe(){const e=ee(r=>r.showFilters),t=ee(r=>r.isVisualEditing),n=ee(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:J("",{"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(oJe,{}),c.jsx(gee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(sJe,{})})]})}const aJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-DPZpVj3x.js"))),lJe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-DcHh-xOS.js"))),cJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-B-mczKaU.js"))),uJe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-CNgGS6ct.js")).then(e=>({default:e.ResourceManagementPanel})));function dJe({showControls:e=!1,showFooter:t=!0,...n}){const r=ee(l=>l.isDashboardPanelOpen),s=ee(l=>l.isVisualEditing),o=ee(l=>l.showDashboardJSON),i=ee(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(wl,{FallbackComponent:hS,children:c.jsxs(V_,{dashboardProps:n,children:[c.jsx(sfe,{}),c.jsx(II,{children:c.jsxs(bee,{preferences:a,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(cJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(aJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(uJe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(XM,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(lJe,{})}),c.jsx(iJe,{})]})})]})]})]})})]})})}var fJe=Object.defineProperty,hJe=(e,t,n)=>t in e?fJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,by=(e,t,n)=>hJe(e,typeof t!="symbol"?t+"":t,n);const pJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},mJe={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}},gJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},bJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},xJe={stringify:e=>e,parse:e=>e},ej={string:xJe,number:bJe,boolean:pJe,function:mJe,json:gJe};function yJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const xy=Symbol.for("r2wc.render"),yy=Symbol.for("r2wc.connected"),gu=Symbol.for("r2wc.context"),Ma=Symbol.for("r2wc.props");function vJe(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 p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=yJe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),by(this,o,!0),by(this,s),by(this,r,{}),by(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ma].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?ej[x]:null;y!=null&&y.parse&&b&&(this[Ma][m]=y.parse(b,g,this))}for(const m of a)this[Ma][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[yy]=!0,this[xy]()}disconnectedCallback(){this[yy]=!1,this[gu]&&n.unmount(this[gu]),delete this[gu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?ej[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Ma][x]=v.parse(b,m,this),this[xy]())}[(o=yy,s=gu,r=Ma,xy)](){this[yy]&&(this[gu]?n.update(this[gu],this[Ma]):this[gu]=n.mount(this.container,e,this[Ma]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[Ma][p]},set(b){this[Ma][p]=b;const x=g?ej[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[xy]()}})}return h}function wJe(e,t,n){const r=hj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function SJe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function CJe({root:e}){e.unmount()}function NJe(e,t={}){return vJe(e,t,{mount:wJe,update:SJe,unmount:CJe})}const jJe={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"},kJe=NJe(xee,{props:jJe});function EJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function NL(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 jL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?NL(Object(n),!0).forEach(function(r){EJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):NL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function _Je(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function DJe(e,t){if(e==null)return{};var n=_Je(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function MJe(e,t){return TJe(e)||RJe(e,t)||IJe(e,t)||AJe()}function TJe(e){if(Array.isArray(e))return e}function RJe(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function IJe(e,t){if(e){if(typeof e=="string")return kL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return kL(e,t)}}function kL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function AJe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1066
|
+
`)}})}});var wXe=pZe(()=>WJ(Ar([Wn({type:ut("text-start"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("text-delta"),id:Le(),delta:Le(),providerMetadata:ir.optional()}),Wn({type:ut("text-end"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("error"),errorText:Le()}),Wn({type:ut("tool-input-start"),toolCallId:Le(),toolName:Le(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-delta"),toolCallId:Le(),inputTextDelta:Le()}),Wn({type:ut("tool-input-available"),toolCallId:Le(),toolName:Le(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional()}),Wn({type:ut("tool-input-error"),toolCallId:Le(),toolName:Le(),input:co(),providerExecuted:Sr().optional(),providerMetadata:ir.optional(),dynamic:Sr().optional(),errorText:Le()}),Wn({type:ut("tool-output-available"),toolCallId:Le(),output:co(),providerExecuted:Sr().optional(),dynamic:Sr().optional(),preliminary:Sr().optional()}),Wn({type:ut("tool-output-error"),toolCallId:Le(),errorText:Le(),providerExecuted:Sr().optional(),dynamic:Sr().optional()}),Wn({type:ut("reasoning-start"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-delta"),id:Le(),delta:Le(),providerMetadata:ir.optional()}),Wn({type:ut("reasoning-end"),id:Le(),providerMetadata:ir.optional()}),Wn({type:ut("source-url"),sourceId:Le(),url:Le(),title:Le().optional(),providerMetadata:ir.optional()}),Wn({type:ut("source-document"),sourceId:Le(),mediaType:Le(),title:Le(),filename:Le().optional(),providerMetadata:ir.optional()}),Wn({type:ut("file"),url:Le(),mediaType:Le(),providerMetadata:ir.optional()}),Wn({type:zJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:Le().optional(),data:co(),transient:Sr().optional()}),Wn({type:ut("start-step")}),Wn({type:ut("finish-step")}),Wn({type:ut("start"),messageId:Le().optional(),messageMetadata:co().optional()}),Wn({type:ut("finish"),messageMetadata:co().optional()}),Wn({type:ut("abort")}),Wn({type:ut("message-metadata"),messageMetadata:co()})])));function SXe(e){return e.type.startsWith("data-")}function JJ(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]=JJ(o,s):n[r]=s}return n}function CXe(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 eee(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await Ow({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await Ow({text:CXe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Uy(e){return e.type.startsWith("tool-")}function NXe(e){return e.type==="dynamic-tool"}function c_(e){return Uy(e)||NXe(e)}function vL(e){return e.type.split("-").slice(1).join("-")}function jXe({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 kXe({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,p,m;function g(w){const C=u.message.parts.filter(Uy).find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function b(w){const C=u.message.parts.filter(j=>j.type==="dynamic-tool").find(j=>j.toolCallId===w);if(C==null)throw new Error("tool-output-error must be preceded by a tool-input-available");return C}function x(w){var S;const C=u.message.parts.find(k=>Uy(k)&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=j.rawInput,D.preliminary=j.preliminary,D.providerExecuted=(S=j.providerExecuted)!=null?S:C.providerExecuted,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:`tool-${w.toolName}`,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,rawInput:j.rawInput,errorText:j.errorText,providerExecuted:j.providerExecuted,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}function y(w){var S;const C=u.message.parts.find(k=>k.type==="dynamic-tool"&&k.toolCallId===w.toolCallId),j=w,D=C;C!=null?(C.state=w.state,D.toolName=w.toolName,D.input=j.input,D.output=j.output,D.errorText=j.errorText,D.rawInput=(S=j.rawInput)!=null?S:D.rawInput,D.preliminary=j.preliminary,j.providerMetadata!=null&&C.state==="input-available"&&(C.callProviderMetadata=j.providerMetadata)):u.message.parts.push({type:"dynamic-tool",toolName:w.toolName,toolCallId:w.toolCallId,state:w.state,input:j.input,output:j.output,errorText:j.errorText,preliminary:j.preliminary,...j.providerMetadata!=null?{callProviderMetadata:j.providerMetadata}:{}})}async function v(w){if(w!=null){const S=u.message.metadata!=null?JJ(u.message.metadata,w):w;t!=null&&await mL({value:S,schema:t}),u.message.metadata=S}}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=(p=a.providerMetadata)!=null?p:w.providerMetadata,d();break}case"reasoning-end":{const w=u.activeReasoningParts[a.id];w.providerMetadata=(m=a.providerMetadata)!=null?m: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(Uy);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}):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:S}=await eee(w.text);w.dynamic?y({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}):x({toolCallId:a.toolCallId,toolName:w.toolName,state:"input-streaming",input:S}),d();break}case"tool-input-available":{a.dynamic?y({toolCallId:a.toolCallId,toolName:a.toolName,state:"input-available",input:a.input,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,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:vL(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})}else{const w=g(a.toolCallId);x({toolCallId:a.toolCallId,toolName:vL(w),state:"output-error",input:w.input,rawInput:w.rawInput,errorText:a.errorText})}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":{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(SXe(a)){(n==null?void 0:n[a.type])!=null&&await mL({value:a.data,schema:n[a.type]});const w=a;if(w.transient){i==null||i(w);break}const S=w.id!=null?u.message.parts.find(C=>w.type===C.type&&w.id===C.id):void 0;S!=null?S.data=w.data:u.message.parts.push(w),i==null||i(w),d()}}l.enqueue(a)})}}))}async function EXe({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()}}Ox({prefix:"aitxt",size:24});Ox({prefix:"aiobj",size:24});var _Xe=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()})}};Ox({prefix:"aiobj",size:24});var DXe={};dXe(DXe,{object:()=>TXe,text:()=>MXe});var MXe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),TXe=({schema:e})=>{const t=cXe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await eee(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 Ow({text:n});if(!s.success)throw new xL({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 EI({value:s.value,schema:t});if(!o.success)throw new xL({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}}},RXe=Hf({name:Le(),version:Le()}),DI=Hf({_meta:mr(Wt({}).loose())}),wb=DI,IXe=Wt({method:Le(),params:mr(DI)}),AXe=Hf({experimental:mr(Wt({}).loose()),logging:mr(Wt({}).loose()),prompts:mr(Hf({listChanged:mr(Sr())})),resources:mr(Hf({subscribe:mr(Sr()),listChanged:mr(Sr())})),tools:mr(Hf({listChanged:mr(Sr())}))});wb.extend({protocolVersion:Le(),capabilities:AXe,serverInfo:RXe,instructions:mr(Le())});var PXe=wb.extend({nextCursor:mr(Le())}),OXe=Wt({name:Le(),description:mr(Le()),inputSchema:Wt({type:ut("object"),properties:mr(Wt({}).loose())}).loose()}).loose();PXe.extend({tools:nu(OXe)});var FXe=Wt({type:ut("text"),text:Le()}).loose(),$Xe=Wt({type:ut("image"),data:AJ(),mimeType:Le()}).loose(),tee=Wt({uri:Le(),mimeType:mr(Le())}).loose(),LXe=tee.extend({text:Le()}),zXe=tee.extend({blob:AJ()}),BXe=Wt({type:ut("resource"),resource:Ar([LXe,zXe])}).loose();wb.extend({content:nu(Ar([FXe,$Xe,BXe])),isError:Sr().default(!1).optional()}).or(wb.extend({toolResult:co()}));var nC="2.0",VXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()])}).merge(IXe).strict(),HXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()]),result:wb}).strict(),UXe=Wt({jsonrpc:ut(nC),id:Ar([Le(),yb().int()]),error:Wt({code:yb().int(),message:Le(),data:mr(co())})}).strict(),WXe=Wt({jsonrpc:ut(nC)}).merge(Wt({method:Le(),params:mr(DI)})).strict();Ar([VXe,WXe,HXe,UXe]);async function qXe(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 YXe=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 kf(this.body),l=await kf(this.headers),u=await kf(this.credentials),d=await((n=this.prepareSendMessagesRequest)==null?void 0:n.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...a,...t.body},headers:{...l,...t.headers},credentials:u,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId})),f=(r=d==null?void 0:d.api)!=null?r:this.api,h=(d==null?void 0:d.headers)!==void 0?d.headers:{...l,...t.headers},p=(d==null?void 0:d.body)!==void 0?d.body:{...a,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId},m=(s=d==null?void 0:d.credentials)!=null?s:u,b=await((o=this.fetch)!=null?o:globalThis.fetch)(f,{method:"POST",headers:pL({"Content-Type":"application/json",...h},`ai-sdk/${yL}`,hL()),body:JSON.stringify(p),credentials:m,signal:e});if(!b.ok)throw new Error((i=await b.text())!=null?i:"Failed to fetch the chat response.");if(!b.body)throw new Error("The response body is empty.");return this.processResponseStream(b.body)}async reconnectToStream(e){var t,n,r,s,o;const i=await kf(this.body),a=await kf(this.headers),l=await kf(this.credentials),u=await((t=this.prepareReconnectToStreamRequest)==null?void 0:t.call(this,{api:this.api,id:e.chatId,body:{...i,...e.body},headers:{...a,...e.headers},credentials:l,requestMetadata:e.metadata})),d=(n=u==null?void 0:u.api)!=null?n:`${this.api}/${e.chatId}/stream`,f=(u==null?void 0:u.headers)!==void 0?u.headers:{...a,...e.headers},h=(r=u==null?void 0:u.credentials)!=null?r:l,m=await((s=this.fetch)!=null?s:globalThis.fetch)(d,{method:"GET",headers:pL(f,`ai-sdk/${yL}`,hL()),credentials:h});if(m.status===204)return null;if(!m.ok)throw new Error((o=await m.text())!=null?o:"Failed to fetch the chat response.");if(!m.body)throw new Error("The response body is empty.");return this.processResponseStream(m.body)}},MI=class extends YXe{constructor(e={}){super(e)}processResponseStream(e){return bZe({stream:e,schema:wXe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},GXe=class{constructor({generateId:e=oZe,id:t=e(),transport:n=new MI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new _Xe,this.sendMessage=async(f,h)=>{var p,m,g,b;if(f==null){await this.makeRequest({trigger:"submit-message",messageId:(p=this.lastMessage)==null?void 0:p.id,...h});return}let x;if("text"in f||"files"in f?x={parts:[...Array.isArray(f.files)?f.files:await qXe(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:(m=x.role)!=null?m:"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 p=f==null?this.state.messages.length-1:this.state.messages.findIndex(m=>m.id===f);if(p===-1)throw new Error(`message ${f} not found`);this.state.messages=this.state.messages.slice(0,this.messages[p].role==="assistant"?p:p+1),await this.makeRequest({trigger:"regenerate-message",messageId:f,...h})},this.resumeStream=async(f={})=>{await this.makeRequest({trigger:"resume-stream",...f})},this.clearError=()=>{this.status==="error"&&(this.state.error=void 0,this.setStatus({status:"ready"}))},this.addToolResult=async({state:f="output-available",tool:h,toolCallId:p,output:m,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=>c_(w)&&w.toolCallId===p?{...w,state:f,output:m,errorText:g}:w)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(w=>c_(w)&&w.toolCallId===p?{...w,state:f,output:m,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.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;this.setStatus({status:"submitted",error:void 0});const l=this.lastMessage;let u=!1,d=!1,f=!1;try{const h={state:jXe({lastMessage:this.state.snapshot(l),messageId:this.generateId()}),abortController:new AbortController};h.abortController.signal.addEventListener("abort",()=>{u=!0}),this.activeResponse=h;let p;if(e==="resume-stream"){const g=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(g==null){this.setStatus({status:"ready"});return}p=g}else p=await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:h.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:s});const m=g=>this.jobExecutor.run(()=>g({state:h.state,write:()=>{var b;this.setStatus({status:"streaming"}),h.state.message.id===((b=this.lastMessage)==null?void 0:b.id)?this.state.replaceMessage(this.state.messages.length-1,h.state.message):this.state.pushMessage(h.state.message)}}));await EXe({stream:kXe({stream:p,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:m,onError:g=>{throw g}}),onError:g=>{throw g}}),this.setStatus({status:"ready"})}catch(h){if(u||h.name==="AbortError")return u=!0,this.setStatus({status:"ready"}),null;f=!0,h instanceof TypeError&&(h.message.toLowerCase().includes("fetch")||h.message.toLowerCase().includes("network"))&&(d=!0),this.onError&&h instanceof Error&&this.onError(h),this.setStatus({status:"error",error:h})}finally{try{(o=this.onFinish)==null||o.call(this,{message:this.activeResponse.state.message,messages:this.state.messages,isAbort:u,isDisconnect:d,isError:f})}catch(h){console.error(h)}this.activeResponse=void 0}(i=this.sendAutomaticallyWhen)!=null&&i.call(this,{messages:this.state.messages})&&!f&&await this.makeRequest({trigger:"submit-message",messageId:(a=this.lastMessage)==null?void 0:a.id,metadata:t,headers:n,body:r})}};function KXe({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(c_);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function ZXe(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 XXe=ZXe;const QXe=$c(XXe);var nee=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(nee(e,t,"read from private field"),n?n.call(e):t.get(e)),zi=(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)},Ol=(e,t,n,r)=>(nee(e,t,"write to private field"),t.set(e,n),n);function JXe(e,t){return t!=null?QXe(e,t):e}var jo,Wy,qy,Wm,qm,Ym,Rf,u_,d_,eQe=class{constructor(e=[]){zi(this,jo,void 0),zi(this,Wy,"ready"),zi(this,qy,void 0),zi(this,Wm,new Set),zi(this,qm,new Set),zi(this,Ym,new Set),this.pushMessage=t=>{Ol(this,jo,Tn(this,jo).concat(t)),Tn(this,Rf).call(this)},this.popMessage=()=>{Ol(this,jo,Tn(this,jo).slice(0,-1)),Tn(this,Rf).call(this)},this.replaceMessage=(t,n)=>{Ol(this,jo,[...Tn(this,jo).slice(0,t),this.snapshot(n),...Tn(this,jo).slice(t+1)]),Tn(this,Rf).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?JXe(t,n):t;return Tn(this,Wm).add(r),()=>{Tn(this,Wm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,qm).add(t),()=>{Tn(this,qm).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Ym).add(t),()=>{Tn(this,Ym).delete(t)}),zi(this,Rf,()=>{Tn(this,Wm).forEach(t=>t())}),zi(this,u_,()=>{Tn(this,qm).forEach(t=>t())}),zi(this,d_,()=>{Tn(this,Ym).forEach(t=>t())}),Ol(this,jo,e)}get status(){return Tn(this,Wy)}set status(e){Ol(this,Wy,e),Tn(this,u_).call(this)}get error(){return Tn(this,qy)}set error(e){Ol(this,qy,e),Tn(this,d_).call(this)}get messages(){return Tn(this,jo)}set messages(e){Ol(this,jo,[...e]),Tn(this,Rf).call(this)}};jo=new WeakMap;Wy=new WeakMap;qy=new WeakMap;Wm=new WeakMap;qm=new WeakMap;Ym=new WeakMap;Rf=new WeakMap;u_=new WeakMap;d_=new WeakMap;var If,wL=class extends GXe{constructor({messages:e,...t}){const n=new eQe(e);super({...t,state:n}),zi(this,If,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,If)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,If)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,If)["~registerErrorCallback"](r),Ol(this,If,n)}};If=new WeakMap;function ree({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new wL(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new wL(n));const o="id"in n?n.id:null,i=N.useCallback(f=>r.current["~registerMessagesCallback"](f,e),[e,o]),a=N.useSyncExternalStore(i,()=>r.current.messages,()=>r.current.messages),l=N.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),u=N.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),d=N.useCallback(f=>{typeof f=="function"&&(f=f(r.current.messages)),r.current.messages=f},[r]);return N.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.addToolResult}}function tQe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function nQe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function rQe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function sQe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function see(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:sQe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function oee(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 oQe(){var b;const{authToken:e,tokenProps:t}=qe(),n=ee(x=>x.dashboard.aiScopeTables),r=(b=Qw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=ree({transport:new MI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Ai.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:RW(x)}})}),onToolCall:p,sendAutomaticallyWhen:KXe,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 p({toolCall:x}){if(x.toolName==="getCurrentTableScope"&&u({tool:x.toolName,toolCallId:x.toolCallId,output:{tables:see(n||[])}}),x.toolName==="getDashboardContext"){const y=ee.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=oee(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function iee(){var u;const{authToken:e,tokenProps:t}=qe(),n=(u=Qw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=un({queryKey:["assistant-profile",n],queryFn:()=>Vn(`${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 aee({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(S8,{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(oe,{variant:"outline",size:"sm",onClick:()=>t(n),className:"text-sm",children:n},r))})]})}function Fw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(iD,{className:r});case"view":return c.jsx(bc,{className:r});case"materialized view":return c.jsx(mae,{className:r});case"model":return c.jsx(o1,{className:r});case"file":return c.jsx(Ni,{className:r});case"dataset":return c.jsx(rl,{className:r});case"upload":return c.jsx(uD,{className:r});case"url":return c.jsx(R8,{className:r});default:return c.jsx(s1,{className:r})}}const lee=E.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(ba,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(ds.Input,{ref:n,className:J("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})]}));lee.displayName=ds.Input.displayName;const my=e=>e.label||(e==null?void 0:e.name),SL=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function iQe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=qe(),f=(d==null?void 0:d.type)==="dashboard",[h,p]=N.useState(""),[m,g]=N.useState(""),b=s.filter(C=>{if(!h)return!0;const j=my(C).toLowerCase(),D=SL(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||D.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(my(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>my(j)===m);C&&(o.some(D=>"id"in C&&"id"in D?C.id===D.id:C.name===D.name&&C.connectionId===D.connectionId)||t(C),i(C),r())},y=C=>{(C.key==="Tab"||C.key==="Enter")&&(C.preventDefault(),x())};if(!e)return null;const v=C=>o.some(j=>"id"in C&&"id"in j?C.id===j.id:C.name===j.name&&C.connectionId===j.connectionId),w=o.length===s.length,S=o.length>0;return c.jsx(c.Fragment,{children:c.jsxs(PS,{shouldFilter:!1,value:m,onValueChange:g,onKeyDown:y,children:[s.length>0&&c.jsxs("div",{className:"flex items-center justify-between border-b pr-3",children:[c.jsx(lee,{placeholder:"Search entities...",value:h,onValueChange:p,className:"flex-1 border-0",autoFocus:!0}),!f&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"outline",size:"sm",className:"h-7 shrink-0",children:[c.jsx(kr,{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(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),a==null||a()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},disabled:w,variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",children:"Select All"}),S&&c.jsxs(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),l==null||l()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},variant:"ghost",size:"sm",className:"h-6 gap-1 px-2 text-xs",children:[c.jsx(vt,{className:"h-3.5 w-3.5"}),"Clear"]})]})]}),c.jsxs(OS,{className:"min-h-60",children:[c.jsx(FS,{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(oe,{onClick:C=>{C.preventDefault(),C.stopPropagation(),u==null||u()},onMouseDown:C=>{C.preventDefault(),C.stopPropagation()},size:"sm",variant:"outline",className:"flex items-center gap-2",children:[c.jsx(kr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx($S,{children:b.map((C,j)=>{const D=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,_=my(C);return c.jsxs(LS,{value:_,onSelect:()=>{D?n==null||n(C):t(C)},onMouseDown:M=>{M.preventDefault(),M.stopPropagation()},className:J("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:Fw(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:_}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:SL(C)})]}),D&&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(Rr,{className:"h-3 w-3 text-background"})})]},k)})})]})]})})}const f_=e=>e.name||e.name,aQe=e=>{const t=f_(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 lQe({entities:e,availableEntities:t,onRemoveEntity:n,onRemoveEntities:r}){const[s,o]=N.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(Yn,{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(bn,{children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{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:[Fw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:f_(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(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{side:"top",className:"max-w-xs",children:aQe(d)})]},h)}),u&&c.jsxs(bn,{open:s,onOpenChange:o,children:[c.jsx(xn,{asChild:!0,children:c.jsxs(Fe,{variant:"secondary",className:"flex cursor-pointer items-center gap-1 transition-colors hover:bg-secondary/80",onClick:()=>o(!0),children:[c.jsx(gae,{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(vt,{className:"h-3 w-3"})})]})}),c.jsx(Cn,{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:Fw(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:f_(d)}),c.jsxs("div",{className:"truncate text-xs text-muted-foreground",children:[d.type," ",d.database?`• ${d.database}`:""]})]})]}),c.jsx(oe,{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(vt,{className:"h-3 w-3"})})]},f)})})]})})]})]})})})}function cee(e){return e.type==="dataset"&&e.label||e.name}function cQe(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 uQe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(ce,{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(Fe,{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,"]"]}),cee(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(vt,{className:"h-2.5 w-2.5 text-red-500"})})]},`${n.type}-${n.name}-${r}`))})})]})}function dQe(e){const{tokenProps:t}=qe(),n=ee(l=>l.authToken)||e;Ee(l=>l.selectedConnectionId),Ee(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}=un({queryKey:["semantic-domains"],queryFn:()=>Vn(`${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 fQe(e,t){const{tokenProps:n}=qe(),r=ee(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=un({queryKey:["datasets",e],queryFn:()=>Vn(`${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 hQe(e){var g,b;const{tokenProps:t}=qe(),n=ee(x=>x.authToken)||e,{connections:r}=Ii(e),s=Ee(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:p}=un({queryKey:["databases",s],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/databases`,(n==null?void 0:n.accessToken)||"",{connection_id:s}),enabled:u(i)}),m=(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:m||[],refetch:p,label:l}}function pQe(e){var g;const{tokenProps:t}=qe(),n=ee(b=>b.authToken)||e,{connections:r}=Ii(e),s=Ee(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=Ee(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:p}=un({queryKey:["schemas",s,o],queryFn:()=>Vn(`${t.apiServiceUrl}/v1/schemas`,(n==null?void 0:n.accessToken)||"",{connection_id:s,database_name:o}),enabled:u()}),m=d==null?void 0:d.schemas.map(b=>({id:b.schema_name,name:b.schema_name}));return{isPending:f,error:h,schemas:m||[],refetch:p,label:l}}function uee(e){const{tokenProps:t}=qe(),n=ee(h=>h.authToken)||e,{connections:r}=Ii(e),s=Ee(h=>{var p,m;return(m=(p=h==null?void 0:h.card)==null?void 0:p.dataSource)==null?void 0:m.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}=un({queryKey:["dataModels",s],queryFn:()=>Vn(`${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 mQe(){var S,C,j;const e=Ee(D=>D.card.dataSource);Ee(D=>D.actions.updateDirectSource);const t=Ee(D=>D.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=Ii(),{databases:i,isPending:a,error:l,label:u}=hQe(),{schemas:d,isPending:f,error:h,label:p}=pQe(),{error:m}=uee(),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=p==null?void 0:p.toLowerCase(),v=D=>{e&&t({...e,dbSelection:{database:D,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=D=>{var _;if(!((_=e==null?void 0:e.dbSelection)!=null&&_.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:D},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})};return c.jsxs(c.Fragment,{children:[(o||l||h||m)&&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:[p,": ",h.message]}),m&&c.jsxs("li",{children:["Data Models: ",m.message]})]})]})}),c.jsx(oe,{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(ce,{className:"text-sm font-medium",children:u}),c.jsxs(rt,{value:((S=e==null?void 0:e.dbSelection)==null?void 0:S.database)||"",onValueChange:v,disabled:a,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[a&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:l?`Error loading ${x}`:a?`Loading ${x}...`:`Select ${x}...`})]})}),c.jsx(et,{children:i.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:p}),c.jsxs(rt,{value:((j=e==null?void 0:e.dbSelection)==null?void 0:j.schema)||"",onValueChange:w,disabled:f,children:[c.jsx(Je,{className:"w-full",children:c.jsxs("div",{className:"flex items-center gap-2",children:[f&&c.jsx(On,{className:"h-4 w-4 animate-spin"}),c.jsx(lt,{placeholder:h?`Error loading ${y}`:f?`Loading ${y}...`:`Select ${y}...`})]})}),c.jsx(et,{children:d.map(D=>c.jsx(pe,{className:"hover:bg-muted",value:D.id,children:D.name},D.id))})]})]})]})]})}function gQe(){const e=Ee(l=>l.card.dataSource),t=Ee(l=>l.actions.updateDataSource),[n,r]=N.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(ce,{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(uD,{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(oe,{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(ce,{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(Ni,{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(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>o(l.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},l.id))})]})]})}function bQe(){const e=Ee(f=>f.card.dataSource),t=Ee(f=>f.actions.updateDataSource),[n,r]=N.useState(""),[s,o]=N.useState(""),[i,a]=N.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(p=>p.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(ce,{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(ce,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Nn,{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(ce,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Nn,{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(ce,{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(oe,{onClick:l,disabled:!n.trim()||!s.trim(),size:"sm",className:"w-full",children:[c.jsx(kr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(ce,{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(s1,{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(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 flex-shrink-0 p-0",onClick:()=>u(f.id),children:c.jsx(vt,{className:"h-3 w-3"})})]},f.id))})]})]})}function xQe(e,t){var y,v;const{tokenProps:n}=qe(),r=ee(w=>w.authToken)||t,{connections:s}=Ii(t),o=Ee(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=Ee(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.database}),a=Ee(w=>{var S,C,j;return(j=(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.dbSelection)==null?void 0:j.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:p,isLoading:m,error:g,refetch:b}=un({queryKey:[e,o,i,a],queryFn:()=>Vn(`${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 S;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:(S=w==null?void 0:w.table_type)==null?void 0:S.toLowerCase(),id:w[`${e}_name`],database:i,schema:a,name:w[`${e}_name`]}});return{isPending:p,isLoading:m,error:g,entities:x||[],refetch:b,label:d}}function $w({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(gd,{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 yQe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=Ii(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=ur(),{entities:m,isLoading:g,error:b}=xQe("table"),{dataModels:x,isPending:y,error:v}=uee(),w=_=>{const M=s.find(O=>O.id===_);if(!M)return;const R=M.type==="upload"?"upload":M.type==="url"?"url":"database";h({...e,connectionId:_,connectionType:M.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(_)},S=_=>{var T,I;const M=n||[],R=M.some(F=>F.name===_.name&&F.type===_.type);let O;if(R)O=M.filter(F=>!(F.name===_.name&&F.type===_.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:_.type,dbObjectType:_.dbObjectType,database:((T=e.dbSelection)==null?void 0:T.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:_.name,dialect:_.dialect};O=[...M,F]}t==null||t(O)},C=_=>{const M=n||[],R=M.some(T=>T.type==="model"&&T.name===_.name);let O;R?O=M.filter(T=>!(T.type==="model"&&T.name===_.name)):O=[...M,_],t==null||t(O)},j=m.filter(_=>_.name.toLowerCase().includes(i.toLowerCase())),D=x.filter(_=>_.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const _=n||[];let M=[..._];if(d==="tables"){const O=j.filter(T=>!_.some(I=>I.name===T.name&&I.type==="table")).map(T=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:T.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:T.name,dialect:T.dialect}});M=[..._,...O]}else if(d==="datamodels"){const R=D.filter(O=>!_.some(T=>T.name===O.name&&T.type==="model"));M=[..._,...R]}t(M)},[d,j,D,n,e,t]);return N.useEffect(()=>{r&&r(k)},[r,k]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"font-medium= text-sm",children:"Connection"}),c.jsxs(rt,{value:(e==null?void 0:e.connectionId)||"",onValueChange:w,disabled:o,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:o?"Loading connections...":"Select connection..."})}),c.jsx(et,{children:s.map(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(rl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:_.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:_.type})]})},_.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(gQe,{}),e.connectionType==="url"&&c.jsx(bQe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(mQe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(cs,{defaultValue:"tables",value:d,onValueChange:_=>f(_),className:"w-full",children:[c.jsxs(Wr,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ht,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ht,{value:"datamodels",children:["Data Models (",D.length,")"]})]}),c.jsxs(Gn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:_=>a(_.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($w,{title:"Error loading tables",message:b.message||"Failed to load tables. Please try again.",onRetry:()=>window.location.reload()}):j.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No tables or views found"}):j.map(_=>{const M=n.some(R=>R.name===_.name&&R.type==="table");return c.jsxs("div",{className:"group flex cursor-pointer items-center space-x-2 rounded p-2 hover:bg-muted",onClick:()=>S(_),children:[c.jsx(dn,{id:`table-${_.name}`,checked:M,onCheckedChange:()=>S(_),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(ce,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[_.name,_.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),_.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},_.name)})})]}),c.jsxs(Gn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:_=>u(_.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($w,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):D.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):D.map(_=>{const M=n.some(R=>R.name===_.name&&R.type==="model");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-muted",onClick:()=>C(_),children:[c.jsx(dn,{id:`dataModel-${_.name}`,checked:M,onCheckedChange:()=>C(_),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer",children:_.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:_.description})]})]},_.name)})})]})]})})})]})]})]})}function vQe({dataSource:e,onDataSourceUpdate:t,onSelectionChange:n,selectedEntities:r,allowedDomainIds:s=[],isRestricted:o=!1,autoSelectedDomainId:i,onRegisterSelectAll:a}){var S;const[l,u]=N.useState(""),d=N.useCallback(C=>{const j={...e,connectionId:e.connectionId||"none",connectionType:e.connectionType||"none",mode:"semanticDomain",semanticDomainId:C};t({...j})},[e,t]);N.useEffect(()=>{i&&!(e!=null&&e.semanticDomainId)&&d(i)},[i,e==null?void 0:e.semanticDomainId,d]);const{semanticDomains:f,isPending:h,error:p}=dQe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=fQe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],D=j.some(_=>_.id===C.id&&_.type==="dataset");let k;if(D)k=j.filter(_=>!(_.id===C.id&&_.type==="dataset"));else{const _={id:C.id,datasetType:C.type,name:C.name||C.table,label:C.label,domainId:C.domainId,description:C.description,database:C.database,schema:C.schema,type:"dataset",connectionId:C.connectionId,connectionType:C.connectionType,dialect:C.dialect,datamodelId:C.datamodelId,sql:C.sql};k=[...j,_]}n==null||n(k)},v=g.filter(C=>C.name.toLowerCase().includes(l.toLowerCase())),w=N.useCallback(()=>{if(!n||!(e!=null&&e.semanticDomainId))return;const C=r||[],D=v.filter(_=>!C.some(M=>M.id===_.id&&M.type==="dataset")).map(_=>({id:_.id,datasetType:_.type,name:_.name||_.table,label:_.label,domainId:_.domainId,description:_.description,database:_.database,schema:_.schema,type:"dataset",connectionId:_.connectionId,connectionType:_.connectionType,dialect:_.dialect,datamodelId:_.datamodelId,sql:_.sql})),k=[...C,...D];n(k)},[v,r,e==null?void 0:e.semanticDomainId,n]);return N.useEffect(()=>{a&&a(w)},[a,w]),c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium",children:"Semantic Domain"}),c.jsxs(rt,{value:(e==null?void 0:e.semanticDomainId)||"",onValueChange:d,disabled:h||o&&!!i,children:[c.jsx(Je,{className:"w-full",children:c.jsx(lt,{placeholder:h?"Loading semantic domains...":o&&i?"Loading domain...":"Select semantic domain...",children:((S=m.find(C=>C.id===(e==null?void 0:e.semanticDomainId)))==null?void 0:S.label)||"Select semantic domain"})}),c.jsx(et,{children:m.map(C=>c.jsx(pe,{className:"hover:bg-muted",value:C.id,children:c.jsxs("div",{className:"flex flex-col items-start",children:[c.jsx("span",{className:"font-medium",children:C.label}),c.jsx("span",{className:"text-xs",children:C.description})]})},C.id))})]}),p&&c.jsx($w,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(ce,{className:"text-sm font-medium text-gray-700",children:"Datasets"}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search datasets...",value:l,onChange:C=>u(C.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($w,{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(C=>{const j=r.some(D=>D.id===C.id&&D.type==="dataset");return c.jsxs("div",{className:"flex cursor-pointer items-start space-x-2 rounded p-2 hover:bg-gray-50",onClick:()=>y(C),children:[c.jsx(dn,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:D=>D.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(ce,{className:"cursor-pointer font-medium",children:C.label||C.name}),c.jsx("span",{className:"text-xs text-gray-500",children:C.description})]})]},C.label||C.name)})})]})]})]})}function TI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=qe(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=ur(),d=ee(M=>M.isVisualEditing),f=ee(M=>M.dashboard.aiContext),{setAiContext:h}=Yt(),p=N.useRef(null),[m,g]=N.useState(!1),b=i&&i.length>0,x=!b,y=b&&i.length===1?i[0]:void 0,v=N.useCallback(M=>{const R=M;u({...n,connectionId:(n==null?void 0:n.connectionId)||"",connectionType:(n==null?void 0:n.connectionType)||"",mode:R,selectedEntities:(n==null?void 0:n.selectedEntities)||[],...R!=="semanticDomain"&&{semanticDomainId:void 0}})},[n,u]),w=N.useCallback(M=>{u({...n,...M})},[n,u]);N.useEffect(()=>{b&&n.mode!=="semanticDomain"&&v("semanticDomain")},[b,n.mode,v]),N.useEffect(()=>{y&&!n.semanticDomainId&&w({semanticDomainId:y})},[y,n.semanticDomainId,w]),N.useEffect(()=>{e?l(s||[]):(p.current=null,g(!1))},[e,n==null?void 0:n.selectedEntities,r,u,s,n]);const S=M=>{const R=a.filter(O=>!(O.name===M.name&&O.type===M.type));l(R)},C=()=>{l([])},j=N.useCallback(M=>{l(M)},[]),D=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(M=>{p.current=M,g(!0)},[]);function _(){var M,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(M=a==null?void 0:a[0])==null?void 0:M.connectionId,T=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:T,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsx(Vr,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Hr,{className:"flex-shrink-0",children:[c.jsx(Ur,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Rs,{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(cs,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Wr,{className:"grid w-full grid-cols-2",children:[c.jsx(Ht,{value:"database",children:"Direct Source"}),c.jsx(Ht,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(vQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,allowedDomainIds:i||[],isRestricted:b,autoSelectedDomainId:y,onRegisterSelectAll:k}),(n==null?void 0:n.mode)==="database"&&x&&c.jsx(yQe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(uQe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ts,{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(oe,{variant:"outline",onClick:D,disabled:!m,children:"Select All"}),c.jsx(oe,{variant:"outline",onClick:C,disabled:a.length===0,children:"Clear All"}),c.jsxs(oe,{variant:"outline",onClick:()=>t(!1),children:[c.jsx(vt,{className:"mr-2 h-4 w-4"}),"Close"]}),c.jsxs(oe,{onClick:_,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function wQe({onFilesSelected:e,disabled:t=!1,currentFileCount:n=0,className:r}){const s=N.useRef(null),o=async a=>{const l=Array.from(a.target.files||[]);if(l.length===0)return;const u=Fa-n;if(l.length>u){$e.error(`You can only attach ${Fa} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=qQ(l);if(f.forEach(({file:h,error:p})=>{$e.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>xI(p)));e(h)}catch(h){console.error("Failed to process files:",h),$e.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>=Fa}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Fa,title:n>=Fa?`Maximum ${Fa} files allowed`:"Attach files",children:c.jsx(tD,{className:"h-4 w-4 text-muted-foreground"})})]})}function SQe({children:e,onFilesDropped:t,disabled:n=!1,currentFileCount:r=0,className:s}){const[o,i]=N.useState(!1),a=N.useCallback(f=>{f.preventDefault(),f.stopPropagation(),n||i(!0)},[n]),l=N.useCallback(f=>{f.preventDefault(),f.stopPropagation();const h=f.currentTarget.getBoundingClientRect(),p=f.clientX,m=f.clientY;(p<h.left||p>=h.right||m<h.top||m>=h.bottom)&&i(!1)},[]),u=N.useCallback(f=>{f.preventDefault(),f.stopPropagation()},[]),d=N.useCallback(async f=>{if(f.preventDefault(),f.stopPropagation(),i(!1),n)return;const h=Array.from(f.dataTransfer.files);if(h.length===0)return;const p=Fa-r;if(h.length>p){$e.error(`You can only attach ${Fa} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=qQ(h);if(g.forEach(({file:b,error:x})=>{$e.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>xI(x)));t(b),$e.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),$e.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:J("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(uD,{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:[Fa-r," slot(s) available"]})]})})]})}const RI=N.forwardRef(({input:e,setInput:t,handleInputChange:n,handleSubmit:r,isLoading:s,stop:o,onFocus:i,status:a,assistantType:l},u)=>{const[d,f]=N.useState(!1),[h,p]=N.useState(!1),[m,g]=N.useState(!1),b=N.useRef(null),x=Op();ENe(),kNe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=W1(),{queueMessage:C}=Fp(),{addFileAttachment:j,removeFileAttachment:D,clearFileAttachments:k,getFileAttachments:_}=ZM(),M=KM(l),R=Ee(H=>H.card.dataSource),O=ee(H=>H.dashboard.aiContext),T=ee(H=>{var q;return(q=H.dashboard.aiContext)==null?void 0:q.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const H=b.current;if(H){if(!e||e.length===0){H.style.height="10px";return}H.style.height="auto";const q=Math.min(Math.max(H.scrollHeight,10),200);H.style.height=`${q}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const H=setTimeout(()=>{I()},0);return()=>clearTimeout(H)},[I]);const F=()=>{const H=e.trim();!H&&M.length===0||(a!=="ready"?(C(l,H,M),t(""),k(l)):r({preventDefault:()=>{}}))},z=H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),F()),H.key==="@"&&(K(),f(!0))},B=N.useCallback(H=>{const q=OWe(H.nativeEvent);q.length>0&&(H.preventDefault(),q.forEach(async X=>{const Z=await xI(X);j(l,Z)}))},[j,l]),$=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),P=N.useCallback(H=>{H.forEach(q=>{j(l,q)})},[j,l]),V=N.useCallback(H=>{D(l,H)},[D,l]),L=H=>{if(x.selectedEntities.some(X=>X.id&&X.id===H.id||X.name===H.name)){const X=x.selectedEntities.filter(Z=>!(Z.id&&Z.id===H.id||Z.name===H.name));y({selectedEntities:X})}else{const X=[...x.selectedEntities,H];y({selectedEntities:X})}},A=H=>{L(H)},W=H=>{var Z;if(!x.selectedEntities.some(G=>G.id&&G.id===H.id||G.name===H.name)){const G=[...x.selectedEntities,H];y({selectedEntities:G})}const X="label"in H?H.label:H.name;t(e+`@${X} `),f(!1),(Z=b.current)==null||Z.focus()},U=H=>{const q=x.selectedEntities.filter(G=>!(G.id&&G.id===H.id||G.name===H.name));y({selectedEntities:q});const Z=`@${"label"in H?H.label:H.name}`;e.includes(Z)&&t(e.replace(Z,"").trim())},Y=H=>{const q=new Set(H.map(G=>G.id||G.name)),X=x.selectedEntities.filter(G=>!q.has(G.id||G.name));y({selectedEntities:X});let Z=e;H.forEach(G=>{const ne=`@${"label"in G?G.label:G.name}`;Z=Z.replace(ne,"").trim()}),t(Z)},K=N.useCallback(()=>{x.selectedEntities.length===0&&y({selectedEntities:(O==null?void 0:O.selectedEntities)||[]})},[x.selectedEntities.length,O==null?void 0:O.selectedEntities,y]);return c.jsxs(SQe,{onFilesDropped:$,currentFileCount:M.length,disabled:s,className:"space-y-4",children:[c.jsx(lQe,{entities:x.selectedEntities,availableEntities:T||[],onRemoveEntity:U,onRemoveEntities:Y}),M.length>0&&c.jsx(FWe,{files:M,onRemove:V,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:z,onPaste:B,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(Ns,{open:d,onOpenChange:H=>{H&&K(),f(H)},children:[c.jsx(js,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(cae,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(ks,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:H=>H.preventDefault(),children:c.jsx(iQe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var H;f(!1),(H=b.current)==null||H.focus()},availableEntities:T||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{T&&y({selectedEntities:T})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(wQe,{onFilesSelected:P,disabled:s,currentFileCount:M.length})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[s&&c.jsx(oe,{className:"rounded-full",size:"sm",onClick:o,children:c.jsx(kae,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&M.length===0,size:"sm",variant:a!=="ready"?"secondary":"default",onClick:F,title:a!=="ready"?"Message will be queued":void 0,children:c.jsx(L8,{className:"size-4"})})]})]})]}),c.jsx(TI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||JS,dialogMode:"aiContext"})]})});RI.displayName="ChatInputWithContext";function dee({assistantType:e,className:t}){const n=IW(e),{removeFromQueue:r}=Fp();return n.length===0?null:c.jsxs("div",{className:J("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(ul,{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(oe,{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(vt,{className:"h-3 w-3"})})]})},s.id))})]})}function fee({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=IW(e),{dequeueMessage:o}=Fp();N.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 hee(e,t={}){const{threshold:n=50,behavior:r="smooth",forceScrollOnStream:s=!0,isStreaming:o=!1}=t,i=N.useRef(null),[a,l]=N.useState(!0),[u,d]=N.useState(!0),[f,h]=N.useState(!1),[p,m]=N.useState(0),g=N.useRef(0),b=N.useRef(!1),x=N.useRef(0),y=N.useRef(a),v=N.useRef(),w=N.useRef({key:null,count:0,length:0}),S=N.useCallback(()=>{const k=i.current;return k?k.scrollHeight-k.scrollTop-k.clientHeight:0},[]),C=N.useCallback((k={})=>{if(!i.current)return;const{force:M=!1,instant:R=!1}=k;if(!M&&!y.current||!a&&!M)return;const O=R||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 T=i.current;if(!T){b.current=!1,v.current=void 0;return}const I=T.scrollHeight;O==="smooth"&&"scrollTo"in T?T.scrollTo({top:I,behavior:O}):T.scrollTop=I,g.current=T.scrollTop,d(!0),l(!0),y.current=!0,h(!1),m(0),b.current=!1,v.current=void 0})},[r,a]),j=N.useCallback(()=>{const k=i.current;if(!k)return;const _=g.current,M=k.scrollTop,R=M-_;if(g.current=M,R<-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 O=S()<=n;d(O),l(O),y.current=O,O&&(h(!1),m(0))},[S,n]),D=N.useCallback(()=>{m(0),h(!1)},[]);return N.useEffect(()=>{y.current=a},[a]),N.useEffect(()=>{const k=i.current;if(!k||!e||e.length===0){h(!1),m(0),w.current={key:null,count:0,length:0},g.current=k?k.scrollTop:0,x.current=k?k.scrollHeight:0;return}g.current=k.scrollTop,x.current=k.scrollHeight;const _=w.current,M=e[e.length-1],R=(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,O=Array.isArray(M==null?void 0:M.parts)?M.parts.reduce(($,P)=>P?typeof P=="string"?$+P.length:typeof P.text=="string"?$+P.text.length:typeof P.content=="string"?$+P.content.length:typeof P.value=="string"?$+P.value.length:$:$,0):typeof(M==null?void 0:M.content)=="string"?M.content.length:typeof(M==null?void 0:M.text)=="string"?M.text.length:0,T=e.length>_.count,I=R!==_.key,F=O>_.length,z=s&&(M==null?void 0:M.role)==="assistant"&&!T&&(I||F),B=o||z;if(w.current={key:R,count:e.length,length:O},a&&(T||I||F||B)){C({force:!1,instant:B});return}if(!a&&T){const $=e.length-_.count;$>0&&(h(!0),m(P=>P+$))}else!a&&F&&(h(!0),m($=>$>0?$:1))},[e,C,a,s,o]),N.useEffect(()=>{C({instant:!0})},[C]),N.useEffect(()=>{if(typeof ResizeObserver>"u")return;const k=i.current;if(!k)return;x.current=k.scrollHeight;const _=new ResizeObserver(()=>{const M=i.current;if(!M)return;const R=x.current,O=M.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return _.observe(k),()=>{_.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:D}}function pee(e,t={}){const{maxVisibleMessages:n=50,initialLoadCount:r=20,loadMoreCount:s=10}=t,[o,i]=N.useState(r),a=N.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=N.useCallback(()=>{i(h=>Math.min(h+s,n))},[s,n]),f=N.useCallback(()=>{i(r)},[r]);return N.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 mee(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:YQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const CQe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function NQe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Yw),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=pp(),y=N.useRef(null);ee(Ve=>Ve.dashboard.aiScopeTables),ee(Ve=>Ve.isDashboardEditing);const v=ee(Ve=>Ve.selectedSheetId),{setDataSource:w}=ur(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Yt(),D=Op(),{setCurrentAIContext:k,updateSelectedEntities:_,setReasoningEffort:M,setShowReasoning:R}=W1(),{clearQueue:O}=Fp(),{clearFileAttachments:T,getFileAttachments:I}=ZM(),F=KM("dashboard"),z=ee(Ve=>Ve.dashboard.aiContext),B=Ee(Ve=>Ve.card.dataSource),{assistantProfile:$}=iee(),P=ee(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:V,isLoading:L,messages:A,setMessages:W,status:U,stop:Y,errorMessage:K,clearError:H}=oQe(),q=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),X=N.useCallback(()=>{q(!g)},[g,q]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&q(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,q]);const[Z,G]=N.useState(""),Q=Ve=>{G(Ve.target.value)};function ne({sql:Ve,data:Ue,cardTitle:pt,connectionId:He,cardType:Ze,python:ve,cardConfig:je,dataSource:Te}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:pt,connectionId:He,cardType:Ze,python:ve,cardConfig:je,dataSource:Te}),!v)return;const ze={id:jr(),title:pt||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ze==="horizontalBar"?"y":"x"}},type:Ze,sql:Ve,python:ve,dataSource:Te,config:je,connectionId:He},nt={id:jr(),cards:[ze],activeCardId:ze.id};j(!0),S(v,nt,"end"),C(nt.id)}const ae=Ve=>{Ve.preventDefault();const Ue=Z.trim();if(!Ue&&F.length===0)return;const pt=[];Ue&&pt.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&pt.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),V({role:"user",parts:pt}),G(""),T("dashboard"),se({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),fee({assistantType:"dashboard",status:U,isLoading:L,sendMessage:V});const{hasActiveTools:ie}=mee(A),{visibleMessages:he,hasMoreMessages:be,totalMessageCount:Ce,loadMoreMessages:Oe,resetMessageWindow:ue}=pee(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:De,isAtBottom:Ie,hasNewMessages:ht,newMessageCount:xe,scrollToBottom:se,handleScroll:de,resetNewMessageCount:we}=hee(he,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ke();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};V(Ue)}function Pe(Ve){Ke(),V({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ke(),V({role:"user",parts:[{type:"text",text:Ve}]}),se({force:!0})}const Nt=N.useCallback(async()=>{const Ve=JSON.stringify(A??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(Ve),$e.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),$e.error("Unable to copy conversation")}},[A]);function Ke(){D.selectedEntities.length===0&&k({selectedEntities:(z==null?void 0:z.selectedEntities)||[]})}const Lt=(Z==null?void 0:Z.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ne(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Dt(){return c.jsxs(fp,{children:[c.jsx(hp,{asChild:!0,children:c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(rp,{className:"size-3.5"})})}),c.jsxs(qd,{align:"end",children:[c.jsx(Xf,{children:"Options"}),c.jsx(yd,{}),c.jsx(Zm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Zm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Zm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const hn=c.jsxs("div",{"data-role":"dashboard-assistant",className:J("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:[Ne(),P&&c.jsx(oe,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:P,children:($==null?void 0:$.name)||"Default Profile"}),c.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[x&&Dt(),a&&c.jsx(oe,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:Nt,children:"Copy Conversation"}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:X,children:g?c.jsx(eD,{className:"size-4"}):c.jsx(i1,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),H(),ue()},children:c.jsx(a1,{className:"size-4"})}),c.jsx(ic,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(yl,{"data-role":"dashboard-assistant-scroll-area",ref:De,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:de,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[be&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:Oe,className:"text-xs",children:["Load ",Math.min(5,Ce-he.length)," ","more messages (",Ce-he.length," ","hidden)"]})}),c.jsx(KQ,{showTools:a,showSystemMessage:u,messages:he,onAddToDashboard:ne,onQuickReply:Qe,disableQuickReplies:L}),!ie&&c.jsx(GQ,{status:U,errorMessage:K})]}),c.jsx(Zo,{orientation:"horizontal"})]}),e&&!Ie&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{se({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Ys,{className:"h-4 w-4"}),ht&&xe>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:xe>9?"9+":xe})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&Lt&&c.jsx(ZQ,{onClick:Se,placeholders:CQe}),c.jsx("div",{children:Lt&&$&&c.jsx(aee,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(dee,{assistantType:"dashboard",className:"mb-3"}),c.jsx(RI,{ref:y,setInput:G,stop:Y,input:Z,handleInputChange:Q,handleSubmit:Ve=>{Ke(),ae(Ve),se({force:!0})},isLoading:L,status:U,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(TI,{incomingSelectedEntities:(z==null?void 0:z.selectedEntities)||[],open:f,onOpenChange:h,dataSource:B||JS,dialogMode:"aiContext"})]});return g&&s?In.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:hn})}),s):hn}function jQe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Yt(),o=ee(d=>d.dashboard.sheets),a=ee(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=ee(d=>d.isDashboardEditing),u=ee(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),$e.success("Card copied to clipboard"),p.preventDefault()):m&&p.key==="v"&&(await h(),p.preventDefault())}async function f(){try{const p=n();p&&await navigator.clipboard.writeText(JSON.stringify(p))}catch(p){console.error("Failed to copy text:",p)}}async function h(){if(!a)return null;try{const p=await navigator.clipboard.readText();try{const m=JSON.parse(p);if(m!=null&&m.id){const g=sR(m),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),$e.success("Card pasted from clipboard")}}catch(m){console.error("Failed to parse clipboard contents: ",m)}return p}catch(p){return console.error("Failed to paste text:",p),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[r,n,s,a,l,u,t])}function kQe(e,t){switch(e.interactionMode){case"drillToDetail":EQe(e,t);break;case"drillThrough":_Qe(e,t);break;case"drillToURL":DQe(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 EQe(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 _Qe(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 DQe(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 MQe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(ls,{open:e,onOpenChange:t,children:c.jsxs(Vr,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Hr,{children:[c.jsx(Ur,{children:i||"Insight Detail"}),c.jsx(Rs,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(lZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(uZ,{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 TQe(){const e=Ft(w=>w.interactionStates),t=Ft(w=>w.setInteractionState),n=Ft(w=>w.clearLastInteractionEvent),r=Ft(w=>w.replaceCardWithInsight),s=Ft(w=>w.setPendingDrillThrough),o=Ft(w=>w.pendingDrillThrough),i=Ft(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Yt(),{selectDashboard:u}=Ab(),d=ee(w=>w.dashboard),f=ee(w=>w.filterValues),{data:h,isLoading:p}=Vfe((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=dZ(m.insightId,{enabled:m.open&&!!m.insightId}),x=N.useRef(new Set),y=N.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:w,filters:S,contextMode:C})=>{g({open:!0,insightId:w,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:C})},replaceCardContent:({cardId:w,insightId:S,filters:C,contextMode:j})=>{r(w,S,C,j)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:w,contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D})=>{const _={sourceCardId:na,interactionMode:"clickFilter",filterGroups:[{filters:w}]},M={...Ao(),appliedClickFilters:[_],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:D};t(na,M)}}),[a,r,f,l,d,s,t]);N.useEffect(()=>{Object.entries(e).forEach(([w,S])=>{if(S!=null&&S.lastInteractionEvent){const C=S.lastInteractionEvent,j=`${w}-${C.interactionMode}-${C.sourceCardId}-${Date.now()}`;if(x.current.has(j))return;x.current.add(j);try{kQe(C,y)}catch(D){console.error("Error executing interaction event:",D)}finally{n(w),setTimeout(()=>{x.current.delete(j)},5e3)}}})},[e,n,y]),N.useEffect(()=>{if(!(!o||!h||p))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,p,u,l,i]);const v=()=>{g({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(MQe,{open:m.open,onOpenChange:v,insightId:m.insightId,filters:m.filters,filterDefinitions:m.filterDefinitions,contextMode:m.contextMode,cardTitle:b.title,cardDescription:b.description}),o&&p&&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(On,{className:"h-8 w-8 animate-spin text-primary"}),c.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading dashboard..."})]})})]})}function RQe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=IQe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function IQe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function AQe(e){return e?`Back to ${e}`:"Back"}function PQe(){var x,y,v,w,S;const e=Ft(C=>C.interactionStates[na]),t=ee(C=>C.actions.goBackFromDrill),n=ee(C=>C.actions.clearDrillContext),{selectDashboard:r}=Ab(),[s,o]=N.useState({x:16,y:16}),[i,a]=N.useState(!1),l=N.useRef({x:0,y:0});N.useEffect(()=>{if(!i)return;const C=D=>{o({x:D.clientX-l.current.x,y:D.clientY-l.current.y})},j=()=>{a(!1)};return document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j)}},[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||!((S=e.appliedClickFilters)!=null&&S.length))return null;const p=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(C){console.error("[DrillBack] Error during back navigation:",C)}},m=()=>{n()},g=C=>{C.target.closest("button")||(a(!0),l.current={x:C.clientX-s.x,y:C.clientY-s.y})};RQe(f);const b=AQe(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((C,j)=>{const D=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[D," = ",k]},j)})})]}),c.jsx(oe,{variant:"ghost",size:"sm",onClick:m,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(vt,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(oe,{variant:"secondary",size:"sm",onClick:p,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(l8,{className:"mr-2 h-4 w-4"}),b]})})]})})}function gee(){var G;const{showAssistant:e,tokenProps:t}=qe(),{preferences:n,isConsoleMode:r}=pp(),s=((G=n==null?void 0:n.cardDisplay)==null?void 0:G.mode)==="print",o=N.useRef(null),i=N.useRef(null),[a,l]=N.useState(!1),u=sd(Q=>Q.setFullscreen),d=sd(Q=>Q.setPanelOpen),f=sd(Q=>Q.setContainer),h=DW("dashboard"),p=MW(),m=TW("dashboard"),g=h.isOpen,b=p==="dashboard",x=ee(Q=>Q.isVisualEditing),y=ee(Q=>Q.themeStyle),v=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.sheets}),w=ee(Q=>Q.isDashboardEditing),S=ee(Q=>Q.selectedSheetId),C=ee(Q=>{var ne;return(ne=Q.dashboard)==null?void 0:ne.id}),j=ee(Q=>Q.isDashboardPanelOpen),D=ee(Q=>Q.actions.setIsDashboardPanelOpen),{getDefaultSheetId:k,setDefaultSheetId:_,clearDefaultSheetId:M}=V6(C),[R,O]=N.useState(null);S1(At.DASHBOARD);const{setSelectedSheetId:T,setSheetTitle:I,addSheet:F,setSheets:z}=Yt();jQe(i);const{setActiveAssistantType:B}=W1();N.useEffect(()=>{if(C){const Q=k();O(Q)}},[C,k]),N.useEffect(()=>{g?B("dashboard"):p==="dashboard"&&u(null)},[g,B,p,u]);function $(Q){var ne,ae;Q?((ne=o.current)==null||ne.resize(40),d("dashboard",!0),B("dashboard")):(d("dashboard",!1),u(null),(ae=o.current)==null||ae.resize(0),B(null))}function P(){const Q={id:jr(),title:"New Sheet"};F(Q),T(Q.id)}function V(Q,ne){if(!C)return;R===Q?(M(),O(null),$e.success("Default sheet cleared")):(_(Q),O(Q),$e.success(`"${ne}" set as default sheet`))}function L(Q){Q<1?(d("dashboard",!1),u(null),B(null)):(g||d("dashboard",!0),B("dashboard"))}function A(){return(y==null?void 0:y.canvasTheme)==="muted"||!(y!=null&&y.canvasTheme)?"hsl(var(--semaphor-muted))":(y==null?void 0:y.canvasTheme)==="clear"?"":y==null?void 0:y.canvasTheme}const W=(Q,ne)=>{Q.dataTransfer.setData("tabIndex",ne.toString())},U=Q=>{Q.preventDefault()},Y=(Q,ne)=>{const ae=Q.dataTransfer.getData("tabIndex");if(ae===ne.toString())return;const ie=Array.from(v||[]),[he]=ie.splice(parseInt(ae),1);ie.splice(ne,0,he),z(ie)},K=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail;function H(){var Q,ne;if(v&&v.length>1||w)return c.jsxs(Wr,{role:"tab-list",className:"flex h-11 items-center justify-start gap-2 rounded-none border-b border-b-muted bg-transparent px-2.5 py-3",children:[r&&K&&c.jsx(oe,{variant:"outline","aria-label":"Manage Dashboards and Visuals",onClick:()=>{D(!j)},className:"h-8 p-2",children:j?c.jsx(v8,{className:"h-4 w-4"}):c.jsx(w8,{className:"h-4 w-4"})}),v==null?void 0:v.map((ae,ie)=>{const he=S===ae.id,be=R===ae.id;return c.jsxs(Ht,{draggable:!0,onDragStart:Ce=>W(Ce,ie),onDragOver:U,onDrop:Ce=>Y(Ce,ie),style:{borderRadius:y==null?void 0:y.controlInputRadius},onClick:()=>T(ae.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:ae.id,children:[c.jsx(tb,{enabled:w&&he,text:ae.title,onSave:Ce=>I(ae.id,Ce),children:ae.title},ae.id),!w&&he&&c.jsx("div",{title:be?"Clear default sheet":"Set as default sheet",children:c.jsx(oD,{className:J("ml-1 size-3 cursor-pointer transition-all",be?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:Ce=>{Ce.stopPropagation(),V(ae.id,ae.title||"Sheet")}})}),w&&he&&v.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>l(!0)})]},ae.id)}),w&&c.jsx("div",{style:{borderRadius:(ne=(Q=y==null?void 0:y.chart)==null?void 0:Q.options)==null?void 0:ne.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:P,children:c.jsx(kr,{className:"size-3"})})]})}function q(){return c.jsx("div",{ref:i,style:{},className:"grow",children:v==null?void 0:v.map(Q=>c.jsx(Gn,{style:{backgroundColor:A()},className:J("mt-0",{}),value:Q.id,children:c.jsx(X6e,{sheet:Q})},Q.id))})}function X(){var Q;return c.jsxs(cs,{"data-role":"dashboard-tabs-container",className:J("relative flex h-full flex-col",y==null?void 0:y.dashboardTabsContainer),onValueChange:ne=>{T(ne)},value:S||((Q=v==null?void 0:v[0])==null?void 0:Q.id),children:[H(),c.jsx(yl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:q()}),c.jsx(M8e,{open:a,setOpen:l})]})}const Z=N.useCallback(Q=>{f("dashboard",Q)},[f]);return v?c.jsxs(c.Fragment,{children:[c.jsx(TQe,{}),c.jsx(PQe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(TX,{className:J("flex-1 basis-0 overflow-y-auto transition-opacity",b&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(HE,{children:X()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(D8e,{open:g,onTabClick:$,withHandle:!0}),c.jsx(HE,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:L,defaultSize:g?40:0,ref:o,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(NQe,{open:g,setOpen:$,isFullscreen:b,onFullscreenChange:Q=>u(Q?"dashboard":null),fullscreenContainer:m})})})]})]}),c.jsx("div",{ref:Z,className:J("absolute inset-0",!b&&"pointer-events-none")}),e===!0&&!s&&!g&&!x&&c.jsx("div",{className:"fixed bottom-6 right-6 z-50",children:c.jsx(oe,{size:"sm",variant:"outline",className:"h-12 w-12 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>$(!0),title:"Open Assistant",children:c.jsx(sD,{className:"h-5 w-5"})})})]})]}):null}function II({children:e}){return c.jsx(va,{style:{height:"100%",width:"100%"},children:c.jsx(dse,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(Yn,{delayDuration:0,children:e})})})}function bee({children:e,preferences:t}){const{currentUser:n}=Ms(),r=N.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(R9.Provider,{value:r,children:c.jsx(jR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function xee(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(wl,{FallbackComponent:hS,children:c.jsx(V_,{dashboardProps:e,children:c.jsx(II,{children:c.jsx(bee,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(XM,{...e,type:"dashboard",children:c.jsx(gee,{})})})})})})})}function AI(e){const{tokenProps:t,authToken:n}=qe(),r=t==null?void 0:t.apiServiceUrl;return un({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return Vn(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 yee(e,t,n){if(t==="source")return{isValid:!0};const r=Ks(e.dataType);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 vee(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 wee=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=AI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=ur(),h=Ee(T=>T.card.type),p=e==null?void 0:e.id,m=N.useCallback(T=>{if(!(e!=null&&e.config))return[];switch(T){case"groupBy":return(e.config.groupByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,dateFormat:I.dateFormat,customFormat:I.customFormat,granularity:I.granularity}));case"metrics":return e.config.metricColumns||[];case"pivotBy":return(e.config.pivotByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(I=>({id:I.id,name:I.name,dataType:I.dataType,label:I.label!==void 0?I.label:I.name,qualifiedEntityName:I.qualifiedEntityName,entityId:I.entityId,entityName:I.entityName,entityType:I.entityType,direction:I.direction}));case"source":return[];default:return[]}},[e]),g=N.useCallback((T,I)=>{if(p)switch(T){case"groupBy":{r(p,{groupByColumns:I});break}case"metrics":{r(p,{metricColumns:I});break}case"pivotBy":{r(p,{pivotByColumns:I});break}case"sortBy":{r(p,{sortByColumns:I});break}}},[p,r]),b=N.useCallback((T,I,F)=>{if(!p)return;const B=m(T)[I];if(B)switch(T){case"groupBy":s(p,B.id,{label:F});break;case"metrics":o(p,B.id,{label:F});break;case"pivotBy":i(p,B.id,{label:F});break;case"sortBy":a(p,B.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aggregate:I,label:aU(z.name,I)})},[p,m,o]),y=N.useCallback((T,I,F)=>{if(!p)return;const B=m("groupBy")[T];if(!B)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,B.id,$)},[p,m,s]),v=N.useCallback((T,I)=>{if(!p)return;const z=m("groupBy")[T];z&&s(p,z.id,{granularity:I})},[p,m,s]),w=N.useCallback((T,I)=>{if(!p)return;const z=m("metrics")[T];z&&o(p,z.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((T,I)=>{if(console.log("handleValueAliasesChange",T,I),!p)return;console.log("handleValueAliasesChange",T,I);const z=m("metrics")[T];z&&(console.log("handleValueAliasesChange",I),o(p,z.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(T=>{if(!p)return;if(m("metrics").length===0){$e.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:T})},[p,r,m]),j=N.useCallback(T=>{p&&r(p,{showTrendline:T})},[p,r]),D=N.useCallback(T=>{p&&r(p,{trendlineWindow:T})},[p,r]),k=N.useCallback(T=>{p&&r(p,{trendlineGranularity:T})},[p,r]),_=N.useCallback(T=>{p&&r(p,{targetValue:T})},[p,r]),M=N.useCallback(T=>{var V;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=XSe(T,I,{joinPlan:(V=e==null?void 0:e.config)==null?void 0:V.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&sU();return}const z=eCe(T,I,h);if(!z){$e.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const B=yee(T,z,h);if(!B.isValid){$e.error("Invalid Field Type",{description:B.reason,position:"top-center",duration:3e3});return}const $=m(z);if(oU(T,$))return;const P=lU(T,z,$);if(P){const L=[...$,P];g(z,L),z==="metrics"&&vee(h,e==null?void 0:e.config,r,p,L)}},[p,e==null?void 0:e.config,m,g,t,n,h,r]),R=N.useCallback((T,I)=>{if(!p)return;const z=m(T)[I];if(z){if(T!=="sortBy"){const B=m("sortBy"),$=B.filter(P=>!(P.name===z.name&&P.qualifiedEntityName===z.qualifiedEntityName));$.length!==B.length&&r(p,{sortByColumns:$})}switch(T){case"groupBy":l(p,z.id);break;case"metrics":u(p,z.id);break;case"pivotBy":d(p,z.id);break;case"sortBy":f(p,z.id);break}}},[p,m,l,u,d,f,r]);return{getFieldsForContainer:m,setFieldsForContainer:g,updateLabel:b,handleAggregationChange:x,handleDateFormatChange:y,handleGranularityChange:v,handleAliasTemplateChange:w,handleValueAliasesChange:S,removeField:R,handleFieldClick:M,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:D,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:_,cardType:h}};function Fx(e,t){var Pe,Qe,Nt,Ke,Lt;const{tokenProps:n}=qe(),r=Zs(),s=qe().authToken||e,o=Ee(Ne=>Ne.selectedConnectionId),i=Ee(Ne=>Ne.card),{queryKey:a}=Wpe(i),l=Ee(Ne=>Ne.selectedDatamodelId),u=Ee(Ne=>Ne.isDevMode),d=Ee(Ne=>Ne.selectedDatabaseName),f=Ee(Ne=>Ne.selectedSchemaName),h=Ee(Ne=>Ne.selectedTableName),p=Ee(Ne=>Ne.actions.setSelectedConnectionId),m=Ee(Ne=>Ne.actions.setSelectedDatamodelId),g=Ee(Ne=>Ne.actions.setSelectedDatabaseName),b=Ee(Ne=>Ne.actions.setSelectedSchemaName),x=Ee(Ne=>Ne.actions.setSelectedTableName);Ee(Ne=>Ne.actions.setCardSql);const{setQueryConfig:y}=ur();function v(Ne){var hn;return o&&Ne==="API"?!1:o&&Ne==="S3"?!0:!(!o||!d||d==="NA"||((hn=k==null?void 0:k.capabilities)==null?void 0:hn.path.includes("schema"))&&!f)}function w(Ne){return o&&Ne?!(Ne==="API"||Ne==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:D,selectedConnection:k}=Ii(e),{refetch:_,data:M,isLoading:R,isError:O}=un({queryKey:["models",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),T=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:z,isFetching:B,isError:$,refetch:P}=un({queryKey:["databases",o],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(T)}),{data:V,isLoading:L,isFetching:A,isError:W,refetch:U}=un({queryKey:["schemas",o,d],queryFn:()=>Vn(`${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:K,isFetching:H,isError:q,refetch:X}=un({queryKey:["tables",o,d,f],queryFn:()=>Vn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(T)}),{columns:Z,isColumnsLoading:G,isColumnsFetching:Q,isColumnsError:ne,refetchColumns:ae}=cU(e);N.useEffect(()=>{(T==="S3"||T==="API")&&(g(""),b(""),m(""),T==="API"&&x("api"))},[T,x,g,b,m]);const ie=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",he=I?"":f||"";function be(Ne){x(Ne),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(Ne){b(Ne),x("")}function Oe(Ne){g(Ne==="none"?"":Ne),b(""),x(""),Ne!=="none"&&Ne!==""&&m("")}function ue(Ne){p(Ne)}function De(Ne){m(Ne==="none"?"":Ne),Ne!=="none"&&Ne!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,V&&((Nt=V==null?void 0:V.schemas)==null?void 0:Nt.length)>0;const Ie=C==null?void 0:C.connections.map(Ne=>({id:Ne.id,name:Ne.name,type:Ne.type})),ht=(Ke=M==null?void 0:M.datamodels)==null?void 0:Ke.map(Ne=>({id:Ne.id,name:Ne.name})),xe=F==null?void 0:F.databases.map(Ne=>({id:Ne.database_name,name:Ne.database_name})),se=V==null?void 0:V.schemas.map(Ne=>({id:Ne.schema_name,name:Ne.schema_name})),de=Y==null?void 0:Y.tables.map(Ne=>({id:Ne.table_name,name:Ne.table_name})),we=(Lt=M==null?void 0:M.datamodels.find(Ne=>Ne.id===l))==null?void 0:Lt.name,Se=Xy({schemaName:he,tableName:ie,modelName:we,connectionType:T,databaseName:d||""});return{connectionItems:Ie,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:D,modelItems:ht,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:xe,isDatabasesLoadingOrFetching:z||B,isDatabaseError:$,schemaItems:se,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:de,selectedTableName:h,isTableLoadingOrFetching:K||H,isTableError:q,columns:Z,isColumnsLoadingOrFetching:G||Q,isColumnsError:ne,isNonDbConnection:I,connectionType:T,tableName:ie,formattedTableName:Se,schemaName:he,refetchConnections:S,refetchModels:_,refetchDatabases:P,refetchSchemas:U,refetchTables:X,refetchColumns:ae,handleConnectionChange:ue,handleDatamodelChange:De,handleDatabaseChange:Oe,handleSchemaChange:Ce,handleTableChange:be}}function gy(e){return`${e}-${jr()}`}function CL(e,t){const n=Yo(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 OQe(e,t){const n=Yo(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 PI(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 See(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Cee(){const e=Ee(C=>C.sqlGen),t=Ee(C=>C.isDevMode),n=Ee(C=>C.card.dataSource),r=Ee(C=>{var j,D;return(D=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:D.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=PI(n),a=See(n),l=Ee(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=ur(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Fx(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var D;if(!t)return;const j=y(C);if(t&&a&&s){const k=R_(j,e);p(k);const _=(D=b==null?void 0:b.find(R=>R.id===l))==null?void 0:D.name,M=T_(k,fi(o||""),fi(s),_||"",g,i||"");M&&(f(M),h(!0))}else if(!t){if(Rb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:gy(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:gy(j.column_name),name:j.column_name,label:CL(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Lc(j.data_type)){const k={...j,role:"groupby",id:gy(j.column_name),name:j.column_name,type:j.data_type,label:OQe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:gy(j.column_name),name:j.column_name,label:CL(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(k)}}},handleShowSample:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Xy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});m(!1);const j=g==="MSSQL"?`SELECT top 10 * FROM ${C}`:`SELECT * FROM ${C} LIMIT 10`;f(j),h(!0)},handleShowCount:()=>{if(!a||!s){console.warn("Cannot generate SQL: missing table metadata");return}const C=Xy({schemaName:o||"",tableName:s,modelName:x,connectionType:g,databaseName:i||""});f(`SELECT COUNT(*) as count FROM ${C}`),h(!0)},isNumberField:C=>Vo(C.dataType)}}function Nee(){const e=Ee(m=>m.selectedConnectionId),t=Ee(m=>m.selectedDatamodelId),n=Ee(m=>m.selectedDatabaseName),r=Ee(m=>m.selectedSchemaName),s=Ee(m=>m.selectedTableName),o=ee(m=>m.dashboard.filters)||[],i=ee(m=>m.selectedSheetId),a=ee(m=>m.actions.addFilter),l=ee(m=>m.actions.removeFilter),{removeFilterValues:u}=Yt(),{modelItems:d,tableName:f,connectionType:h}=Fx();function p(m,g="sheet",b){var k;const x=fi(m.column_name),y=fi(n||""),v=fi(r||""),w=fi(f);let S=Gw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(_=>_.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${jg}.${j}.${x}`,S=`${jg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let D;if(g==="sheet"&&i?D=Dke(o,C,w,n||"",y,i):D=o==null?void 0:o.find(_=>_.column===C&&_.table===w&&(_.database===y||_.database===n)),D)u(D.id),l(D.id);else{const _=jr(),M=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:_,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:M,sql:W4(m.data_type,S,x)}),_):(a({id:_,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:M,sql:W4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),_)}}return{assignFilter:p}}function FQe({column:e}){const[t,n]=N.useState(!1),r=Ee(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=PI(r),a=Ee(x=>x.selectedDatamodelId),l=Ee(x=>x.sqlGen),{modelItems:u,connectionType:d}=Fx(),f=Ee(x=>x.actions.setSqlGen),h=Ee(x=>x.actions.setCardSql),p=Ee(x=>x.actions.setRunSql),m=See(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=R_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=T_(v,fi(o||""),fi(s),w||"",d,i||"");S&&(h(S),p(!0)),n(!1)}function b(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>g(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>g(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>g(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>g(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>g(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return m?c.jsxs(Ip,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(Ap,{asChild:!0,children:c.jsx(rp,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Jd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function $Qe({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 LQe({field:e,context:t="editor",fieldState:n}){const r=Ee(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=ee(L=>L.dashboard.filters),a=ee(L=>L.selectedSheetId),l=ee(L=>L.actions.removeFilter),{removeFilterValues:u}=Yt(),{assignFilter:d}=Nee(),f=s?Zc(i,a):i,h=s?f==null?void 0:f.find(L=>{var A;return L.title===e.name||((A=L.column)==null?void 0:A.includes(e.name))}):void 0,p=!!h,m=h&&s?i==null?void 0:i.find(L=>L.id===h.id):void 0,g=m&&(m.applyToSheetIds&&m.applyToSheetIds.length>1||m.excludeSheetIds&&m.excludeSheetIds.length>0||!m.applyToSheetIds&&!m.excludeSheetIds&&!m.sheetId);s&&p&&console.log("[SourceField Debug]",{fieldName:e.name,hasActiveFilter:p,activeFilterOnSheet:h?{id:h.id,title:h.title,column:h.column,applyToSheetIds:h.applyToSheetIds,excludeSheetIds:h.excludeSheetIds}:null,activeFilterForField:m?{id:m.id,title:m.title,column:m.column,applyToSheetIds:m.applyToSheetIds,excludeSheetIds:m.excludeSheetIds}:null,isMultiSheetFilter:g,selectedSheetId:a});const[b,x]=N.useState(!1),[y,v]=N.useState(null),{attributes:w,listeners:S,setNodeRef:C,transform:j,transition:D,isDragging:k}=IS({id:e.id,disabled:o}),[_,M]=N.useState(!1),R=Ee(L=>L.card),{handleFieldClick:O}=wee(R),{handleDevModeFieldClick:T,isNumberField:I}=Cee(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},z=()=>{if(s){const L={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description,qualifiedFieldName:e.qualifiedFieldName};p&&g?(v({column:L,field:e}),x(!0)):d(L,"sheet",e)}else r?T(e):O(e)},B={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:_i.Transform.toString(j),transition:D},V=(()=>{if(!n||s)return{};const A={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",...A},draggable:{borderColor:"border-green-300/30 dark:border-green-700/30",bgColor:"bg-green-50/20 dark:bg-green-950/10",...A},indirect:{borderColor:"border-yellow-300/30 dark:border-yellow-700/30",bgColor:"bg-yellow-50/20 dark:bg-yellow-950/10",...A}}[n.state]||A})();return c.jsxs("div",{ref:C,style:$,...o?{}:w,...o?{}:S,className:J("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",V.borderColor||"border-transparent",V.bgColor||"",V.hoverBorderColor,V.hoverBgColor||"hover:bg-muted",V.opacity,V.cursor,p&&"border-accent-foreground/20 bg-accent",{"cursor-pointer":r||s,"cursor-grab active:cursor-grabbing":!o&&!r&&!s}),title:n==null?void 0:n.tooltip,children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-3 p-2",onClick:z,children:[ib(e.dataType),c.jsx(Yn,{children:c.jsxs(bn,{children:[c.jsx(xn,{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 ${_?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(Cn,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx($Qe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(FQe,{column:B})})]}),_&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Si,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(z8,{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(Mae,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"break-all",children:e.name})]}),c.jsx(Fe,{variant:"outline",className:"mt-2 text-xs",children:e.dataType})]})})}),c.jsx(Wb,{open:b,onOpenChange:x,children:c.jsxs(mp,{children:[c.jsxs(gp,{children:[c.jsx(xp,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(yp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(bp,{children:[c.jsx(wp,{children:"Cancel"}),c.jsx(vp,{onClick:F,children:"Remove Filter"})]})]})})]})}const zQe="SEMAPHOR_CALCULATED_FIELD",BQe=["MM-DD-YYYY","YYYY-MM-DD","MM/DD/YYYY","DD/MM/YYYY","MMMM DD, YYYY","MMM DD, YYYY","DD MMM YYYY","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 jee(e){return!!e.expression}function VQe(e){return!!e.expression}function HQe(e){return!!e.expression}var kee=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(kee||{}),jl="Accordion",UQe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[OI,WQe,qQe]=l1(jl),[rC]=_r(jl,[qQe,mZ]),FI=mZ(),Eee=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(OI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(ZQe,{...o,ref:t}):c.jsx(KQe,{...s,ref:t})})});Eee.displayName=jl;var[_ee,YQe]=rC(jl),[Dee,GQe]=rC(jl,{collapsible:!1}),KQe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=$r({prop:n,defaultProp:r,onChange:s});return c.jsx(_ee,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Dee,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Mee,{...i,ref:t})})})}),ZQe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=$r({prop:n,defaultProp:r,onChange:s}),l=N.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=N.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(_ee,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Dee,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Mee,{...o,ref:t})})})}),[XQe,sC]=rC(jl),Mee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=N.useRef(null),l=ft(a,t),u=WQe(n),f=Vd(s)==="ltr",h=ke(e.onKeyDown,p=>{var D;if(!UQe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var _;return!((_=k.ref.current)!=null&&_.disabled)}),b=g.findIndex(k=>k.ref.current===m),x=g.length;if(b===-1)return;p.preventDefault();let y=b;const v=0,w=x-1,S=()=>{y=b+1,y>w&&(y=v)},C=()=>{y=b-1,y<v&&(y=w)};switch(p.key){case"Home":y=v;break;case"End":y=w;break;case"ArrowRight":o==="horizontal"&&(f?S():C());break;case"ArrowDown":o==="vertical"&&S();break;case"ArrowLeft":o==="horizontal"&&(f?C():S());break;case"ArrowUp":o==="vertical"&&C();break}const j=y%x;(D=g[j].ref.current)==null||D.focus()});return c.jsx(XQe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(OI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Lw="AccordionItem",[QQe,$I]=rC(Lw),Tee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=sC(Lw,n),i=YQe(Lw,n),a=FI(n),l=nr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(QQe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(xZ,{"data-orientation":o.orientation,"data-state":Fee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Tee.displayName=Lw;var Ree="AccordionHeader",Iee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(jl,n),o=$I(Ree,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":Fee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Iee.displayName=Ree;var h_="AccordionTrigger",Aee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(jl,n),o=$I(h_,n),i=GQe(h_,n),a=FI(n);return c.jsx(OI.ItemSlot,{scope:n,children:c.jsx(e$e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Aee.displayName=h_;var Pee="AccordionContent",Oee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=sC(jl,n),o=$I(Pee,n),i=FI(n);return c.jsx(t$e,{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}})});Oee.displayName=Pee;function Fee(e){return e?"open":"closed"}var JQe=Eee,eJe=Tee,tJe=Iee,$ee=Aee,Lee=Oee;const zee=JQe,LI=E.forwardRef(({className:e,...t},n)=>c.jsx(eJe,{ref:n,className:J("border-b",e),...t}));LI.displayName="AccordionItem";const zI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(tJe,{className:"flex",children:c.jsxs($ee,{ref:r,className:J("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(Ys,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));zI.displayName=$ee.displayName;const BI=E.forwardRef(({className:e,children:t,...n},r)=>c.jsx(Lee,{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:J("pb-4 pt-0",e),children:t})}));BI.displayName=Lee.displayName;function nJe({context:e="editor"}={}){var _,M,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");Ee(T=>T.isDevMode);const o=Ee(T=>T.card.dataSource),i=Ee(T=>T.card.config),a=Ee(T=>T.card),{autoJoinMetadata:l}=fa(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=IM(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=AI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(M=(_=i==null?void 0:i.joinPlan)==null?void 0:_.baseEntity)==null||M.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,Cee();const b=u.filter(T=>T.name.toLowerCase().includes(t.toLowerCase())||T.dataType.toLowerCase().includes(t.toLowerCase())||T.label&&T.label.toLowerCase().includes(t.toLowerCase())||T.qualifiedEntityName&&T.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=T=>{if(T.role==="metric"&&jee(T)||T.role==="groupby"&&T.expression)return"calculated";if(T.dataType==="number"||T.dataType==="integer"||T.dataType==="float"||T.dataType==="decimal"||T.dataType==="currency")return"metrics";const I=Ks(T.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(T=>x(T)===r)).reduce((T,I)=>{const F=I.qualifiedEntityName||"Other Fields";return T[F]||(T[F]={label:P_(I.entityName),fields:[]}),T[F].fields.push(I),T},{}),S=Object.keys(v),C=b.filter(T=>x(T)==="dimensions").length,j=b.filter(T=>x(T)==="metrics").length,D=b.filter(T=>x(T)==="calculated").length,k=b.length>0;return f?c.jsx("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:c.jsx(_c,{size:"md",color:"muted","aria-label":"Loading data"})}):h?c.jsxs("div",{className:"flex h-full w-[290px] flex-col items-center justify-center",children:[c.jsx(rl,{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:h.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?c.jsx(Ds,{className:"h-[calc(100vh-200px)] w-[290px]",children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx(rl,{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:e==="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"})]})}):c.jsxs("div",{className:"mt-2 flex h-full w-full grow flex-col gap-2 px-6 pb-6",children:[c.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[u.length>0&&c.jsxs("div",{className:"relative mb-4",children:[c.jsx(ba,{className:"absolute left-3 top-1/2 size-3.5 -translate-y-1/2 transform text-muted-foreground"}),c.jsx(Bn,{className:"pl-10 pr-10",type:"text",placeholder:"Search fields...",value:t,onChange:T=>n(T.target.value)}),t&&c.jsx("button",{className:"absolute right-3 top-1/2 -translate-y-1/2 transform text-muted-foreground hover:text-foreground",onClick:()=>n(""),type:"button",children:c.jsx(vt,{className:"size-3.5"})})]}),k&&c.jsx(cs,{defaultValue:"all",value:r,onValueChange:T=>s(T),className:"mb-4",children:c.jsxs(Wr,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ht,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ht,{value:"dimensions",className:"text-xs",children:[c.jsx(o1,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ht,{value:"metrics",className:"text-xs",children:[c.jsx(np,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ht,{value:"calculated",className:"text-xs",children:[c.jsx(K_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]})]})})]}),c.jsxs(yl,{className:"py-2",children:[c.jsx(zee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([T,I])=>{const F=d.find(z=>z.entityName===T)||{entityName:T,label:I.label};return c.jsxs(LI,{value:T,className:"border-none",children:[c.jsx(zI,{className:"group rounded-md px-2.5 py-2 text-muted-foreground hover:bg-muted hover:no-underline",children:c.jsxs("div",{title:F.label||F.entityName,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||F.entityName}),c.jsx(Fe,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:I.fields.length})]})}),c.jsx(BI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(z=>{const B=AM(z,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(LQe,{field:z,context:e,fieldState:B},z.id)})})})]},T)})}),Object.keys(v).length===0&&u.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:e==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),Object.keys(v).length===0&&u.length>0&&c.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),c.jsx(Zo,{orientation:"horizontal"}),c.jsx(Zo,{orientation:"vertical"})]})]})}function Bee({context:e="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(nJe,{context:e})," "]})}function Vee(){const e=Ee(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=ur();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=PI(e),d=(p=e.selectedEntities)==null?void 0:p[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 rJe(){Vee();const e=ee(l=>l.selectedSheetId),t=ee(l=>l.selectedFrameId),n=ee(l=>l.dashboard),r=ee(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Yt(),{setCard:o}=ur(),i=Ee(l=>l.card.dataSource);return N.useEffect(()=>{var u,d;let l=r();if(!l){const f=(u=n==null?void 0:n.sheets)==null?void 0:u.find(p=>p.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 sJe(){const e=ee(n=>n.actions.setShowFilters),{hasEntities:t}=rJe();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(ce,{className:"px-2 text-base",children:"Dashboard Filters"}),c.jsx(oe,{onClick:()=>e(!1),className:"h-7 w-7 p-0",variant:"ghost",children:c.jsx(hZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(rl,{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(TS,{collisionDetection:ES,children:c.jsx(RS,{items:[],strategy:zR,children:c.jsx(Bee,{context:"filter"})})})})]})}function oJe(){const e=ee(r=>r.dashboard.filters),t=ee(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:J("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(ER,{filter:r}),c.jsx(CS,{filter:r})]},r.id))}):null}function iJe(){const e=ee(r=>r.showFilters),t=ee(r=>r.isVisualEditing),n=ee(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:J("",{"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(oJe,{}),c.jsx(gee,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex overflow-hidden",children:c.jsx(sJe,{})})]})}const aJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CzcAbxpr.js"))),lJe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-D6KBQgRc.js"))),cJe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BQPFtG3z.js"))),uJe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-BNDpfKQl.js")).then(e=>({default:e.ResourceManagementPanel})));function dJe({showControls:e=!1,showFooter:t=!0,...n}){const r=ee(l=>l.isDashboardPanelOpen),s=ee(l=>l.isVisualEditing),o=ee(l=>l.showDashboardJSON),i=ee(l=>l.actions.setIsDashboardPanelOpen),{preferences:a}=n;return c.jsx(wl,{FallbackComponent:hS,children:c.jsxs(V_,{dashboardProps:n,children:[c.jsx(sfe,{}),c.jsx(II,{children:c.jsxs(bee,{preferences:a,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(cJe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(aJe,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(uJe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(XM,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(lJe,{})}),c.jsx(iJe,{})]})})]})]})]})})]})})}var fJe=Object.defineProperty,hJe=(e,t,n)=>t in e?fJe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,by=(e,t,n)=>hJe(e,typeof t!="symbol"?t+"":t,n);const pJe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},mJe={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}},gJe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},bJe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},xJe={stringify:e=>e,parse:e=>e},ej={string:xJe,number:bJe,boolean:pJe,function:mJe,json:gJe};function yJe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const xy=Symbol.for("r2wc.render"),yy=Symbol.for("r2wc.connected"),gu=Symbol.for("r2wc.context"),Ma=Symbol.for("r2wc.props");function vJe(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 p of i){l[p]=Array.isArray(t.props)?"string":t.props[p];const m=yJe(p);d[p]=m,f[m]=p}for(const p of a)u[p]=Array.isArray(t.events)?{}:t.events[p];class h extends HTMLElement{constructor(){super(),by(this,o,!0),by(this,s),by(this,r,{}),by(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ma].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?ej[x]:null;y!=null&&y.parse&&b&&(this[Ma][m]=y.parse(b,g,this))}for(const m of a)this[Ma][m]=g=>{const b=m.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(b,{detail:g,...u[m]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[yy]=!0,this[xy]()}disconnectedCallback(){this[yy]=!1,this[gu]&&n.unmount(this[gu]),delete this[gu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?ej[y]:null;x in l&&v!=null&&v.parse&&b&&(this[Ma][x]=v.parse(b,m,this),this[xy]())}[(o=yy,s=gu,r=Ma,xy)](){this[yy]&&(this[gu]?n.update(this[gu],this[Ma]):this[gu]=n.mount(this.container,e,this[Ma]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[Ma][p]},set(b){this[Ma][p]=b;const x=g?ej[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[xy]()}})}return h}function wJe(e,t,n){const r=hj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function SJe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function CJe({root:e}){e.unmount()}function NJe(e,t={}){return vJe(e,t,{mount:wJe,update:SJe,unmount:CJe})}const jJe={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"},kJe=NJe(xee,{props:jJe});function EJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function NL(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 jL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?NL(Object(n),!0).forEach(function(r){EJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):NL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function _Je(e,t){if(e==null)return{};var n={},r=Object.keys(e),s,o;for(o=0;o<r.length;o++)s=r[o],!(t.indexOf(s)>=0)&&(n[s]=e[s]);return n}function DJe(e,t){if(e==null)return{};var n=_Je(e,t),r,s;if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(s=0;s<o.length;s++)r=o[s],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function MJe(e,t){return TJe(e)||RJe(e,t)||IJe(e,t)||AJe()}function TJe(e){if(Array.isArray(e))return e}function RJe(e,t){if(!(typeof Symbol>"u"||!(Symbol.iterator in Object(e)))){var n=[],r=!0,s=!1,o=void 0;try{for(var i=e[Symbol.iterator](),a;!(r=(a=i.next()).done)&&(n.push(a.value),!(t&&n.length===t));r=!0);}catch(l){s=!0,o=l}finally{try{!r&&i.return!=null&&i.return()}finally{if(s)throw o}}return n}}function IJe(e,t){if(e){if(typeof e=="string")return kL(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set")return Array.from(e);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return kL(e,t)}}function kL(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function AJe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1067
1067
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function PJe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function EL(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 _L(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?EL(Object(n),!0).forEach(function(r){PJe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):EL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function OJe(){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 Gm(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 zw(e){return{}.toString.call(e).includes("Object")}function FJe(e){return!Object.keys(e).length}function Sb(e){return typeof e=="function"}function $Je(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function LJe(e,t){return zw(t)||mc("changeType"),Object.keys(t).some(function(n){return!$Je(e,n)})&&mc("changeField"),t}function zJe(e){Sb(e)||mc("selectorType")}function BJe(e){Sb(e)||zw(e)||mc("handlerType"),zw(e)&&Object.values(e).some(function(t){return!Sb(t)})&&mc("handlersType")}function VJe(e){e||mc("initialIsRequired"),zw(e)||mc("initialType"),FJe(e)&&mc("initialContent")}function HJe(e,t){throw new Error(e[t]||e.default)}var UJe={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"},mc=Gm(HJe)(UJe),vy={changes:LJe,selector:zJe,handler:BJe,initial:VJe};function WJe(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};vy.initial(e),vy.handler(t);var n={current:e},r=Gm(GJe)(n,t),s=Gm(YJe)(n),o=Gm(vy.changes)(e),i=Gm(qJe)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return vy.selector(u),u(n.current)}function l(u){OJe(r,s,o,i)(u)}return[a,l]}function qJe(e,t){return Sb(t)?t(e.current):t}function YJe(e,t){return e.current=_L(_L({},e.current),t),t}function GJe(e,t,n){return Sb(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:WJe},ZJe={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function XJe(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 QJe(e){return{}.toString.call(e).includes("Object")}function JJe(e){return e||DL("configIsRequired"),QJe(e)||DL("configType"),e.urls?(eet(),{paths:{vs:e.urls.monacoBase}}):e}function eet(){console.warn(Hee.deprecation)}function tet(e,t){throw new Error(e[t]||e.default)}var Hee={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!
|
|
1068
1068
|
You are using deprecated way of configuration.
|
|
1069
1069
|
|