react-semaphor 0.1.99 → 0.1.100
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-hsJsvBAe.js → dashboard-controls-DKci3my0.js} +1 -1
- package/dist/chunks/{dashboard-controls-CkHAO4CL.js → dashboard-controls-DW1JJWP7.js} +3 -3
- package/dist/chunks/{dashboard-json-K4H9HKDD.js → dashboard-json-BDAEIUep.js} +1 -1
- package/dist/chunks/{dashboard-json-BVoJAaE6.js → dashboard-json-C0CKQW3d.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-BDVEh9_m.js → edit-dashboard-visual-BtV3RWgf.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-3k0b3fdf.js → edit-dashboard-visual-DQzy1fUR.js} +3 -3
- package/dist/chunks/{editor-action-buttons-BJvCMEI8.js → editor-action-buttons-BJRrkj_n.js} +2 -2
- package/dist/chunks/{editor-action-buttons-CgKo0pGs.js → editor-action-buttons-CReBF7FV.js} +1 -1
- package/dist/chunks/{index-DEb8-ujQ.js → index-BDtdPUUE.js} +2 -2
- package/dist/chunks/{index-DT0OJMna.js → index-f2IZ7tlh.js} +9 -7
- package/dist/chunks/{resource-management-panel-CMdBNTA3.js → resource-management-panel-BQVERuRi.js} +1 -1
- package/dist/chunks/{resource-management-panel-DCNLT8uy.js → resource-management-panel-DNpbhYNu.js} +2 -2
- package/dist/chunks/{schedule-dashboard-CYopD6lq.js → schedule-dashboard-CfeYnMXp.js} +3 -3
- package/dist/chunks/{schedule-dashboard-Bc9Q91OK.js → schedule-dashboard-D8ctQToc.js} +1 -1
- package/dist/chunks/{use-visual-utils-C3UIGK5O.js → use-visual-utils-BN4h1-xa.js} +1 -1
- package/dist/chunks/{use-visual-utils-DcvgsE6B.js → use-visual-utils-CRA2-3Z2.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 Xme{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=AB.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 Va=new Xme;const HP="transparent",Qme={boolean(e,t,n){return n>.5?t:e},color(e,t,n){const r=IP(e||HP),s=r.valid&&IP(t||HP);return s&&s.valid?s.mix(r,n).hexString():t},number(e,t,n){return e+(t-e)*n}};let Jme=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||Qme[t.type||typeof i],this._easing=Ym[t.easing]||Ym.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 XB{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];(gn(o.properties)&&o.properties||[s]).forEach(a=>{(a===s||!r.has(a))&&r.set(a,i)})})}_animateOptions(t,n){const r=n.options,s=tge(t,r);if(!s)return[];const o=this._createAnimations(s,r);return r.$shared&&ege(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 Jme(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 Va.add(this._chart,r),!0}}function ege(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 tge(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 UP(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 nge(e,t,n){if(n===!1)return!1;const r=UP(e,n),s=UP(t,n);return{top:s.end,right:r.end,bottom:s.start,left:r.start}}function rge(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 QB(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 WP(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],nr(u)&&(o||t===0||pa(t)===pa(u))&&(t+=u)}return!d&&!r.all?0:t}function sge(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 WC(e,t){const n=e&&e.options.stacked;return n||n===void 0&&t.stack!==void 0}function oge(e,t,n){return`${e.id}.${t.id}.${n.stack||n.type}`}function ige(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 age(e,t,n){const r=e[t]||(e[t]={});return r[n]||(r[n]={})}function qP(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 YP(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=oge(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]=age(s,d,g),h[a]=b,h._top=qP(h,i,!0,r.type),h._bottom=qP(h,i,!1,r.type);const y=h._visualValues||(h._visualValues={});y[a]=b}}function qC(e,t){const n=e.scales;return Object.keys(n).filter(r=>n[r].axis===t).shift()}function lge(e,t){return Uc(e,{active:!1,dataset:void 0,datasetIndex:t,index:t,mode:"default",type:"dataset"})}function cge(e,t,n){return Uc(e,{active:!1,dataIndex:t,parsed:void 0,raw:void 0,element:n,index:t,mode:"default",type:"data"})}function em(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 YC=e=>e==="reset"||e==="none",GP=(e,t)=>t?e:Object.assign({},e),uge=(e,t,n)=>e&&!t.hidden&&t._stacked&&{keys:QB(n,!0),values:null};class Zs{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=WC(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&&em(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,qC(t,"x")),i=n.yAxisID=ct(r.yAxisID,qC(t,"y")),a=n.rAxisID=ct(r.rAxisID,qC(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&&DP(this._data,this),t._stacked&&em(t)}_dataCheck(){const t=this.getDataset(),n=t.data||(t.data=[]),r=this._data;if(_t(n)){const s=this._cachedMeta;this._data=sge(n,s)}else if(r!==n){if(r){DP(r,this);const s=this._cachedMeta;em(s),s._parsed=[]}n&&Object.isExtensible(n)&&Zpe(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=WC(n.vScale,n),n.stack!==r.stack&&(s=!0,em(n),n.stack=r.stack),this._resyncElements(t),(s||o!==n._stacked)&&(YP(this,n._parsed),n._stacked=WC(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{gn(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&&YP(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(jc(p,a),h),y:i.parse(jc(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:QB(s,!0),values:n._stacks[t.axis]._visualValues};return WP(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=WP(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=uge(n,r,this.chart),u={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:d,max:f}=ige(a);let h,p;function m(){p=s[h];const g=p[a.axis];return!nr(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],nr(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=rge(ct(this.options.clip,nge(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=cge(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=lge(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&&Eh(r);if(a)return GP(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(GP(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 XB(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||YC(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){YC(s)?Object.assign(t,r):this._resolveAnimations(n,s).update(t,r)}updateSharedOptions(t,n,r){t&&!YC(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&&em(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(Zs,"defaults",{}),Ae(Zs,"datasetElementType",null),Ae(Zs,"dataElementType",null);function dge(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=IB(r.sort((s,o)=>s-o))}return e._cache.$bar}function fge(e){const t=e.iScale,n=dge(t,e.type);let r=t._length,s,o,i,a;const l=()=>{i===32767||i===-32768||(Eh(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 hge(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 pge(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 mge(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 JB(e,t,n,r){return gn(e)?mge(e,t,n,r):t[n.axis]=n.parse(e,r),t}function ZP(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(JB(h,f,o,u));return l}function GC(e){return e&&e.barStart!==void 0&&e.barEnd!==void 0}function gge(e,t,n){return e!==0?pa(e):(t.isHorizontal()?1:-1)*(t.min>=n?1:-1)}function bge(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 xge(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}=bge(e);s==="middle"&&n&&(e.enableBorderRadius=!0,(n._top||0)===r?s=u:(n._bottom||0)===r?s=d:(o[KP(d,i,a,l)]=!0,s=u)),o[KP(s,i,a,l)]=!0,e.borderSkipped=o}function KP(e,t,n,r){return r?(e=yge(e,t,n),e=XP(e,n,t)):e=XP(e,t,n),e}function yge(e,t,n){return e===t?n:e===n?t:e}function XP(e,t,n){return e==="start"?t:e==="end"?n:e}function vge(e,{inflateAmount:t},n){e.inflateAmount=t==="auto"?n===1?.33:0:t}class Qu extends Zs{parsePrimitiveData(t,n,r,s){return ZP(t,n,r,s)}parseArrayData(t,n,r,s){return ZP(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(jc(g,u),h),f.push(JB(jc(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=GC(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||GC(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;xge(y,v,x,i),vge(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||fge(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=GC(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&&pa(f)!==pa(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=gge(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=pa(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"?pge(t,n,s,u):hge(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(Qu,"id","bar"),Ae(Qu,"defaults",{datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}}),Ae(Qu,"overrides",{scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}});class Ny extends Zs{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(Ny,"id","bubble"),Ae(Ny,"defaults",{datasetElementType:!1,dataElementType:"point",animations:{numbers:{type:"number",properties:["x","y","borderWidth","radius"]}}}),Ae(Ny,"overrides",{scales:{x:{type:"linear"},y:{type:"linear"}}});function wge(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)=>Tg(v,a,l,!0)?1:Math.max(w,w*n,S,S*n),m=(v,w,S)=>Tg(v,a,l,!0)?-1:Math.min(w,w*n,S,S*n),g=p(0,u,f),b=p(lr,d,h),x=m(Fn,u,f),y=m(Fn+lr,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 Du extends Zs{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=>+jc(r[u],l)}let i,a;for(i=t,a=t+n;i<a;++i)s._parsed[i]=o(i)}}_getRotation(){return wi(this.options.rotation-90)}_getCircumference(){return wi(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(Ape(this.options.cutout,a),1),u=this._getRingWeight(this.index),{circumference:d,rotation:f}=this._getRotationExtents(),{ratioX:h,ratioY:p,offsetX:m,offsetY:g}=wge(f,d,l),b=(r.width-i)/h,x=(r.height-i)/p,y=Math.max(Math.min(b,x)/2,0),v=_B(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=Ub(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(Du,"id","doughnut"),Ae(Du,"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(Du,"descriptors",{_scriptable:t=>t!=="spacing",_indexable:t=>t!=="spacing"&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")}),Ae(Du,"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 jy extends Zs{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}=OB(n,s,i);this._drawStart=a,this._drawCount=l,FB(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=Sd(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 _=this.getParsed(S),k=St(_[p]),E=j[h]=i.getPixelForValue(_[h],S),T=j[p]=o||k?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,_,l):_[p],S);j.skip=isNaN(E)||isNaN(T)||k,j.stop=S>0&&Math.abs(_[h]-w[h])>b,g&&(j.parsed=_,j.raw=u.data[S]),f&&(j.options=d||this.resolveDataElementOptions(S,C.active?"active":s)),x||this.updateElement(C,S,j,s),w=_}}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(jy,"id","line"),Ae(jy,"defaults",{datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1}),Ae(jy,"overrides",{scales:{_index_:{type:"category"},_value_:{type:"linear"}}});class Zm extends Zs{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=Ub(n._parsed[t].r,r.options.locale);return{label:s[t]||"",value:o}}parseObjectData(t,n,r,s){return UB.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)?wi(this.resolveDataElementOptions(t,n).angle||r):0}}Ae(Zm,"id","polarArea"),Ae(Zm,"defaults",{dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0}),Ae(Zm,"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 ik extends Du{}Ae(ik,"id","pie"),Ae(ik,"defaults",{cutout:0,rotation:0,circumference:360,radius:"100%"});class ky extends Zs{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 UB.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(ky,"id","radar"),Ae(ky,"defaults",{datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}}),Ae(ky,"overrides",{aspectRatio:1,scales:{r:{type:"radialLinear"}}});class Ey extends Zs{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}=OB(n,r,s);if(this._drawStart=o,this._drawCount=i,FB(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=Sd(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:{},_=St(C[m]),k=j[p]=i.getPixelForValue(C[p],w),E=j[m]=o||_?a.getBasePixel():a.getPixelForValue(l?this.applyStack(a,C,l):C[m],w);j.skip=isNaN(k)||isNaN(E)||_,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(Ey,"id","scatter"),Ae(Ey,"defaults",{datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1}),Ae(Ey,"overrides",{interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}});var Sge=Object.freeze({__proto__:null,BarController:Qu,BubbleController:Ny,DoughnutController:Du,LineController:jy,PieController:ik,PolarAreaController:Zm,RadarController:ky,ScatterController:Ey});function cu(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class GM{constructor(t){Ae(this,"options");this.options=t||{}}static override(t){Object.assign(GM.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 Cge={_date:GM};function Nge(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?Ype:sl;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 C1(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}=Nge(o[a],t,i,s);for(let p=f;p<=h;++p){const m=d[p];m.skip||r(m,u,p)}}}function jge(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 ZC(e,t,n,r,s){const o=[];return!s&&!e.isPointInArea(t)||C1(e,n,t,function(a,l,u){!s&&!ol(a,e.chartArea,0)||a.inRange(t.x,t.y,r)&&o.push({element:a,datasetIndex:l,index:u})},!0),o}function kge(e,t,n,r){let s=[];function o(i,a,l){const{startAngle:u,endAngle:d}=i.getProps(["startAngle","endAngle"],r),{angle:f}=TB(i,{x:t.x,y:t.y});Tg(f,u,d)&&s.push({element:i,datasetIndex:a,index:l})}return C1(e,n,t,o),s}function Ege(e,t,n,r,s,o){let i=[];const a=jge(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 C1(e,n,t,u),i}function KC(e,t,n,r,s,o){return!o&&!e.isPointInArea(t)?[]:n==="r"&&!r?kge(e,t,n,s):Ege(e,t,n,r,s,o)}function QP(e,t,n,r,s){const o=[],i=n==="x"?"inXRange":"inYRange";let a=!1;return C1(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 _ge={modes:{index(e,t,n,r){const s=yu(t,e),o=n.axis||"x",i=n.includeInvisible||!1,a=n.intersect?ZC(e,s,o,r,i):KC(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?ZC(e,s,o,r,i):KC(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 ZC(e,s,o,r,i)},nearest(e,t,n,r){const s=yu(t,e),o=n.axis||"xy",i=n.includeInvisible||!1;return KC(e,s,o,n.intersect,r,i)},x(e,t,n,r){const s=yu(t,e);return QP(e,s,"x",n.intersect,r)},y(e,t,n,r){const s=yu(t,e);return QP(e,s,"y",n.intersect,r)}}};const eV=["left","top","right","bottom"];function tm(e,t){return e.filter(n=>n.pos===t)}function JP(e,t){return e.filter(n=>eV.indexOf(n.pos)===-1&&n.box.axis===t)}function nm(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 Mge(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 Dge(e){const t={};for(const n of e){const{stack:r,pos:s,stackWeight:o}=n;if(!r||!eV.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 Tge(e,t){const n=Dge(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 Rge(e){const t=Mge(e),n=nm(t.filter(u=>u.box.fullSize),!0),r=nm(tm(t,"left"),!0),s=nm(tm(t,"right")),o=nm(tm(t,"top"),!0),i=nm(tm(t,"bottom")),a=JP(t,"x"),l=JP(t,"y");return{fullSize:n,leftAndTop:r.concat(o),rightAndBottom:s.concat(l).concat(i).concat(a),chartArea:tm(t,"chartArea"),vertical:r.concat(s).concat(l),horizontal:o.concat(i).concat(a)}}function eO(e,t,n,r){return Math.max(e[n],t[n])+Math.max(e[r],t[r])}function tV(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 Ige(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&&tV(i,o.getPadding());const a=Math.max(0,t.outerWidth-eO(i,e,"left","right")),l=Math.max(0,t.outerHeight-eO(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 Age(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 Pge(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 wm(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,Pge(a.horizontal,t));const{same:f,other:h}=Ige(t,n,a,r);u|=f&&s.length,d=d||h,l.fullSize||s.push(a)}return u&&wm(s,t,n,r)||d}function l0(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 tO(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;Eh(u.start)&&(i=u.start),l.fullSize?l0(l,s.left,i,n.outerWidth-s.right-s.left,h):l0(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;Eh(u.start)&&(o=u.start),l.fullSize?l0(l,o,s.top,h,n.outerHeight-s.bottom-s.top):l0(l,o,t.top+u.placed,h,f),u.start=o,u.placed+=f,o=l.right}}t.x=o,t.y=i}var es={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=Lr(e.options.layout.padding),o=Math.max(t-s.width,0),i=Math.max(n-s.height,0),a=Rge(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);tV(h,Lr(r));const p=Object.assign({maxPadding:h,w:o,h:i,x:s.left,y:s.top},s),m=Tge(l.concat(u),f);wm(a.fullSize,p,f,m),wm(l,p,f,m),wm(u,p,f,m)&&wm(l,p,f,m),Age(p),tO(a.leftAndTop,p,f,m),p.x+=p.w,p.y+=p.h,tO(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 nV{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 Oge extends nV{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const _y="$chartjs",Fge={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},nO=e=>e===null||e==="";function $ge(e,t){const n=e.style,r=e.getAttribute("height"),s=e.getAttribute("width");if(e[_y]={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=LP(e,"width");o!==void 0&&(e.width=o)}if(nO(r))if(e.style.height==="")e.height=e.width/(t||2);else{const o=LP(e,"height");o!==void 0&&(e.height=o)}return e}const rV=zme?{passive:!0}:!1;function Lge(e,t,n){e&&e.addEventListener(t,n,rV)}function zge(e,t,n){e&&e.canvas&&e.canvas.removeEventListener(t,n,rV)}function Bge(e,t){const n=Fge[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 vv(e,t){for(const n of e)if(n===t||n.contains(t))return!0}function Vge(e,t,n){const r=e.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||vv(a.addedNodes,r),i=i&&!vv(a.removedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}function Hge(e,t,n){const r=e.canvas,s=new MutationObserver(o=>{let i=!1;for(const a of o)i=i||vv(a.removedNodes,r),i=i&&!vv(a.addedNodes,r);i&&n()});return s.observe(document,{childList:!0,subtree:!0}),s}const Rg=new Map;let rO=0;function sV(){const e=window.devicePixelRatio;e!==rO&&(rO=e,Rg.forEach((t,n)=>{n.currentDevicePixelRatio!==e&&t()}))}function Uge(e,t){Rg.size||window.addEventListener("resize",sV),Rg.set(e,t)}function Wge(e){Rg.delete(e),Rg.size||window.removeEventListener("resize",sV)}function qge(e,t,n){const r=e.canvas,s=r&&YM(r);if(!s)return;const o=PB((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),Uge(e,o),i}function XC(e,t,n){n&&n.disconnect(),t==="resize"&&Wge(e)}function Yge(e,t,n){const r=e.canvas,s=PB(o=>{e.ctx!==null&&n(Bge(o,e))},e);return Lge(r,t,s),s}class Gge extends nV{acquireContext(t,n){const r=t&&t.getContext&&t.getContext("2d");return r&&r.canvas===t?($ge(t,n),r):null}releaseContext(t){const n=t.canvas;if(!n[_y])return!1;const r=n[_y].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[_y],!0}addEventListener(t,n,r){this.removeEventListener(t,n);const s=t.$proxies||(t.$proxies={}),i={attach:Vge,detach:Hge,resize:qge}[n]||Yge;s[n]=i(t,n,r)}removeEventListener(t,n){const r=t.$proxies||(t.$proxies={}),s=r[n];if(!s)return;({attach:XC,detach:XC,resize:XC}[n]||zge)(t,n,s),r[n]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,n,r,s){return Lme(t,n,r,s)}isAttached(t){const n=t&&YM(t);return!!(n&&n.isConnected)}}function Zge(e){return!qM()||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas?Oge:Gge}var my;let Qo=(my=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 Sd(this.x)&&Sd(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(my,"defaults",{}),Ae(my,"defaultRoutes"),my);function Kge(e,t){const n=e.options.ticks,r=Xge(e),s=Math.min(n.maxTicksLimit||r,r),o=n.major.enabled?Jge(t):[],i=o.length,a=o[0],l=o[i-1],u=[];if(i>s)return ebe(t,u,o,i/s),u;const d=Qge(o,t,s);if(i>0){let f,h;const p=i>1?Math.round((l-a)/(i-1)):null;for(c0(t,u,d,St(p)?0:a-p,a),f=0,h=i-1;f<h;f++)c0(t,u,d,o[f],o[f+1]);return c0(t,u,d,l,St(p)?t.length:l+p),u}return c0(t,u,d),u}function Xge(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 Qge(e,t,n){const r=tbe(e),s=t.length/n;if(!r)return Math.max(s,1);const o=Vpe(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 Jge(e){const t=[];let n,r;for(n=0,r=e.length;n<r;n++)e[n].major&&t.push(n);return t}function ebe(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 c0(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 tbe(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 nbe=e=>e==="left"?"right":e==="right"?"left":e,sO=(e,t,n)=>t==="top"||t==="left"?e[t]+n:e[t]-n,oO=(e,t)=>Math.min(t||e,e);function iO(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 rbe(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 sbe(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 rm(e){return e.drawTicks?e.tickLength:0}function aO(e,t){if(!e.display)return 0;const n=_n(e.font,t),r=Lr(e.padding);return(gn(e.text)?e.text.length:1)*n.lineHeight+r.height}function obe(e,t){return Uc(e,{scale:t,type:"scale"})}function ibe(e,t,n){return Uc(e,{tick:n,index:t,type:"tick"})}function abe(e,t,n){let r=LM(e);return(n&&t!=="right"||!n&&t==="right")&&(r=nbe(r)),r}function lbe(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=Kr(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=sO(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=sO(e,n,t);m=Kr(r,i,s),f=n==="left"?-lr:lr}return{titleX:p,titleY:m,maxWidth:h,rotation:f}}class Wc 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=oo(t,Number.POSITIVE_INFINITY),n=oo(n,Number.NEGATIVE_INFINITY),r=oo(r,Number.POSITIVE_INFINITY),s=oo(s,Number.NEGATIVE_INFINITY),{min:oo(t,r),max:oo(n,s),minDefined:nr(t),maxDefined:nr(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:oo(n,oo(r,n)),max:oo(r,oo(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(){hn(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=bme(this,o,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const l=a<this.ticks.length;this._convertTicksToLabels(l?iO(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),i.display&&(i.autoSkip||i.source==="auto")&&(this.ticks=Kge(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(){hn(this.options.afterUpdate,[this])}beforeSetDimensions(){hn(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(){hn(this.options.afterSetDimensions,[this])}_callHooks(t){this.chart.notifyPlugins(t,this.getContext()),hn(this.options[t],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){hn(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=hn(n.callback,[o.value,r,t],this)}afterTickToLabelConversion(){hn(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){hn(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const t=this.options,n=t.ticks,r=oO(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-rm(t.grid)-n.padding-aO(t.title,this.chart.options.font),u=Math.sqrt(f*f+h*h),i=FM(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(){hn(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){hn(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=aO(s,n.options.font);if(a?(t.width=this.maxWidth,t.height=rm(o)+l):(t.height=this.maxHeight,t.width=rm(o)+l),r.display&&this.ticks.length){const{first:u,last:d,widest:f,highest:h}=this._getLabelSizes(),p=r.padding*2,m=wi(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(){hn(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=iO(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/oO(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)&&!gn(m))v=bv(s,x.data,x.gc,v,m),w=y;else if(gn(m))for(h=0,p=m.length;h<p;++h)S=m[h],!St(S)&&!gn(S)&&(v=bv(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)}sbe(o,n);const C=i.indexOf(u),j=a.indexOf(d),_=k=>({width:i[k]||0,height:a[k]||0});return{first:_(0),last:_(n-1),widest:_(C),highest:_(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 qpe(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=ibe(this.getContext(),t,r))}return this.$context||(this.$context=obe(this.chart.getContext(),this))}_tickSize(){const t=this.options.ticks,n=wi(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=rm(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,_,k,E,T,R,O;if(i==="top")y=x(this.bottom),j=this.bottom-h,k=y-b,T=x(t.top)+b,O=t.bottom;else if(i==="bottom")y=x(this.top),T=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,_=y-b,E=x(t.left)+b,R=t.right;else if(i==="right")y=x(this.left),E=t.left,R=x(t.right)-b,C=y+b,_=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],B=i[F];y=x(this.chart.scales[F].getPixelForValue(B))}T=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],B=i[F];y=x(this.chart.scales[F].getPixelForValue(B))}C=y-b,_=C-h,E=t.left,R=t.right}const D=ct(s.ticks.maxTicksLimit,f),I=Math.max(1,Math.ceil(f/D));for(v=0;v<f;v+=I){const F=this.getContext(v),B=o.setContext(F),V=a.setContext(F),$=B.lineWidth,P=B.color,H=V.dash||[],L=V.dashOffset,A=B.tickWidth,W=B.tickColor,q=B.tickBorderDash||[],Y=B.tickBorderDashOffset;w=rbe(this,v,l),w!==void 0&&(S=lu(r,w,$),u?C=_=E=R=S:j=k=T=O=S,p.push({tx1:C,ty1:j,tx2:_,ty2:k,x1:E,y1:T,x2:R,y2:O,width:$,color:P,borderDash:H,borderDashOffset:L,tickWidth:A,tickColor:W,tickBorderDash:q,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=rm(r.grid),p=h+d,m=f?-d:p,g=-wi(this.labelRotation),b=[];let x,y,v,w,S,C,j,_,k,E,T,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 D=this._getLabelSizes();for(x=0,y=a.length;x<y;++x){v=a[x],w=v.label;const I=o.setContext(this.getContext(x));_=this.getPixelForTick(x)+o.labelOffset,k=this._resolveTickFontOptions(x),E=k.lineHeight,T=gn(w)?w.length:1;const F=T/2,B=I.color,V=I.textStrokeColor,$=I.textStrokeWidth;let P=j;i?(S=_,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=-T*E+E/2:u==="center"?R=-D.highest.height/2-F*E+E:R=-D.highest.height+E/2:u==="near"||g!==0?R=E/2:u==="center"?R=D.highest.height/2-F*E:R=D.highest.height-T*E,f&&(R*=-1),g!==0&&!I.showLabelBackdrop&&(S+=E/2*Math.sin(g))):(C=_,R=(1-T)*E/2);let H;if(I.showLabelBackdrop){const L=Lr(I.backdropPadding),A=D.heights[x],W=D.widths[x];let q=R-L.top,Y=0-L.left;switch(O){case"middle":q-=A/2;break;case"bottom":q-=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}H={left:Y,top:q,width:W+L.width,height:A+L.height,color:I.backdropColor}}b.push({label:w,font:k,textOffset:R,options:{rotation:g,color:B,strokeColor:V,strokeWidth:$,textAlign:P,textBaseline:O,translation:[S,C],backdrop:H}})}return b}_getXAxisLabelAlignment(){const{position:t,ticks:n}=this.options;if(-wi(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&&pc(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;Nd(r,u,0,d,l,a)}s&&mc(r)}drawTitle(){const{ctx:t,options:{position:n,title:r,reverse:s}}=this;if(!r.display)return;const o=_n(r.font),i=Lr(r.padding),a=r.align;let l=o.lineHeight/2;n==="bottom"||n==="center"||_t(n)?(l+=i.bottom,gn(r.text)&&(l+=o.lineHeight*(r.text.length-1))):l+=i.top;const{titleX:u,titleY:d,maxWidth:f,rotation:h}=lbe(this,l,n,a);Nd(t,r.text,0,0,o,{color:r.color,maxWidth:f,rotation:h,textAlign:abe(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!==Wc.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 u0{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;dbe(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,cbe(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 Cd[r])}}function cbe(e,t,n){const r=xr(Object.create(null),[n?Pn.get(n):{},Pn.get(t),e.defaults]);Pn.set(t,r),e.defaultRoutes&&ube(t,e.defaultRoutes),e.descriptors&&Pn.describe(t,e.descriptors)}function ube(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 dbe(e){return"id"in e&&"defaults"in e}class fbe{constructor(){this.controllers=new u0(Zs,"datasets",!0),this.elements=new u0(Qo,"elements"),this.plugins=new u0(Object,"plugins"),this.scales=new u0(Wc,"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=OM(t);hn(r["before"+s],[],r),n[t](r),hn(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 fbe;class hbe{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(hn(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=pbe(r);return s===!1&&!n?[]:gbe(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 pbe(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 mbe(e,t){return!t&&e===!1?null:e===!0?{}:e}function gbe(e,{plugins:t,localIds:n},r,s){const o=[],i=e.getContext();for(const a of t){const l=a.id,u=mbe(r[l],s);u!==null&&o.push({plugin:a,options:bbe(e.config,{plugin:a,local:n[l]},u,i)})}return o}function bbe(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 ak(e,t){const n=Pn.datasets[e]||{};return((t.datasets||{})[e]||{}).indexAxis||t.indexAxis||n.indexAxis||"x"}function xbe(e,t){let n=e;return e==="_index_"?n=t:e==="_value_"&&(n=t==="x"?"y":"x"),n}function ybe(e,t){return e===t?"_index_":"_value_"}function lO(e){if(e==="x"||e==="y"||e==="r")return e}function vbe(e){if(e==="top"||e==="bottom")return"x";if(e==="left"||e==="right")return"y"}function lk(e,...t){if(lO(e))return e;for(const n of t){const r=n.axis||vbe(n.position)||e.length>1&&lO(e[0].toLowerCase());if(r)return r}throw new Error(`Cannot determine type of '${e}' axis. Please provide 'axis' or 'position' option.`)}function cO(e,t,n){if(n[t+"AxisID"]===e)return{axis:t}}function wbe(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 cO(e,"x",n[0])||cO(e,"y",n[0])}return{}}function Sbe(e,t){const n=Cd[e.type]||{scales:{}},r=t.scales||{},s=ak(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=lk(i,a,wbe(i,e),Pn.scales[a.type]),u=ybe(l,s),d=n.scales||{};o[i]=Wm(Object.create(null),[{axis:l},a,d[l],d[u]])}),e.data.datasets.forEach(i=>{const a=i.type||e.type,l=i.indexAxis||ak(a,t),d=(Cd[a]||{}).scales||{};Object.keys(d).forEach(f=>{const h=xbe(f,l),p=i[h+"AxisID"]||h;o[p]=o[p]||Object.create(null),Wm(o[p],[{axis:h},r[p],d[f]])})}),Object.keys(o).forEach(i=>{const a=o[i];Wm(a,[Pn.scales[a.type],Pn.scale])}),o}function oV(e){const t=e.options||(e.options={});t.plugins=ct(t.plugins,{}),t.scales=Sbe(e,t)}function iV(e){return e=e||{},e.datasets=e.datasets||[],e.labels=e.labels||[],e}function Cbe(e){return e=e||{},e.data=iV(e.data),oV(e),e}const uO=new Map,aV=new Set;function d0(e,t){let n=uO.get(e);return n||(n=t(),uO.set(e,n),aV.add(n)),n}const sm=(e,t,n)=>{const r=jc(t,n);r!==void 0&&e.add(r)};class Nbe{constructor(t){this._config=Cbe(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=iV(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(),oV(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return d0(t,()=>[[`datasets.${t}`,""]])}datasetAnimationScopeKeys(t,n){return d0(`${t}.transition.${n}`,()=>[[`datasets.${t}.transitions.${n}`,`transitions.${n}`],[`datasets.${t}`,""]])}datasetElementScopeKeys(t,n){return d0(`${t}-${n}`,()=>[[`datasets.${t}.elements.${n}`,`datasets.${t}`,`elements.${n}`,""]])}pluginScopeKeys(t){const n=t.id,r=this.type;return d0(`${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=>sm(l,t,f))),d.forEach(f=>sm(l,s,f)),d.forEach(f=>sm(l,Cd[o]||{},f)),d.forEach(f=>sm(l,Pn,f)),d.forEach(f=>sm(l,ok,f))});const u=Array.from(l);return u.length===0&&u.push(Object.create(null)),aV.has(n)&&i.set(n,u),u}chartOptionScopes(){const{options:t,type:n}=this;return[t,Cd[n]||{},Pn.datasets[n]||{},{type:n},Pn,ok]}resolveNamedOptions(t,n,r,s=[""]){const o={$shared:!0},{resolver:i,subPrefixes:a}=dO(this._resolverCache,t,s);let l=i;if(kbe(i,n)){o.$shared=!1,r=kc(r)?r():r;const u=this.createResolver(t,r,a);l=_h(i,r,u)}for(const u of n)o[u]=l[u];return o}createResolver(t,n,r=[""],s){const{resolver:o}=dO(this._resolverCache,t,r);return _t(n)?_h(o,n,void 0,s):o}}function dO(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:HM(t,n),subPrefixes:n.filter(a=>!a.toLowerCase().includes("hover"))},r.set(s,o)),o}const jbe=e=>_t(e)&&Object.getOwnPropertyNames(e).some(t=>kc(e[t]));function kbe(e,t){const{isScriptable:n,isIndexable:r}=zB(e);for(const s of t){const o=n(s),i=r(s),a=(i||o)&&e[s];if(o&&(kc(a)||jbe(a))||i&&gn(a))return!0}return!1}var Ebe="4.4.8";const _be=["top","bottom","left","right","chartArea"];function fO(e,t){return e==="top"||e==="bottom"||_be.indexOf(e)===-1&&t==="x"}function hO(e,t){return function(n,r){return n[e]===r[e]?n[t]-r[t]:n[e]-r[e]}}function pO(e){const t=e.chart,n=t.options.animation;t.notifyPlugins("afterRender"),hn(n&&n.onComplete,[e],t)}function Mbe(e){const t=e.chart,n=t.options.animation;hn(n&&n.onProgress,[e],t)}function lV(e){return qM()&&typeof e=="string"?e=document.getElementById(e):e&&e.length&&(e=e[0]),e&&e.canvas&&(e=e.canvas),e}const My={},mO=e=>{const t=lV(e);return Object.values(My).filter(n=>n.canvas===t).pop()};function Dbe(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 Tbe(e,t,n,r){return!n||e.type==="mouseout"?null:r?t:e}function f0(e,t,n){return e.options.clip?e[n]:t[n]}function Rbe(e,t){const{xScale:n,yScale:r}=e;return n&&r?{left:f0(n,t,"left"),right:f0(n,t,"right"),top:f0(r,t,"top"),bottom:f0(r,t,"bottom")}:t}class Kt{static register(...t){Qn.add(...t),gO()}static unregister(...t){Qn.remove(...t),gO()}constructor(t,n){const r=this.config=new Nbe(n),s=lV(t),o=mO(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||Zge(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=Ipe(),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 hbe,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=Kpe(f=>this.update(f),i.resizeDelay||0),this._dataChanges=[],My[this.id]=this,!a||!l){console.error("Failed to create chart: can't acquire context from the given item");return}Va.listen(this,"complete",pO),Va.listen(this,"progress",Mbe),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():$P(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return PP(this.canvas,this.ctx),this}stop(){return Va.stop(this),this}resize(t,n){Va.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,$P(this,a,!0)&&(this.notifyPlugins("resize",{size:i}),hn(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=lk(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=lk(l,a),d=ct(a.type,i.dtype);(a.position===void 0||fO(a.position,u)!==fO(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=>{es.configure(this,i,i.options),es.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(hO("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||ak(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(hO("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=>{es.removeBox(this,t)}),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,n=new Set(Object.keys(this._listeners)),r=new Set(t.events);(!kP(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;Dbe(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(!kP(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;es.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,kc(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&&(Va.has(this)?this.attached&&!Va.running(this)&&Va.start(this):(this.draw(),pO({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=Rbe(t,this.chartArea),i={meta:t,index:t.index,cancelable:!0};this.notifyPlugins("beforeDatasetDraw",i)!==!1&&(s&&pc(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&&mc(n),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return ol(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,n,r,s){const o=_ge.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=Uc(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);Eh(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(),Va.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(),PP(t,n),this.platform.releaseContext(n),this.canvas=null,this.ctx=null),delete My[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}});!pv(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=Lpe(t),u=Tbe(t,this._lastEvent,r,l);r&&(this._lastEvent=null,hn(o.onHover,[t,a,this],this),l&&hn(o.onClick,[t,a,this],this));const d=!pv(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",My),Ae(Kt,"overrides",Cd),Ae(Kt,"registry",Qn),Ae(Kt,"version",Ebe),Ae(Kt,"getChart",mO);function gO(){return sn(Kt.instances,e=>e._plugins.invalidate())}function Ibe(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+lr,r-lr),e.closePath(),e.clip()}function Abe(e){return BM(e,["outerStart","outerEnd","innerStart","innerEnd"])}function Pbe(e,t,n,r){const s=Abe(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 cf(e,t,n,r){return{x:n+e*Math.cos(t),y:r+e*Math.sin(t)}}function wv(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,B=(I+F)/2,V=B!==0?m*B/(B+r):m;p=(m-V)/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}=Pbe(t,h,f,y-x),j=f-v,_=f-w,k=x+v/j,E=y-w/_,T=h+S,R=h+C,O=x+S/T,D=y-C/R;if(e.beginPath(),o){const I=(k+E)/2;if(e.arc(i,a,f,k,I),e.arc(i,a,f,I,E),w>0){const $=cf(_,E,i,a);e.arc($.x,$.y,w,E,y+lr)}const F=cf(R,y,i,a);if(e.lineTo(F.x,F.y),C>0){const $=cf(R,D,i,a);e.arc($.x,$.y,C,y+lr,D+Math.PI)}const B=(y-C/h+(x+S/h))/2;if(e.arc(i,a,h,y-C/h,B,!0),e.arc(i,a,h,B,x+S/h,!0),S>0){const $=cf(T,O,i,a);e.arc($.x,$.y,S,O+Math.PI,x-lr)}const V=cf(j,x,i,a);if(e.lineTo(V.x,V.y),v>0){const $=cf(j,k,i,a);e.arc($.x,$.y,v,x-lr,k)}}else{e.moveTo(i,a);const I=Math.cos(k)*f+i,F=Math.sin(k)*f+a;e.lineTo(I,F);const B=Math.cos(E)*f+i,V=Math.sin(E)*f+a;e.lineTo(B,V)}e.closePath()}function Obe(e,t,n,r,s){const{fullCircles:o,startAngle:i,circumference:a}=t;let l=t.endAngle;if(o){wv(e,t,n,r,l,s);for(let u=0;u<o;++u)e.fill();isNaN(a)||(l=i+(a%An||An))}return wv(e,t,n,r,l,s),e.fill(),l}function Fbe(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){wv(e,t,n,r,m,s);for(let g=0;g<o;++g)e.stroke();isNaN(a)||(m=i+(a%An||An))}p&&Ibe(e,t,m),o||(wv(e,t,n,r,m,s),e.stroke())}class Df 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}=TB(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=Tg(i,l,u)&&l!==u,b=m>=An||g,x=rl(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,Obe(n,this,d,i,a),Fbe(n,this,d,i,a),n.restore()}}Ae(Df,"id","arc"),Ae(Df,"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(Df,"defaultRoutes",{backgroundColor:"backgroundColor"}),Ae(Df,"descriptors",{_scriptable:!0,_indexable:n=>n!=="borderDash"});function cV(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 $be(e,t,n){e.lineTo(n.x,n.y)}function Lbe(e){return e.stepped?lme:e.tension||e.cubicInterpolationMode==="monotone"?cme:$be}function uV(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 zbe(e,t,n,r){const{points:s,options:o}=t,{count:i,start:a,loop:l,ilen:u}=uV(s,n,r),d=Lbe(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 Bbe(e,t,n,r){const s=t.points,{count:o,start:i,ilen:a}=uV(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 ck(e){const t=e.options,n=t.borderDash&&t.borderDash.length;return!e._decimated&&!e._loop&&!t.tension&&t.cubicInterpolationMode!=="monotone"&&!t.stepped&&!n?Bbe:zbe}function Vbe(e){return e.stepped?Bme:e.tension||e.cubicInterpolationMode==="monotone"?Vme:vu}function Hbe(e,t,n,r){let s=t._path;s||(s=t._path=new Path2D,t.path(s,n,r)&&s.closePath()),cV(e,t.options),e.stroke(s)}function Ube(e,t,n,r){const{segments:s,options:o}=t,i=ck(t);for(const a of s)cV(e,o,a.style),e.beginPath(),i(e,t,a,{start:n,end:n+r-1})&&e.closePath(),e.stroke()}const Wbe=typeof Path2D=="function";function qbe(e,t,n,r){Wbe&&!t.options.segment?Hbe(e,t,n,r):Ube(e,t,n,r)}class ic 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;Ime(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=Gme(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=KB(this,{property:n,start:s,end:s});if(!i.length)return;const a=[],l=Vbe(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 ck(this)(t,this,n,r)}path(t,n,r){const s=this.segments,o=ck(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(),qbe(t,this,r,s),t.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}Ae(ic,"id","line"),Ae(ic,"defaults",{borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0}),Ae(ic,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"}),Ae(ic,"descriptors",{_scriptable:!0,_indexable:t=>t!=="borderDash"&&t!=="fill"});function bO(e,t,n,r){const s=e.options,{[n]:o}=e.getProps([n],r);return Math.abs(t-o)<s.radius+s.hitRadius}class Ju 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 bO(this,n,"x",r)}inYRange(n,r){return bO(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||!ol(this,r,this.size(s)/2)||(n.strokeStyle=s.borderColor,n.lineWidth=s.borderWidth,n.fillStyle=s.backgroundColor,xv(n,s,this.x,this.y))}getRange(){const n=this.options||{};return n.radius+n.hitRadius}}Ae(Ju,"id","point"),Ae(Ju,"defaults",{borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0}),Ae(Ju,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});function dV(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 ac(e,t,n,r){return e?0:Ir(t,n,r)}function Ybe(e,t,n){const r=e.options.borderWidth,s=e.borderSkipped,o=VM(r);return{t:ac(s.top,o.top,0,n),r:ac(s.right,o.right,0,t),b:ac(s.bottom,o.bottom,0,n),l:ac(s.left,o.left,0,t)}}function Gbe(e,t,n){const{enableBorderRadius:r}=e.getProps(["enableBorderRadius"]),s=e.options.borderRadius,o=ml(s),i=Math.min(t,n),a=e.borderSkipped,l=r||_t(s);return{topLeft:ac(!l||a.top||a.left,o.topLeft,0,i),topRight:ac(!l||a.top||a.right,o.topRight,0,i),bottomLeft:ac(!l||a.bottom||a.left,o.bottomLeft,0,i),bottomRight:ac(!l||a.bottom||a.right,o.bottomRight,0,i)}}function Zbe(e){const t=dV(e),n=t.right-t.left,r=t.bottom-t.top,s=Ybe(e,n/2,r/2),o=Gbe(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 QC(e,t,n,r){const s=t===null,o=n===null,a=e&&!(s&&o)&&dV(e,r);return a&&(s||rl(t,a.left,a.right))&&(o||rl(n,a.top,a.bottom))}function Kbe(e){return e.topLeft||e.topRight||e.bottomLeft||e.bottomRight}function Xbe(e,t){e.rect(t.x,t.y,t.w,t.h)}function JC(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 ma 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}=Zbe(this),a=Kbe(i.radius)?pl:Xbe;t.save(),(i.w!==o.w||i.h!==o.h)&&(t.beginPath(),a(t,JC(i,n,o)),t.clip(),a(t,JC(o,-n,i)),t.fillStyle=r,t.fill("evenodd")),t.beginPath(),a(t,JC(o,n)),t.fillStyle=s,t.fill(),t.restore()}inRange(t,n,r){return QC(this,t,n,r)}inXRange(t,n){return QC(this,t,null,n)}inYRange(t,n){return QC(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(ma,"id","bar"),Ae(ma,"defaults",{borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0}),Ae(ma,"defaultRoutes",{backgroundColor:"backgroundColor",borderColor:"borderColor"});var Qbe=Object.freeze({__proto__:null,ArcElement:Df,BarElement:ma,LineElement:ic,PointElement:Ju});const uk=["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)"],xO=uk.map(e=>e.replace("rgb(","rgba(").replace(")",", 0.5)"));function fV(e){return uk[e%uk.length]}function hV(e){return xO[e%xO.length]}function Jbe(e,t){return e.borderColor=fV(t),e.backgroundColor=hV(t),++t}function exe(e,t){return e.backgroundColor=e.data.map(()=>fV(t++)),t}function txe(e,t){return e.backgroundColor=e.data.map(()=>hV(t++)),t}function nxe(e){let t=0;return(n,r)=>{const s=e.getDatasetMeta(r).controller;s instanceof Du?t=exe(n,t):s instanceof Zm?t=txe(n,t):s&&(t=Jbe(n,t))}}function yO(e){let t;for(t in e)if(e[t].borderColor||e[t].backgroundColor)return!0;return!1}function rxe(e){return e&&(e.borderColor||e.backgroundColor)}function sxe(){return Pn.borderColor!=="rgba(0,0,0,0.1)"||Pn.backgroundColor!=="rgba(0,0,0,0.1)"}var oxe={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=yO(r)||rxe(s)||o&&yO(o)||sxe();if(!n.forceOverride&&i)return;const a=nxe(e);r.forEach(a)}};function ixe(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:_,y:k}=e[d];for(p=m=-1,y=C;y<j;y++)m=.5*Math.abs((_-b)*(e[y].y-k)-(_-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 axe(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),_=Math.max(f,h);j!==p&&j!==C&&b.push({...e[j],x:s}),_!==p&&_!==C&&b.push({...e[_],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 pV(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=>{pV(t)})}function lxe(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(sl(t,o.axis,i).lo,0,n-1)),u?s=Ir(sl(t,o.axis,a).hi+1,r,n)-r:s=n-r,{start:r,count:s}}var cxe={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}=lxe(l,u);const p=n.threshold||4*r;if(h<=p){pV(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=ixe(u,f,h,r,n);break;case"min-max":m=axe(u,f,h,r);break;default:throw new Error(`Unsupported decimation algorithm '${n.algorithm}'`)}s._decimated=m})},destroy(e){vO(e)}};function uxe(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=ZM(l,u,s);const d=dk(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=KB(t,d);for(const h of f){const p=dk(n,o[h.start],o[h.end],h.loop),m=ZB(a,s,p);for(const g of m)i.push({source:g,target:h,start:{[n]:wO(d,p,"start",Math.max)},end:{[n]:wO(d,p,"end",Math.min)}})}}return i}function dk(e,t,n,r){if(r)return;let s=t[e],o=n[e];return e==="angle"&&(s=co(s),o=co(o)),{property:e,start:s,end:o}}function dxe(e,t){const{x:n=null,y:r=null}=e||{},s=t.points,o=[];return t.segments.forEach(({start:i,end:a})=>{a=ZM(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 ZM(e,t,n){for(;t>e;t--){const r=n[t];if(!isNaN(r.x)&&!isNaN(r.y))break}return t}function wO(e,t,n,r){return e&&t?r(e[n],t[n]):e?e[n]:t?t[n]:0}function mV(e,t){let n=[],r=!1;return gn(e)?(r=!0,n=e):n=dxe(e,t),n.length?new ic({points:n,options:{tension:0},_loop:r,_fullLoop:r}):null}function SO(e){return e&&e.fill!==!1}function fxe(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(!nr(s))return s;if(i=e[s],!i)return!1;if(i.visible)return s;o.push(s),s=i.fill}return!1}function hxe(e,t,n){const r=bxe(e);if(_t(r))return isNaN(r.value)?!1:r;let s=parseFloat(r);return nr(s)&&Math.floor(s)===s?pxe(r[0],t,s,n):["origin","start","end","stack","shape"].indexOf(r)>=0&&r}function pxe(e,t,n,r){return(e==="-"||e==="+")&&(n=t+n),n===t||n<0||n>=r?!1:n}function mxe(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 gxe(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 bxe(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 xxe(e){const{scale:t,index:n,line:r}=e,s=[],o=r.segments,i=r.points,a=yxe(t,n);a.push(mV({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++)vxe(s,i[d],a)}return new ic({points:s,options:{}})}function yxe(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 vxe(e,t,n){const r=[];for(let s=0;s<n.length;s++){const o=n[s],{first:i,last:a,point:l}=wxe(o,t,"x");if(!(!l||i&&a)){if(i)r.unshift(l);else if(e.push(l),!a)break}}e.push(...r)}function wxe(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(rl(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 Sxe(e){const{chart:t,fill:n,line:r}=e;if(nr(n))return Cxe(t,n);if(n==="stack")return xxe(e);if(n==="shape")return!0;const s=Nxe(e);return s instanceof gV?s:mV(s,r)}function Cxe(e,t){const n=e.getDatasetMeta(t);return n&&e.isDatasetVisible(t)?n.dataset:null}function Nxe(e){return(e.scale||{}).getPointPositionForValue?kxe(e):jxe(e)}function jxe(e){const{scale:t={},fill:n}=e,r=mxe(n,t);if(nr(r)){const s=t.isHorizontal();return{x:s?r:null,y:s?null:r}}return null}function kxe(e){const{scale:t,fill:n}=e,r=t.options,s=t.getLabels().length,o=r.reverse?t.max:t.min,i=gxe(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 eN(e,t,n){const r=Sxe(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&&(pc(e,n),Exe(e,{line:s,target:r,above:d,below:f,area:n,scale:o,axis:i}),mc(e))}function Exe(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&&(CO(e,r,i.top),NO(e,{line:n,target:r,color:s,scale:a,property:l}),e.restore(),e.save(),CO(e,r,i.bottom)),NO(e,{line:n,target:r,color:o,scale:a,property:l}),e.restore()}function CO(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[ZM(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 NO(e,t){const{line:n,target:r,property:s,color:o,scale:i}=t,a=uxe(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,_xe(e,i,p&&dk(s,d,f)),e.beginPath();const m=!!n.pathSegment(e,l);let g;if(p){m?e.closePath():jO(e,r,f,s);const b=!!r.pathSegment(e,u,{move:m,reverse:!0});g=m&&b,g||jO(e,r,d,s)}e.closePath(),e.fill(g?"evenodd":"nonzero"),e.restore()}}function _xe(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 jO(e,t,n,r){const s=t.interpolate(n,r);s&&e.lineTo(s.x,s.y)}var Mxe={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 ic&&(l={visible:e.isDatasetVisible(i),index:i,fill:hxe(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=fxe(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&&eN(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;SO(o)&&eN(e.ctx,o,e.chartArea)}},beforeDatasetDraw(e,t,n){const r=t.meta.$filler;!SO(r)||n.drawTime!=="beforeDatasetDraw"||eN(e.ctx,r,e.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const kO=(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)}},Dxe=(e,t)=>e!==null&&t!==null&&e.datasetIndex===t.datasetIndex&&e.index===t.index;class EO 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=hn(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}=kO(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}=Txe(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=Yf(o,this.left,this.width);if(this.isHorizontal()){let a=0,l=Kr(r,this.left+s,this.right-this.lineWidths[a]);for(const u of n)a!==u.row&&(a=u.row,l=Kr(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=Kr(r,this.top+t+s,this.bottom-this.columnSizes[a].height);for(const u of n)u.col!==a&&(a=u.col,l=Kr(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;pc(t,this),this._draw(),mc(t)}}_draw(){const{options:t,columnSizes:n,lineWidths:r,ctx:s}=this,{align:o,labels:i}=t,a=Pn.color,l=Yf(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}=kO(i,f),x=function(C,j,_){if(isNaN(m)||m<=0||isNaN(g)||g<0)return;s.save();const k=ct(_.lineWidth,1);if(s.fillStyle=ct(_.fillStyle,a),s.lineCap=ct(_.lineCap,"butt"),s.lineDashOffset=ct(_.lineDashOffset,0),s.lineJoin=ct(_.lineJoin,"miter"),s.lineWidth=k,s.strokeStyle=ct(_.strokeStyle,a),s.setLineDash(ct(_.lineDash,[])),i.usePointStyle){const E={radius:g*Math.SQRT2/2,pointStyle:_.pointStyle,rotation:_.rotation,borderWidth:k},T=l.xPlus(C,m/2),R=j+h;LB(s,E,T,R,i.pointStyleWidth&&m)}else{const E=j+Math.max((f-g)/2,0),T=l.leftForLtr(C,m),R=ml(_.borderRadius);s.beginPath(),Object.values(R).some(O=>O!==0)?pl(s,{x:T,y:E,w:m,h:g,radius:R}):s.rect(T,E,m,g),s.fill(),k!==0&&s.stroke()}s.restore()},y=function(C,j,_){Nd(s,_.text,C,j+b/2,u,{strikethrough:_.hidden,textAlign:l.textAlign(_.textAlign)})},v=this.isHorizontal(),w=this._computeTitleHeight();v?p={x:Kr(o,this.left+d,this.right-r[0]),y:this.top+d+w,line:0}:p={x:this.left+d,y:Kr(o,this.top+w+d,this.bottom-n[0].height),line:0},qB(this.ctx,t.textDirection);const S=b+d;this.legendItems.forEach((C,j)=>{s.strokeStyle=C.fontColor,s.fillStyle=C.fontColor;const _=s.measureText(C.text).width,k=l.textAlign(C.textAlign||(C.textAlign=i.textAlign)),E=m+h+_;let T=p.x,R=p.y;l.setWidth(this.width),v?j>0&&T+E+d>this.right&&(R=p.y+=S,p.line++,T=p.x=Kr(o,this.left+d,this.right-r[p.line])):j>0&&R+S>this.bottom&&(T=p.x=T+n[p.line].width+d,p.line++,R=p.y=Kr(o,this.top+w+d,this.bottom-n[p.line].height));const O=l.x(T);if(x(O,R,C),T=Xpe(k,T+m+h,v?T+E:this.right,t.rtl),y(l.x(T),R,C),v)p.x+=E+d;else if(typeof C.text!="string"){const D=u.lineHeight;p.y+=bV(C,D)+d}else p.y+=S}),YB(this.ctx,t.textDirection)}drawTitle(){const t=this.options,n=t.title,r=_n(n.font),s=Lr(n.padding);if(!n.display)return;const o=Yf(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=Kr(t.align,f,this.right-h);else{const m=this.columnSizes.reduce((g,b)=>Math.max(g,b.height),0);d=u+Kr(t.align,this.top,this.bottom-m-t.labels.padding-this._computeTitleHeight())}const p=Kr(a,f,f+h);i.textAlign=o.textAlign(LM(a)),i.textBaseline="middle",i.strokeStyle=n.color,i.fillStyle=n.color,i.font=r.string,Nd(i,n.text,p,d,r)}_computeTitleHeight(){const t=this.options.title,n=_n(t.font),r=Lr(t.padding);return t.display?n.lineHeight+r.height:0}_getLegendItemAt(t,n){let r,s,o;if(rl(t,this.left,this.right)&&rl(n,this.top,this.bottom)){for(o=this.legendHitBoxes,r=0;r<o.length;++r)if(s=o[r],rl(t,s.left,s.left+s.width)&&rl(n,s.top,s.top+s.height))return this.legendItems[r]}return null}handleEvent(t){const n=this.options;if(!Axe(t.type,n))return;const r=this._getLegendItemAt(t.x,t.y);if(t.type==="mousemove"||t.type==="mouseout"){const s=this._hoveredItem,o=Dxe(s,r);s&&!o&&hn(n.onLeave,[t,s,this],this),this._hoveredItem=r,r&&!o&&hn(n.onHover,[t,r,this],this)}else r&&hn(n.onClick,[t,r,this],this)}}function Txe(e,t,n,r,s){const o=Rxe(r,e,t,n),i=Ixe(s,r,t.lineHeight);return{itemWidth:o,itemHeight:i}}function Rxe(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 Ixe(e,t,n){let r=e;return typeof t.text!="string"&&(r=bV(t,n)),r}function bV(e,t){const n=e.text?e.text.length:0;return t*n}function Axe(e,t){return!!((e==="mousemove"||e==="mouseout")&&(t.onHover||t.onLeave)||t.onClick&&(e==="click"||e==="mouseup"))}var Pxe={id:"legend",_element:EO,start(e,t,n){const r=e.legend=new EO({ctx:e.ctx,options:n,chart:e});es.configure(e,r,n),es.addBox(e,r)},stop(e){es.removeBox(e,e.legend),delete e.legend},beforeUpdate(e,t,n){const r=e.legend;es.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=Lr(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 KM 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=gn(r.text)?r.text.length:1;this._padding=Lr(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=Kr(a,r,o),f=n+t,u=o-r):(i.position==="left"?(d=r+t,f=Kr(a,s,n),l=Fn*-.5):(d=o-t,f=Kr(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);Nd(t,n.text,0,0,r,{color:n.color,maxWidth:l,rotation:u,textAlign:LM(n.align),textBaseline:"middle",translation:[i,a]})}}function Oxe(e,t){const n=new KM({ctx:e.ctx,options:t,chart:e});es.configure(e,n,t),es.addBox(e,n),e.titleBlock=n}var Fxe={id:"title",_element:KM,start(e,t,n){Oxe(e,n)},stop(e){const t=e.titleBlock;es.removeBox(e,t),delete e.titleBlock},beforeUpdate(e,t,n){const r=e.titleBlock;es.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 h0=new WeakMap;var $xe={id:"subtitle",start(e,t,n){const r=new KM({ctx:e.ctx,options:n,chart:e});es.configure(e,r,n),es.addBox(e,r),h0.set(e,r)},stop(e){es.removeBox(e,h0.get(e)),h0.delete(e)},beforeUpdate(e,t,n){const r=h0.get(e);es.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 Sm={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=sk(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 Wi(e,t){return t&&(gn(t)?Array.prototype.push.apply(e,t):e.push(t)),e}function Ha(e){return(typeof e=="string"||e instanceof String)&&e.indexOf(`
|
|
761
761
|
`)>-1?e.split(`
|
|
762
762
|
`):e}function Lxe(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 _O(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=Lr(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 zxe(e,t){const{y:n,height:r}=t;return n<r/2?"top":n>e.height-r/2?"bottom":"center"}function Bxe(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 Vxe(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"),Bxe(u,e,t,n)&&(u="center"),u}function MO(e,t,n){const r=n.yAlign||t.yAlign||zxe(e,n);return{xAlign:n.xAlign||t.xAlign||Vxe(e,t,n,r),yAlign:r}}function Hxe(e,t){let{x:n,width:r}=e;return t==="right"?n-=r:t==="center"&&(n-=r/2),n}function Uxe(e,t,n){let{y:r,height:s}=e;return t==="top"?r+=n:t==="bottom"?r-=s+n:r-=s/2,r}function DO(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}=ml(i);let m=Hxe(t,a);const g=Uxe(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 p0(e,t,n){const r=Lr(n.padding);return t==="center"?e.x+e.width/2:t==="right"?e.x+e.width-r.right:e.x+r.left}function TO(e){return Wi([],Ha(e))}function Wxe(e,t,n){return Uc(e,{tooltip:t,tooltipItems:n,type:"tooltip"})}function RO(e,t){const n=t&&t.dataset&&t.dataset.tooltip&&t.dataset.tooltip.callbacks;return n?e.override(n):e}const xV={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 Rs(e,t,n,r){const s=e[t].call(n,r);return typeof s>"u"?xV[t].call(n,r):s}class fk 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 XB(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(o)),o}getContext(){return this.$context||(this.$context=Wxe(this.chart.getContext(),this,this._tooltipItems))}getTitle(t,n){const{callbacks:r}=n,s=Rs(r,"beforeTitle",this,t),o=Rs(r,"title",this,t),i=Rs(r,"afterTitle",this,t);let a=[];return a=Wi(a,Ha(s)),a=Wi(a,Ha(o)),a=Wi(a,Ha(i)),a}getBeforeBody(t,n){return TO(Rs(n.callbacks,"beforeBody",this,t))}getBody(t,n){const{callbacks:r}=n,s=[];return sn(t,o=>{const i={before:[],lines:[],after:[]},a=RO(r,o);Wi(i.before,Ha(Rs(a,"beforeLabel",this,o))),Wi(i.lines,Rs(a,"label",this,o)),Wi(i.after,Ha(Rs(a,"afterLabel",this,o))),s.push(i)}),s}getAfterBody(t,n){return TO(Rs(n.callbacks,"afterBody",this,t))}getFooter(t,n){const{callbacks:r}=n,s=Rs(r,"beforeFooter",this,t),o=Rs(r,"footer",this,t),i=Rs(r,"afterFooter",this,t);let a=[];return a=Wi(a,Ha(s)),a=Wi(a,Ha(o)),a=Wi(a,Ha(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(Lxe(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=RO(t.callbacks,d);s.push(Rs(f,"labelColor",this,d)),o.push(Rs(f,"labelPointStyle",this,d)),i.push(Rs(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=Sm[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=_O(this,r),u=Object.assign({},a,l),d=MO(this.chart,r,u),f=DO(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}=ml(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=Yf(r.rtl,this.x,this.width);for(t.x=p0(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=p0(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,xv(t,g,b,x),t.strokeStyle=i.borderColor,t.fillStyle=i.backgroundColor,xv(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=ml(i.borderRadius);Object.values(x).some(y=>y!==0)?(t.beginPath(),t.fillStyle=o.multiKeyBackground,pl(t,{x:g,y:m,w:u,h:l,radius:x}),t.fill(),t.stroke(),t.fillStyle=i.backgroundColor,t.beginPath(),pl(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=Yf(r.rtl,this.x,this.width),g=function(_){n.fillText(_,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=p0(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=Yf(r.rtl,this.x,this.width);for(t.x=p0(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}=ml(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=Sm[t.position].call(this,this._active,this._eventPosition);if(!i)return;const a=this._size=_O(this,t),l=Object.assign({},i,this._size),u=MO(n,t,l),d=DO(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=Lr(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),qB(t,n.textDirection),o.y+=i.top,this.drawTitle(o,t,n),this.drawBody(o,t,n),this.drawFooter(o,t,n),YB(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=!pv(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||!pv(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=Sm[o.position].call(this,t,n);return i!==!1&&(r!==i.x||s!==i.y)}}Ae(fk,"positioners",Sm);var yV={id:"tooltip",_element:fk,positioners:Sm,afterInit(e,t,n){n&&(e.tooltip=new fk({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:xV},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"]},qxe=Object.freeze({__proto__:null,Colors:oxe,Decimation:cxe,Filler:Mxe,Legend:Pxe,SubTitle:$xe,Title:Fxe,Tooltip:yV});const Yxe=(e,t,n,r)=>(typeof t=="string"?(n=e.push(t)-1,r.unshift({index:n,label:t})):isNaN(t)&&(n=null),n);function Gxe(e,t,n,r){const s=e.indexOf(t);if(s===-1)return Yxe(e,t,n,r);const o=e.lastIndexOf(t);return s!==o?n:s}const Zxe=(e,t)=>e===null?null:Ir(Math.round(e),0,t);function IO(e){const t=this.getLabels();return e>=0&&e<t.length?t[e]:e}class Ig extends Wc{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:Gxe(r,t,ct(n,t),this._addedLabels),Zxe(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 IO.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(Ig,"id","category"),Ae(Ig,"defaults",{ticks:{callback:IO}});function Kxe(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=_P((b-g)/m/p)*p,C,j,_,k;if(S<1e-14&&!x&&!y)return[{value:g},{value:b}];k=Math.ceil(b/S)-Math.floor(g/S),k>m&&(S=_P(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,_=Math.ceil(b/S)*S):(j=g,_=b),x&&y&&o&&Upe((a-i)/o,S/1e3)?(k=Math.round(Math.min((a-i)/S,d)),S=(a-i)/k,j=i,_=a):v?(j=x?i:j,_=y?a:_,k=u-1,S=(_-j)/k):(k=(_-j)/S,qm(k,Math.round(k),S/1e3)?k=Math.round(k):k=Math.ceil(k));const E=Math.max(MP(S),MP(j));C=Math.pow(10,St(l)?E:l),j=Math.round(j*C)/C,_=Math.round(_*C)/C;let T=0;for(x&&(h&&j!==i?(n.push({value:i}),j<i&&T++,qm(Math.round((j+T*S)*C)/C,i,AO(i,w,e))&&T++):j<i&&T++);T<k;++T){const R=Math.round((j+T*S)*C)/C;if(y&&R>a)break;n.push({value:R})}return y&&h&&_!==a?n.length&&qm(n[n.length-1].value,a,AO(a,w,e))?n[n.length-1].value=a:n.push({value:a}):(!y||_===a)&&n.push({value:_}),n}function AO(e,t,{horizontal:n,minRotation:r}){const s=wi(r),o=(n?Math.sin(s):Math.cos(s))||.001,i=.75*t*(""+e).length;return Math.min(t/o,i)}class Sv extends Wc{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=pa(s),u=pa(o);l<0&&u<0?a(0):l>0&&u>0&&i(0)}if(s===o){let l=o===0?1:Math.abs(o*.05);a(o+l),t||i(s-l)}this.min=s,this.max=o}getTickLimit(){const t=this.options.ticks;let{maxTicksLimit:n,stepSize:r}=t,s;return r?(s=Math.ceil(this.max/r)-Math.floor(this.min/r)+1,s>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${r} would result generating up to ${s} ticks. Limiting to 1000.`),s=1e3)):(s=this.computeTickLimit(),n=n||11),n&&(s=Math.min(n,s)),s}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,n=t.ticks;let r=this.getTickLimit();r=Math.max(2,r);const s={maxTicks:r,bounds:t.bounds,min:t.min,max:t.max,precision:n.precision,step:n.stepSize,count:n.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:n.minRotation||0,includeBounds:n.includeBounds!==!1},o=this._range||this,i=Kxe(s,o);return t.bounds==="ticks"&&DB(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 Ub(t,this.chart.options.locale,this.options.ticks.format)}}class jd extends Sv{determineDataLimits(){const{min:t,max:n}=this.getMinMax(!0);this.min=nr(t)?t:0,this.max=nr(n)?n:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),n=t?this.width:this.height,r=wi(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(jd,"id","linear"),Ae(jd,"defaults",{ticks:{callback:w1.formatters.numeric}});const Ag=e=>Math.floor(oc(e)),uu=(e,t)=>Math.pow(10,Ag(e)+t);function PO(e){return e/Math.pow(10,Ag(e))===1}function OO(e,t,n){const r=Math.pow(10,n),s=Math.floor(e/r);return Math.ceil(t/r)-s}function Xxe(e,t){const n=t-e;let r=Ag(n);for(;OO(e,t,r)>10;)r++;for(;OO(e,t,r)<10;)r--;return Math.min(r,Ag(e))}function Qxe(e,{min:t,max:n}){t=oo(e.min,t);const r=[],s=Ag(t);let o=Xxe(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=oo(e.min,Math.round((l+d+f*Math.pow(10,o))*i)/i);for(;h<n;)r.push({value:h,major:PO(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=oo(e.max,h);return r.push({value:p,major:PO(p),significand:f}),r}class Dh extends Wc{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,n){const r=Sv.prototype.parse.apply(this,[t,n]);if(r===0){this._zero=!0;return}return nr(r)&&r>0?r:null}determineDataLimits(){const{min:t,max:n}=this.getMinMax(!0);this.min=nr(t)?Math.max(0,t):null,this.max=nr(n)?Math.max(0,n):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!nr(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=Qxe(n,this);return t.bounds==="ticks"&&DB(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":Ub(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=oc(t),this._valueRange=oc(this.max)-oc(t)}getPixelForValue(t){return(t===void 0||t===0)&&(t=this.min),t===null||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(oc(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const n=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+n*this._valueRange)}}Ae(Dh,"id","logarithmic"),Ae(Dh,"defaults",{ticks:{callback:w1.formatters.logarithmic,major:{enabled:!0}}});function hk(e){const t=e.ticks;if(t.display&&e.display){const n=Lr(t.backdropPadding);return ct(t.font&&t.font.size,Pn.font.size)+n.height}return 0}function Jxe(e,t,n){return n=gn(n)?n:[n],{w:ame(e,t.string,n),h:n.length*t.lineHeight}}function FO(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 e0e(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=Jxe(e.ctx,f,e._pointLabels[l]);r[l]=h;const p=co(e.getIndexAngle(l)+a),m=Math.round(FM(p)),g=FO(m,d.x,h.w,0,180),b=FO(m,d.y,h.h,90,270);t0e(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=s0e(e,r,s)}function t0e(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 n0e(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(FM(co(l.angle+lr))),d=a0e(l.y,a.h,u),f=o0e(u),h=i0e(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 r0e(e,t){if(!t)return!0;const{left:n,top:r,right:s,bottom:o}=e;return!(ol({x:n,y:r},t)||ol({x:n,y:o},t)||ol({x:s,y:r},t)||ol({x:s,y:o},t))}function s0e(e,t,n){const r=[],s=e._pointLabels.length,o=e.options,{centerPointLabels:i,display:a}=o.pointLabels,l={extra:hk(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=n0e(e,d,l);r.push(f),a==="auto"&&(f.visible=r0e(f,u),f.visible&&(u=f))}return r}function o0e(e){return e===0||e===180?"center":e<180?"left":"right"}function i0e(e,t,n){return n==="right"?e-=t:n==="center"&&(e-=t/2),e}function a0e(e,t,n){return n===90||n===270?e-=t/2:(n>270||n<90)&&(e-=t),e}function l0e(e,t,n){const{left:r,top:s,right:o,bottom:i}=n,{backdropColor:a}=t;if(!St(a)){const l=ml(t.borderRadius),u=Lr(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(),pl(e,{x:d,y:f,w:h,h:p,radius:l}),e.fill()):e.fillRect(d,f,h,p)}}function c0e(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));l0e(n,i,o);const a=_n(i.font),{x:l,y:u,textAlign:d}=o;Nd(n,e._pointLabels[s],l,u+a.lineHeight/2,a,{color:i.color,textAlign:d,textBaseline:"middle"})}}function vV(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 u0e(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(),vV(e,n,i,r),o.closePath(),o.stroke(),o.restore())}function d0e(e,t,n){return Uc(e,{label:n,index:t,type:"pointLabel"})}class Cm extends Sv{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=Lr(hk(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=nr(t)&&!isNaN(t)?t:0,this.max=nr(n)&&!isNaN(n)?n:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/hk(this.options))}generateTickLabels(t){Sv.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map((n,r)=>{const s=hn(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?e0e(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 co(t*n+wi(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 d0e(this.getContext(),t,r)}}getPointPosition(t,n,r=0){const s=this.getIndexAngle(t)-lr+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(),vV(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&&c0e(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);u0e(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=Lr(u.backdropPadding);t.fillRect(-i/2-f.left,-o-d.size/2-f.top,i+f.width,d.size+f.height)}Nd(t,a.label,0,-o,d,{color:u.color,strokeColor:u.textStrokeColor,strokeWidth:u.textStrokeWidth})}),t.restore()}drawTitle(){}}Ae(Cm,"id","radialLinear"),Ae(Cm,"defaults",{display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:w1.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback(t){return t},padding:5,centerPointLabels:!1}}),Ae(Cm,"defaultRoutes",{"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"}),Ae(Cm,"descriptors",{angleLines:{_fallback:"grid"}});const N1={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}},Us=Object.keys(N1);function $O(e,t){return e-t}function LO(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)),nr(i)||(i=typeof r=="string"?n.parse(i,r):n.parse(i)),i===null?null:(s&&(i=s==="week"&&(Sd(o)||o===!0)?n.startOf(i,"isoWeek",o):n.startOf(i,s)),+i)}function zO(e,t,n,r){const s=Us.length;for(let o=Us.indexOf(e);o<s-1;++o){const i=N1[Us[o]],a=i.steps?i.steps:Number.MAX_SAFE_INTEGER;if(i.common&&Math.ceil((n-t)/(a*i.size))<=r)return Us[o]}return Us[s-1]}function f0e(e,t,n,r,s){for(let o=Us.length-1;o>=Us.indexOf(n);o--){const i=Us[o];if(N1[i].common&&e._adapter.diff(s,r,i)>=t-1)return i}return Us[n?Us.indexOf(n):0]}function h0e(e){for(let t=Us.indexOf(e)+1,n=Us.length;t<n;++t)if(N1[Us[t]].common)return Us[t]}function BO(e,t,n){if(!n)e[t]=!0;else if(n.length){const{lo:r,hi:s}=$M(n,t),o=n[r]>=t?n[r]:n[s];e[o]=!0}}function p0e(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 VO(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:p0e(e,r,s,n)}class Pg extends Wc{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 Cge._date(t.adapters.date);s.init(n),Wm(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:LO(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=nr(s)&&!isNaN(s)?s:+n.startOf(Date.now(),r),o=nr(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=Gpe(s,o,i);return this._unit=n.unit||(r.autoSkip?zO(n.minUnit,this.min,this.max,this._getLabelCapacity(o)):f0e(this,a.length,n.minUnit,this.min,this.max)),this._majorUnit=!r.major.enabled||this._unit==="year"?void 0:h0e(this._unit),this.initOffsets(s),t.reverse&&a.reverse(),VO(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||zO(o.minUnit,n,r,this._getLabelCapacity(n)),a=ct(s.ticks.stepSize,1),l=i==="week"?o.isoWeekday:!1,u=Sd(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++)BO(d,h,m);return(h===r||s.bounds==="ticks"||p===1)&&BO(d,h,m),Object.keys(d).sort($O).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 hn(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=wi(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,VO(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(LO(this,s[n]));return this._cache.labels=this._normalized?t:this.normalize(t)}normalize(t){return IB(t.sort($O))}}Ae(Pg,"id","time"),Ae(Pg,"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 m0(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}=sl(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}=sl(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 pk extends Pg{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=m0(n,this.min),this._tableRange=m0(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(m0(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const n=this._offsets,r=this.getDecimalForPixel(t)/n.factor-n.end;return m0(this._table,r*this._tableRange+this._minPos,!0)}}Ae(pk,"id","timeseries"),Ae(pk,"defaults",Pg.defaults);var m0e=Object.freeze({__proto__:null,CategoryScale:Ig,LinearScale:jd,LogarithmicScale:Dh,RadialLinearScale:Cm,TimeScale:Pg,TimeSeriesScale:pk});const g0e=[Sge,Qbe,qxe,m0e];class Ec{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*b0e(e){for(const t of e)yield*t}function wV(e){return Array.from(b0e(e))}function Tf(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,XM=1e-12,Rt=Math.PI,tr=Rt/2,HO=Rt/4,vo=Rt*2,bs=180/Rt,pn=Rt/180,Zt=Math.abs,gp=Math.atan,Sa=Math.atan2,wt=Math.cos,g0=Math.ceil,SV=Math.exp,Cv=Math.log,tN=Math.pow,pt=Math.sin,Lo=Math.sign||function(e){return e>0?1:e<0?-1:0},ks=Math.sqrt,QM=Math.tan;function CV(e){return e>1?0:e<-1?Rt:Math.acos(e)}function Zo(e){return e>1?tr:e<-1?-tr:Math.asin(e)}function Tr(){}function Nv(e,t){e&&WO.hasOwnProperty(e.type)&&WO[e.type](e,t)}var UO={Feature:function(e,t){Nv(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,s=n.length;++r<s;)Nv(n[r].geometry,t)}},WO={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){mk(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)mk(n[r],t,0)},Polygon:function(e,t){qO(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)qO(n[r],t)},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,s=n.length;++r<s;)Nv(n[r],t)}};function mk(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 qO(e,t){var n=-1,r=e.length;for(t.polygonStart();++n<r;)mk(e[n],t,1);t.polygonEnd()}function ku(e,t){e&&UO.hasOwnProperty(e.type)?UO[e.type](e,t):Nv(e,t)}function gk(e){return[Sa(e[1],e[0]),Zo(e[2])]}function Th(e){var t=e[0],n=e[1],r=wt(n);return[r*wt(t),r*pt(t),pt(n)]}function b0(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function jv(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 nN(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function x0(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function bk(e){var t=ks(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function xk(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 yk(e,t){return Zt(e)>Rt&&(e-=Math.round(e/vo)*vo),[e,t]}yk.invert=yk;function NV(e,t,n){return(e%=vo)?t||n?xk(GO(e),ZO(t,n)):GO(e):t||n?ZO(t,n):yk}function YO(e){return function(t,n){return t+=e,Zt(t)>Rt&&(t-=Math.round(t/vo)*vo),[t,n]}}function GO(e){var t=YO(e);return t.invert=YO(-e),t}function ZO(e,t){var n=wt(e),r=pt(e),s=wt(t),o=pt(t);function i(a,l){var u=wt(l),d=wt(a)*u,f=pt(a)*u,h=pt(l),p=h*n+d*r;return[Sa(f*s-p*o,d*n-h*r),Zo(p*s+f*o)]}return i.invert=function(a,l){var u=wt(l),d=wt(a)*u,f=pt(a)*u,h=pt(l),p=h*s-f*o;return[Sa(f*s+h*o,d*n+p*r),Zo(p*n-d*r)]},i}function x0e(e){e=NV(e[0]*pn,e[1]*pn,e.length>2?e[2]*pn:0);function t(n){return n=e(n[0]*pn,n[1]*pn),n[0]*=bs,n[1]*=bs,n}return t.invert=function(n){return n=e.invert(n[0]*pn,n[1]*pn),n[0]*=bs,n[1]*=bs,n},t}function y0e(e,t,n,r,s,o){if(n){var i=wt(t),a=pt(t),l=r*n;s==null?(s=t+r*vo,o=t-l/2):(s=KO(i,s),o=KO(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=gk([i,-a*wt(d),-a*pt(d)]),e.point(u[0],u[1])}}function KO(e,t){t=Th(t),t[0]-=e,bk(t);var n=CV(-t[1]);return((-t[2]<0?-n:n)+vo-at)%vo}function jV(){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 Dy(e,t){return Zt(e[0]-t[0])<at&&Zt(e[1]-t[1])<at}function y0(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 kV(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(Dy(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 y0(b,m,null,!0)),i.push(y.o=new y0(b,null,y,!1)),o.push(y=new y0(x,m,null,!1)),i.push(y.o=new y0(x,null,y,!0))}}),!!o.length){for(i.sort(t),XO(o),XO(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 XO(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 rN(e){return Zt(e[0])<=Rt?e[0]:Lo(e[0])*((Zt(e[0])+Rt)%vo-Rt)}function EV(e,t){var n=rN(t),r=t[1],s=pt(r),o=[pt(n),-wt(n),0],i=0,a=0,l=new Ec;s===1?r=tr+at:s===-1&&(r=-tr-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=rN(p),g=p[1]/2+HO,b=pt(g),x=wt(g),y=0;y<h;++y,m=w,b=C,x=j,p=v){var v=f[y],w=rN(v),S=v[1]/2+HO,C=pt(S),j=wt(S),_=w-m,k=_>=0?1:-1,E=k*_,T=E>Rt,R=b*C;if(l.add(Sa(R*k*pt(E),x*j+R*wt(E))),i+=T?_+k*vo:_,T^m>=n^w>=n){var O=jv(Th(p),Th(v));bk(O);var D=jv(o,O);bk(D);var I=(T^_>=0?-1:1)*Zo(D[2]);(r>I||r===I&&(O[0]||O[1]))&&(a+=T^_>=0?1:-1)}}return(i<-at||i<at&&l<-XM)^a&1}function _V(e,t,n,r){return function(s){var o=t(s),i=jV(),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=wV(d);var w=EV(u,r);d.length?(l||(s.polygonStart(),l=!0),kV(d,w0e,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,_,k,E;if(f.pop(),u.push(f),f=null,!!j){if(w&1){if(k=S[0],(_=k.length-1)>0){for(l||(s.polygonStart(),l=!0),s.lineStart(),C=0;C<_;++C)s.point((E=k[C])[0],E[1]);s.lineEnd()}return}j>1&&w&2&&S.push(S.pop().concat(S.shift())),d.push(S.filter(v0e))}}return h}}function v0e(e){return e.length>1}function w0e(e,t){return((e=e.x)[0]<0?e[1]-tr-at:tr-e[1])-((t=t.x)[0]<0?t[1]-tr-at:tr-t[1])}const QO=_V(function(){return!0},S0e,N0e,[-Rt,-tr]);function S0e(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=Zt(o-t);Zt(l-Rt)<at?(e.point(t,n=(n+i)/2>0?tr:-tr),e.point(r,n),e.lineEnd(),e.lineStart(),e.point(a,n),e.point(o,n),s=0):r!==a&&l>=Rt&&(Zt(t-r)<at&&(t-=r*at),Zt(o-a)<at&&(o-=a*at),n=C0e(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 C0e(e,t,n,r){var s,o,i=pt(e-n);return Zt(i)>at?gp((pt(t)*(o=wt(r))*pt(n)-pt(r)*(s=wt(t))*pt(e))/(s*o*i)):(t+r)/2}function N0e(e,t,n,r){var s;if(e==null)s=n*tr,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(Zt(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 j0e(e){var t=wt(e),n=2*pn,r=t>0,s=Zt(t)>at;function o(d,f,h,p){y0e(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||Dy(f,v)||Dy(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||!Dy(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=Th(d),m=Th(f),g=[1,0,0],b=jv(p,m),x=b0(b,b),y=b[0],v=x-y*y;if(!v)return!h&&d;var w=t*x/v,S=-t*y/v,C=jv(g,b),j=x0(g,w),_=x0(b,S);nN(j,_);var k=C,E=b0(j,k),T=b0(k,k),R=E*E-T*(b0(j,j)-1);if(!(R<0)){var O=ks(R),D=x0(k,(-E-O)/T);if(nN(D,j),D=gk(D),!h)return D;var I=d[0],F=f[0],B=d[1],V=f[1],$;F<I&&($=I,I=F,F=$);var P=F-I,H=Zt(P-Rt)<at,L=H||P<at;if(!H&&V<B&&($=B,B=V,V=$),L?H?B+V>0^D[1]<(Zt(D[0]-I)<at?B:V):B<=D[1]&&D[1]<=V:P>Rt^(I<=D[0]&&D[0]<=F)){var A=x0(k,(-E+O)/T);return nN(A,j),[D,gk(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 _V(i,a,o,r?[0,-e]:[-Rt,e-Rt])}function k0e(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 Nm=1e9,v0=-Nm;function E0e(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 Zt(u[0]-e)<at?d>0?0:3:Zt(u[0]-n)<at?d>0?2:1:Zt(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=jV(),h,p,m,g,b,x,y,v,w,S,C,j={point:_,lineStart:R,lineEnd:O,polygonStart:E,polygonEnd:T};function _(I,F){s(I,F)&&d.point(I,F)}function k(){for(var I=0,F=0,B=p.length;F<B;++F)for(var V=p[F],$=1,P=V.length,H=V[0],L,A,W=H[0],q=H[1];$<P;++$)L=W,A=q,H=V[$],W=H[0],q=H[1],A<=r?q>r&&(W-L)*(r-A)>(q-A)*(e-L)&&++I:q<=r&&(W-L)*(r-A)<(q-A)*(e-L)&&--I;return I}function E(){d=f,h=[],p=[],C=!0}function T(){var I=k(),F=C&&I,B=(h=wV(h)).length;(F||B)&&(u.polygonStart(),F&&(u.lineStart(),o(null,null,1,u),u.lineEnd()),B&&kV(h,a,I,o,u),u.polygonEnd()),d=u,h=p=m=null}function R(){j.point=D,p&&p.push(m=[]),S=!0,w=!1,y=v=NaN}function O(){h&&(D(g,b),x&&w&&f.rejoin(),h.push(f.result())),j.point=_,w&&d.lineEnd()}function D(I,F){var B=s(I,F);if(p&&m.push([I,F]),S)g=I,b=F,x=B,S=!1,B&&(d.lineStart(),d.point(I,F));else if(B&&w)d.point(I,F);else{var V=[y=Math.max(v0,Math.min(Nm,y)),v=Math.max(v0,Math.min(Nm,v))],$=[I=Math.max(v0,Math.min(Nm,I)),F=Math.max(v0,Math.min(Nm,F))];k0e(V,$,e,t,n,r)?(w||(d.lineStart(),d.point(V[0],V[1])),d.point($[0],$[1]),B||d.lineEnd(),C=!1):B&&(d.lineStart(),d.point(I,F),C=!1)}y=I,v=F,w=B}return j}}var vk,wk,Ty,Ry,Rh={sphere:Tr,point:Tr,lineStart:_0e,lineEnd:Tr,polygonStart:Tr,polygonEnd:Tr};function _0e(){Rh.point=D0e,Rh.lineEnd=M0e}function M0e(){Rh.point=Rh.lineEnd=Tr}function D0e(e,t){e*=pn,t*=pn,wk=e,Ty=pt(t),Ry=wt(t),Rh.point=T0e}function T0e(e,t){e*=pn,t*=pn;var n=pt(t),r=wt(t),s=Zt(e-wk),o=wt(s),i=pt(s),a=r*i,l=Ry*n-Ty*r*o,u=Ty*n+Ry*r*o;vk.add(Sa(ks(a*a+l*l),u)),wk=e,Ty=n,Ry=r}function R0e(e){return vk=new Ec,ku(e,Rh),+vk}var Sk=[null,null],I0e={type:"LineString",coordinates:Sk};function Ck(e,t){return Sk[0]=e,Sk[1]=t,R0e(I0e)}var JO={Feature:function(e,t){return kv(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,s=n.length;++r<s;)if(kv(n[r].geometry,t))return!0;return!1}},e5={Sphere:function(){return!0},Point:function(e,t){return t5(e.coordinates,t)},MultiPoint:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(t5(n[r],t))return!0;return!1},LineString:function(e,t){return n5(e.coordinates,t)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(n5(n[r],t))return!0;return!1},Polygon:function(e,t){return r5(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,s=n.length;++r<s;)if(r5(n[r],t))return!0;return!1},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,s=n.length;++r<s;)if(kv(n[r],t))return!0;return!1}};function kv(e,t){return e&&e5.hasOwnProperty(e.type)?e5[e.type](e,t):!1}function t5(e,t){return Ck(e,t)===0}function n5(e,t){for(var n,r,s,o=0,i=e.length;o<i;o++){if(r=Ck(e[o],t),r===0||o>0&&(s=Ck(e[o],e[o-1]),s>0&&n<=s&&r<=s&&(n+r-s)*(1-Math.pow((n-r)/s,2))<XM*s))return!0;n=r}return!1}function r5(e,t){return!!EV(e.map(A0e),MV(t))}function A0e(e){return e=e.map(MV),e.pop(),e}function MV(e){return[e[0]*pn,e[1]*pn]}function P0e(e,t){return(e&&JO.hasOwnProperty(e.type)?JO[e.type]:kv)(e,t)}function s5(e,t,n){var r=Tf(e,t-at,n).concat(t);return function(s){return r.map(function(o){return[s,o]})}}function o5(e,t,n){var r=Tf(e,t-at,n).concat(t);return function(s){return r.map(function(o){return[o,s]})}}function DV(){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 Tf(g0(r/d)*d,n,d).map(m).concat(Tf(g0(a/f)*f,i,f).map(g)).concat(Tf(g0(t/l)*l,e,l).filter(function(v){return Zt(v%d)>at}).map(h)).concat(Tf(g0(o/u)*u,s,u).filter(function(v){return Zt(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=s5(o,s,90),p=o5(t,e,b),m=s5(a,i,90),g=o5(r,n,b),x):b},x.extentMajor([[-180,-90+at],[180,90-at]]).extentMinor([[-180,-80-at],[180,80+at]])}function O0e(){return DV()()}const Nk=e=>e;var sN=new Ec,jk=new Ec,TV,RV,kk,Ek,Qa={point:Tr,lineStart:Tr,lineEnd:Tr,polygonStart:function(){Qa.lineStart=F0e,Qa.lineEnd=L0e},polygonEnd:function(){Qa.lineStart=Qa.lineEnd=Qa.point=Tr,sN.add(Zt(jk)),jk=new Ec},result:function(){var e=sN/2;return sN=new Ec,e}};function F0e(){Qa.point=$0e}function $0e(e,t){Qa.point=IV,TV=kk=e,RV=Ek=t}function IV(e,t){jk.add(Ek*e-kk*t),kk=e,Ek=t}function L0e(){IV(TV,RV)}var Ih=1/0,Ev=Ih,Og=-Ih,_v=Og,Mv={point:z0e,lineStart:Tr,lineEnd:Tr,polygonStart:Tr,polygonEnd:Tr,result:function(){var e=[[Ih,Ev],[Og,_v]];return Og=_v=-(Ev=Ih=1/0),e}};function z0e(e,t){e<Ih&&(Ih=e),e>Og&&(Og=e),t<Ev&&(Ev=t),t>_v&&(_v=t)}var _k=0,Mk=0,jm=0,Dv=0,Tv=0,Rf=0,Dk=0,Tk=0,km=0,AV,PV,ca,ua,$o={point:kd,lineStart:i5,lineEnd:a5,polygonStart:function(){$o.lineStart=H0e,$o.lineEnd=U0e},polygonEnd:function(){$o.point=kd,$o.lineStart=i5,$o.lineEnd=a5},result:function(){var e=km?[Dk/km,Tk/km]:Rf?[Dv/Rf,Tv/Rf]:jm?[_k/jm,Mk/jm]:[NaN,NaN];return _k=Mk=jm=Dv=Tv=Rf=Dk=Tk=km=0,e}};function kd(e,t){_k+=e,Mk+=t,++jm}function i5(){$o.point=B0e}function B0e(e,t){$o.point=V0e,kd(ca=e,ua=t)}function V0e(e,t){var n=e-ca,r=t-ua,s=ks(n*n+r*r);Dv+=s*(ca+e)/2,Tv+=s*(ua+t)/2,Rf+=s,kd(ca=e,ua=t)}function a5(){$o.point=kd}function H0e(){$o.point=W0e}function U0e(){OV(AV,PV)}function W0e(e,t){$o.point=OV,kd(AV=ca=e,PV=ua=t)}function OV(e,t){var n=e-ca,r=t-ua,s=ks(n*n+r*r);Dv+=s*(ca+e)/2,Tv+=s*(ua+t)/2,Rf+=s,s=ua*e-ca*t,Dk+=s*(ca+e),Tk+=s*(ua+t),km+=s*3,kd(ca=e,ua=t)}function FV(e){this._context=e}FV.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 Rk=new Ec,oN,$V,LV,Em,_m,Fg={point:Tr,lineStart:function(){Fg.point=q0e},lineEnd:function(){oN&&zV($V,LV),Fg.point=Tr},polygonStart:function(){oN=!0},polygonEnd:function(){oN=null},result:function(){var e=+Rk;return Rk=new Ec,e}};function q0e(e,t){Fg.point=zV,$V=Em=e,LV=_m=t}function zV(e,t){Em-=e,_m-=t,Rk.add(ks(Em*Em+_m*_m)),Em=e,_m=t}let l5,Rv,c5,u5;class d5{constructor(t){this._append=t==null?BV:Y0e(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!==c5||this._append!==Rv){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`,c5=r,Rv=this._append,u5=this._,this._=s}this._+=u5;break}}}result(){const t=this._;return this._="",t.length?t:null}}function BV(e){let t=1;this._+=e[0];for(const n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function Y0e(e){const t=Math.floor(e);if(!(t>=0))throw new RangeError(`invalid digits: ${e}`);if(t>15)return BV;if(t!==l5){const n=10**t;l5=t,Rv=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 Rv}function f5(e,t){let n=3,r=4.5,s,o;function i(a){return a&&(typeof r=="function"&&o.pointRadius(+r.apply(this,arguments)),ku(a,s(o))),o.result()}return i.area=function(a){return ku(a,s(Qa)),Qa.result()},i.measure=function(a){return ku(a,s(Fg)),Fg.result()},i.bounds=function(a){return ku(a,s(Mv)),Mv.result()},i.centroid=function(a){return ku(a,s($o)),$o.result()},i.projection=function(a){return arguments.length?(s=a==null?(e=null,Nk):(e=a).stream,i):e},i.context=function(a){return arguments.length?(o=a==null?(t=null,new d5(n)):new FV(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 d5(n)),i},i.projection(e).digits(n).context(t)}function JM(e){return function(t){var n=new Ik;for(var r in e)n[r]=e[r];return n.stream=t,n}}function Ik(){}Ik.prototype={constructor:Ik,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 eD(e,t,n){var r=e.clipExtent&&e.clipExtent();return e.scale(150).translate([0,0]),r!=null&&e.clipExtent(null),ku(n,e.stream(Mv)),t(Mv.result()),r!=null&&e.clipExtent(r),e}function tD(e,t,n){return eD(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 VV(e,t,n){return tD(e,[[0,0],t],n)}function HV(e,t,n){return eD(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 UV(e,t,n){return eD(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 h5=16,G0e=wt(30*pn);function p5(e,t){return+t?K0e(e,t):Z0e(e)}function Z0e(e){return JM({point:function(t,n){t=e(t,n),this.stream.point(t[0],t[1])}})}function K0e(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=ks(w*w+S*S+C*C),_=Zo(C/=j),k=Zt(Zt(C)-1)<at||Zt(o-f)<at?(o+f)/2:Sa(S,w),E=e(k,_),T=E[0],R=E[1],O=T-r,D=R-s,I=y*O-x*D;(I*I/v>t||Zt((x*O+y*D)/v-.5)>.3||i*h+a*p+l*m<G0e)&&(n(r,s,o,i,a,l,T,R,k,w/=j,S/=j,C,g,b),b.point(T,R),n(T,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(_,k){_=e(_,k),r.point(_[0],_[1])}function y(){f=NaN,b.point=v,r.lineStart()}function v(_,k){var E=Th([_,k]),T=e(_,k);n(f,h,d,p,m,g,f=T[0],h=T[1],d=_,p=E[0],m=E[1],g=E[2],h5,r),r.point(f,h)}function w(){b.point=x,r.lineEnd()}function S(){y(),b.point=C,b.lineEnd=j}function C(_,k){v(s=_,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,h5,r),b.lineEnd=w,w()}return b}}var X0e=JM({point:function(e,t){this.stream.point(e*pn,t*pn)}});function Q0e(e){return JM({point:function(t,n){var r=e(t,n);return this.stream.point(r[0],r[1])}})}function J0e(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 m5(e,t,n,r,s,o){if(!o)return J0e(e,t,n,r,s);var i=wt(o),a=pt(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 El(e){return WV(function(){return e})()}function WV(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=QO,b=null,x,y,v,w=Nk,S=.5,C,j,_,k,E;function T(I){return _(I[0]*pn,I[1]*pn)}function R(I){return I=_.invert(I[0],I[1]),I&&[I[0]*bs,I[1]*bs]}T.stream=function(I){return k&&E===I?k:k=X0e(Q0e(d)(g(C(w(E=I)))))},T.preclip=function(I){return arguments.length?(g=I,m=void 0,D()):g},T.postclip=function(I){return arguments.length?(w=I,b=x=y=v=null,D()):w},T.clipAngle=function(I){return arguments.length?(g=+I?j0e(m=I*pn):(m=null,QO),D()):m*bs},T.clipExtent=function(I){return arguments.length?(w=I==null?(b=x=y=v=null,Nk):E0e(b=+I[0][0],x=+I[0][1],y=+I[1][0],v=+I[1][1]),D()):b==null?null:[[b,x],[y,v]]},T.scale=function(I){return arguments.length?(n=+I,O()):n},T.translate=function(I){return arguments.length?(r=+I[0],s=+I[1],O()):[r,s]},T.center=function(I){return arguments.length?(o=I[0]%360*pn,i=I[1]%360*pn,O()):[o*bs,i*bs]},T.rotate=function(I){return arguments.length?(a=I[0]%360*pn,l=I[1]%360*pn,u=I.length>2?I[2]%360*pn:0,O()):[a*bs,l*bs,u*bs]},T.angle=function(I){return arguments.length?(f=I%360*pn,O()):f*bs},T.reflectX=function(I){return arguments.length?(h=I?-1:1,O()):h<0},T.reflectY=function(I){return arguments.length?(p=I?-1:1,O()):p<0},T.precision=function(I){return arguments.length?(C=p5(j,S=I*I),D()):ks(S)},T.fitExtent=function(I,F){return tD(T,I,F)},T.fitSize=function(I,F){return VV(T,I,F)},T.fitWidth=function(I,F){return HV(T,I,F)},T.fitHeight=function(I,F){return UV(T,I,F)};function O(){var I=m5(n,0,0,h,p,f).apply(null,t(o,i)),F=m5(n,r-I[0],s-I[1],h,p,f);return d=NV(a,l,u),j=xk(t,F),_=xk(d,j),C=p5(j,S),D()}function D(){return k=E=null,T}return function(){return t=e.apply(this,arguments),T.invert=t.invert&&R,O()}}function nD(e){var t=0,n=Rt/3,r=WV(e),s=r(t,n);return s.parallels=function(o){return arguments.length?r(t=o[0]*pn,n=o[1]*pn):[t*bs,n*bs]},s}function eye(e){var t=wt(e);function n(r,s){return[r*t,pt(s)/t]}return n.invert=function(r,s){return[r/t,Zo(s*t)]},n}function tye(e,t){var n=pt(e),r=(n+pt(t))/2;if(Zt(r)<at)return eye(e);var s=1+n*(2*r-n),o=ks(s)/r;function i(a,l){var u=ks(s-2*r*pt(l))/r;return[u*pt(a*=r),o-u*wt(a)]}return i.invert=function(a,l){var u=o-l,d=Sa(a,Zt(u))*Lo(u);return u*r<0&&(d-=Rt*Lo(a)*Lo(u)),[d/r,Zo((s-(a*a+u*u)*r*r)/(2*r))]},i}function Iv(){return nD(tye).scale(155.424).center([0,33.6442])}function qV(){return Iv().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function nye(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 rye(){var e,t,n=qV(),r,s=Iv().rotate([154,0]).center([-2,58.5]).parallels([55,65]),o,i=Iv().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=nye([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 tD(d,h,p)},d.fitSize=function(h,p){return VV(d,h,p)},d.fitWidth=function(h,p){return HV(d,h,p)},d.fitHeight=function(h,p){return UV(d,h,p)};function f(){return e=t=null,d}return d.scale(1070)}function YV(e){return function(t,n){var r=wt(t),s=wt(n),o=e(r*s);return o===1/0?[2,0]:[o*s*pt(t),o*pt(n)]}}function Wb(e){return function(t,n){var r=ks(t*t+n*n),s=e(r),o=pt(s),i=wt(s);return[Sa(t*o,r*i),Zo(r&&n*o/r)]}}var GV=YV(function(e){return ks(2/(1+e))});GV.invert=Wb(function(e){return 2*Zo(e/2)});function sye(){return El(GV).scale(124.75).clipAngle(180-.001)}var ZV=YV(function(e){return(e=CV(e))&&e/pt(e)});ZV.invert=Wb(function(e){return e});function oye(){return El(ZV).scale(79.4188).clipAngle(180-.001)}function j1(e,t){return[e,Cv(QM((tr+t)/2))]}j1.invert=function(e,t){return[e,2*gp(SV(t))-tr]};function iye(){return KV(j1).scale(961/vo)}function KV(e){var t=El(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(x0e(t.rotate()).invert([0,0]));return o(i==null?[[h[0]-f,h[1]-f],[h[0]+f,h[1]+f]]:e===j1?[[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 w0(e){return QM((tr+e)/2)}function aye(e,t){var n=wt(e),r=e===t?pt(e):Cv(n/wt(t))/Cv(w0(t)/w0(e)),s=n*tN(w0(e),r)/r;if(!r)return j1;function o(i,a){s>0?a<-tr+at&&(a=-tr+at):a>tr-at&&(a=tr-at);var l=s/tN(w0(a),r);return[l*pt(r*i),s-l*wt(r*i)]}return o.invert=function(i,a){var l=s-a,u=Lo(r)*ks(i*i+l*l),d=Sa(i,Zt(l))*Lo(l);return l*r<0&&(d-=Rt*Lo(i)*Lo(l)),[d/r,2*gp(tN(s/u,1/r))-tr]},o}function lye(){return nD(aye).scale(109.5).parallels([30,30])}function Av(e,t){return[e,t]}Av.invert=Av;function cye(){return El(Av).scale(152.63)}function uye(e,t){var n=wt(e),r=e===t?pt(e):(n-wt(t))/(t-e),s=n/r+e;if(Zt(r)<at)return Av;function o(i,a){var l=s-a,u=r*i;return[l*pt(u),s-l*wt(u)]}return o.invert=function(i,a){var l=s-a,u=Sa(i,Zt(l))*Lo(l);return l*r<0&&(u-=Rt*Lo(i)*Lo(l)),[u/r,s-Lo(r)*ks(i*i+l*l)]},o}function dye(){return nD(uye).scale(131.154).center([0,13.9389])}var Km=1.340264,Xm=-.081106,Qm=893e-6,Jm=.003796,Pv=ks(3)/2,fye=12;function XV(e,t){var n=Zo(Pv*pt(t)),r=n*n,s=r*r*r;return[e*wt(n)/(Pv*(Km+3*Xm*r+s*(7*Qm+9*Jm*r))),n*(Km+Xm*r+s*(Qm+Jm*r))]}XV.invert=function(e,t){for(var n=t,r=n*n,s=r*r*r,o=0,i,a,l;o<fye&&(a=n*(Km+Xm*r+s*(Qm+Jm*r))-t,l=Km+3*Xm*r+s*(7*Qm+9*Jm*r),n-=i=a/l,r=n*n,s=r*r*r,!(Zt(i)<XM));++o);return[Pv*e*(Km+3*Xm*r+s*(7*Qm+9*Jm*r))/wt(n),Zo(pt(n)/Pv)]};function hye(){return El(XV).scale(177.158)}function QV(e,t){var n=wt(t),r=wt(e)*n;return[n*pt(e)/r,pt(t)/r]}QV.invert=Wb(gp);function pye(){return El(QV).scale(144.049).clipAngle(60)}function JV(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)))]}JV.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(Zt(s)>at&&--r>0);return[e/(.8707+(o=n*n)*(-.131979+o*(-.013791+o*o*o*(.003971-.001529*o)))),n]};function mye(){return El(JV).scale(175.295)}function eH(e,t){return[wt(t)*pt(e),pt(t)]}eH.invert=Wb(Zo);function gye(){return El(eH).scale(249.5).clipAngle(90+at)}function tH(e,t){var n=wt(t),r=1+wt(e)*n;return[n*pt(e)/r,pt(t)/r]}tH.invert=Wb(function(e){return 2*gp(e)});function bye(){return El(tH).scale(250).clipAngle(142)}function nH(e,t){return[Cv(QM((tr+t)/2)),-e]}nH.invert=function(e,t){return[-t,2*gp(SV(e))-tr]};function xye(){var e=KV(nH),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 k1(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function rD(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function bp(){}var Ed=.7,Ah=1/Ed,Gf="\\s*([+-]?\\d+)\\s*",$g="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ga="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",yye=/^#([0-9a-f]{3,8})$/,vye=new RegExp(`^rgb\\(${Gf},${Gf},${Gf}\\)$`),wye=new RegExp(`^rgb\\(${ga},${ga},${ga}\\)$`),Sye=new RegExp(`^rgba\\(${Gf},${Gf},${Gf},${$g}\\)$`),Cye=new RegExp(`^rgba\\(${ga},${ga},${ga},${$g}\\)$`),Nye=new RegExp(`^hsl\\(${$g},${ga},${ga}\\)$`),jye=new RegExp(`^hsla\\(${$g},${ga},${ga},${$g}\\)$`),g5={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};k1(bp,sD,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:b5,formatHex:b5,formatHex8:kye,formatHsl:Eye,formatRgb:x5,toString:x5});function b5(){return this.rgb().formatHex()}function kye(){return this.rgb().formatHex8()}function Eye(){return sH(this).formatHsl()}function x5(){return this.rgb().formatRgb()}function sD(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=yye.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?y5(t):n===3?new ts(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?S0(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?S0(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=vye.exec(e))?new ts(t[1],t[2],t[3],1):(t=wye.exec(e))?new ts(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Sye.exec(e))?S0(t[1],t[2],t[3],t[4]):(t=Cye.exec(e))?S0(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Nye.exec(e))?S5(t[1],t[2]/100,t[3]/100,1):(t=jye.exec(e))?S5(t[1],t[2]/100,t[3]/100,t[4]):g5.hasOwnProperty(e)?y5(g5[e]):e==="transparent"?new ts(NaN,NaN,NaN,0):null}function y5(e){return new ts(e>>16&255,e>>8&255,e&255,1)}function S0(e,t,n,r){return r<=0&&(e=t=n=NaN),new ts(e,t,n,r)}function rH(e){return e instanceof bp||(e=sD(e)),e?(e=e.rgb(),new ts(e.r,e.g,e.b,e.opacity)):new ts}function Lg(e,t,n,r){return arguments.length===1?rH(e):new ts(e,t,n,r??1)}function ts(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}k1(ts,Lg,rD(bp,{brighter(e){return e=e==null?Ah:Math.pow(Ah,e),new ts(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Ed:Math.pow(Ed,e),new ts(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new ts(ed(this.r),ed(this.g),ed(this.b),Ov(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:v5,formatHex:v5,formatHex8:_ye,formatRgb:w5,toString:w5}));function v5(){return`#${Tu(this.r)}${Tu(this.g)}${Tu(this.b)}`}function _ye(){return`#${Tu(this.r)}${Tu(this.g)}${Tu(this.b)}${Tu((isNaN(this.opacity)?1:this.opacity)*255)}`}function w5(){const e=Ov(this.opacity);return`${e===1?"rgb(":"rgba("}${ed(this.r)}, ${ed(this.g)}, ${ed(this.b)}${e===1?")":`, ${e})`}`}function Ov(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function ed(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Tu(e){return e=ed(e),(e<16?"0":"")+e.toString(16)}function S5(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new pi(e,t,n,r)}function sH(e){if(e instanceof pi)return new pi(e.h,e.s,e.l,e.opacity);if(e instanceof bp||(e=sD(e)),!e)return new pi;if(e instanceof pi)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 pi(i,a,l,e.opacity)}function Mye(e,t,n,r){return arguments.length===1?sH(e):new pi(e,t,n,r??1)}function pi(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}k1(pi,Mye,rD(bp,{brighter(e){return e=e==null?Ah:Math.pow(Ah,e),new pi(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Ed:Math.pow(Ed,e),new pi(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 ts(iN(e>=240?e-240:e+120,s,r),iN(e,s,r),iN(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new pi(C5(this.h),C0(this.s),C0(this.l),Ov(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=Ov(this.opacity);return`${e===1?"hsl(":"hsla("}${C5(this.h)}, ${C0(this.s)*100}%, ${C0(this.l)*100}%${e===1?")":`, ${e})`}`}}));function C5(e){return e=(e||0)%360,e<0?e+360:e}function C0(e){return Math.max(0,Math.min(1,e||0))}function iN(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 Dye=Math.PI/180,Tye=180/Math.PI;var oH=-.14861,oD=1.78277,iD=-.29227,E1=-.90649,zg=1.97294,N5=zg*E1,j5=zg*oD,k5=oD*iD-E1*oH;function Rye(e){if(e instanceof td)return new td(e.h,e.s,e.l,e.opacity);e instanceof ts||(e=rH(e));var t=e.r/255,n=e.g/255,r=e.b/255,s=(k5*r+N5*t-j5*n)/(k5+N5-j5),o=r-s,i=(zg*(n-s)-iD*o)/E1,a=Math.sqrt(i*i+o*o)/(zg*s*(1-s)),l=a?Math.atan2(i,o)*Tye-120:NaN;return new td(l<0?l+360:l,a,s,e.opacity)}function Ca(e,t,n,r){return arguments.length===1?Rye(e):new td(e,t,n,r??1)}function td(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}k1(td,Ca,rD(bp,{brighter(e){return e=e==null?Ah:Math.pow(Ah,e),new td(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Ed:Math.pow(Ed,e),new td(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=isNaN(this.h)?0:(this.h+120)*Dye,t=+this.l,n=isNaN(this.s)?0:this.s*t*(1-t),r=Math.cos(e),s=Math.sin(e);return new ts(255*(t+n*(oH*r+oD*s)),255*(t+n*(iD*r+E1*s)),255*(t+n*(zg*r)),this.opacity)}}));function Iye(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 Aye(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 Iye((n-r/t)*t,i,s,o,a)}}const aD=e=>()=>e;function iH(e,t){return function(n){return e+n*t}}function Pye(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 Oye(e,t){var n=t-e;return n?iH(e,n>180||n<-180?n-360*Math.round(n/360):n):aD(isNaN(e)?t:e)}function Fye(e){return(e=+e)==1?Zf:function(t,n){return n-t?Pye(t,n,e):aD(isNaN(t)?n:t)}}function Zf(e,t){var n=t-e;return n?iH(e,n):aD(isNaN(e)?t:e)}(function e(t){var n=Fye(t);function r(s,o){var i=n((s=Lg(s)).r,(o=Lg(o)).r),a=n(s.g,o.g),l=n(s.b,o.b),u=Zf(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 $ye(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=Lg(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 Lye=$ye(Aye);function aH(e){return function t(n){n=+n;function r(s,o){var i=e((s=Ca(s)).h,(o=Ca(o)).h),a=Zf(s.s,o.s),l=Zf(s.l,o.l),u=Zf(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)}aH(Oye);var lD=aH(Zf);const jn=e=>Lye(e[e.length-1]);var zye=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(tn);const Bye=jn(zye);var Vye=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(tn);const Hye=jn(Vye);var Uye=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(tn);const Wye=jn(Uye);var qye=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(tn);const Yye=jn(qye);var Gye=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(tn);const Zye=jn(Gye);var Kye=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(tn);const Xye=jn(Kye);var Qye=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(tn);const Jye=jn(Qye);var eve=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(tn);const tve=jn(eve);var nve=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(tn);const rve=jn(nve);var sve=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(tn);const ove=jn(sve);var ive=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(tn);const ave=jn(ive);var lve=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(tn);const cve=jn(lve);var uve=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(tn);const dve=jn(uve);var fve=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(tn);const hve=jn(fve);var pve=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(tn);const mve=jn(pve);var gve=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(tn);const bve=jn(gve);var xve=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(tn);const yve=jn(xve);var vve=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(tn);const wve=jn(vve);var Sve=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(tn);const Cve=jn(Sve);var Nve=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(tn);const jve=jn(Nve);var kve=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(tn);const Eve=jn(kve);var _ve=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(tn);const Mve=jn(_ve);var Dve=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(tn);const Tve=jn(Dve);var Rve=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(tn);const Ive=jn(Rve);var Ave=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(tn);const Pve=jn(Ave);var Ove=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(tn);const Fve=jn(Ove);var $ve=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(tn);const Lve=jn($ve);function zve(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 Bve=lD(Ca(300,.5,0),Ca(-240,.5,1));var Vve=lD(Ca(-100,.75,.35),Ca(80,1.5,.8)),Hve=lD(Ca(260,.75,.35),Ca(80,1.5,.8)),N0=Ca();function Uve(e){(e<0||e>1)&&(e-=Math.floor(e));var t=Math.abs(e-.5);return N0.h=360*e-100,N0.s=1.5-1.5*t,N0.l=.8-.9*t,N0+""}var j0=Lg(),Wve=Math.PI/3,qve=Math.PI*2/3;function Yve(e){var t;return e=(.5-e)*Math.PI,j0.r=255*(t=Math.sin(e))*t,j0.g=255*(t=Math.sin(e+Wve))*t,j0.b=255*(t=Math.sin(e+qve))*t,j0+""}function Gve(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 _1(e){var t=e.length;return function(n){return e[Math.max(0,Math.min(t-1,Math.floor(n*t)))]}}const Zve=_1(tn("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var Kve=_1(tn("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),Xve=_1(tn("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),Qve=_1(tn("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function Jve(e){return e}function ewe(e){if(e==null)return Jve;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 twe(e,t){for(var n,r=e.length,s=r-t;s<--r;)n=e[s],e[s++]=e[r],e[r]=n}function nwe(e,t){return typeof t=="string"&&(t=e.objects[t]),t.type==="GeometryCollection"?{type:"FeatureCollection",features:t.geometries.map(function(n){return E5(e,n)})}:E5(e,t)}function E5(e,t){var n=t.id,r=t.bbox,s=t.properties==null?{}:t.properties,o=rwe(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 rwe(e,t){var n=ewe(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&&twe(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 eg={geoAzimuthalEqualArea:sye,geoAzimuthalEquidistant:oye,geoGnomonic:pye,geoOrthographic:gye,geoStereographic:bye,geoEqualEarth:hye,geoAlbers:qV,geoAlbersUsa:rye,geoConicConformal:lye,geoConicEqualArea:Iv,geoConicEquidistant:dye,geoEquirectangular:cye,geoMercator:iye,geoTransverseMercator:xye,geoNaturalEarth1:mye};Object.keys(eg).forEach(e=>{eg[`${e.charAt(3).toLowerCase()}${e.slice(4)}`]=eg[e]});class qd extends Wc{constructor(t){super(t),this.outlineBounds=null,this.oldChartBounds=null,this.geoPath=f5()}init(t){t.position="chartArea",super.init(t),typeof t.projection=="function"?this.projection=t.projection:this.projection=(eg[t.projection]||eg.albersUsa)(),this.geoPath.projection(this.projection),this.outlineBounds=null,this.oldChartBounds=null}computeBounds(t){const n=f5(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}}qd.id="projection";qd.defaults={projection:"albersUsa",projectionScale:1,projectionOffset:[0,0],padding:0};qd.descriptors={_scriptable:e=>e!=="projection",_indexable:e=>e!=="projectionOffset"};const M1={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 swe(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 owe(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=swe(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 If extends jd{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=owe(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 lH extends Dh{constructor(){super(...arguments),this.legendSize={w:0,h:0}}init(t){If.prototype.init.call(this,t)}parse(t,n){return If.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 If.prototype.update.call(this,t,n,r)}_computeLabelArea(){}draw(t){return If.prototype.draw.call(this,t)}_drawIndicator(){}}const Ja={interpolateBlues:Mve,interpolateBrBG:Bye,interpolateBuGn:ove,interpolateBuPu:ave,interpolateCividis:zve,interpolateCool:Hve,interpolateCubehelixDefault:Bve,interpolateGnBu:cve,interpolateGreens:Tve,interpolateGreys:Ive,interpolateInferno:Xve,interpolateMagma:Kve,interpolateOrRd:dve,interpolateOranges:Lve,interpolatePRGn:Hye,interpolatePiYG:Wye,interpolatePlasma:Qve,interpolatePuBu:mve,interpolatePuBuGn:hve,interpolatePuOr:Yye,interpolatePuRd:bve,interpolatePurples:Pve,interpolateRainbow:Uve,interpolateRdBu:Zye,interpolateRdGy:Xye,interpolateRdPu:yve,interpolateRdYlBu:Jye,interpolateRdYlGn:tve,interpolateReds:Fve,interpolateSinebow:Yve,interpolateSpectral:rve,interpolateTurbo:Gve,interpolateViridis:Zve,interpolateWarm:Vve,interpolateYlGn:Cve,interpolateYlGnBu:wve,interpolateYlOrBr:jve,interpolateYlOrRd:Eve};Object.keys(Ja).forEach(e=>{Ja[`${e.charAt(11).toLowerCase()}${e.slice(12)}`]=Ja[e],Ja[e.slice(11)]=Ja[e]});function cH(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 uH={interpolate:"blues",missing:"transparent",quantize:0};class _c extends If{get interpolate(){const t=this.options;return t?typeof t.interpolate=="function"?t.interpolate:Ja[t.interpolate]||Ja.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=cH(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)}}}}_c.id="color";_c.defaults=xr({},[jd.defaults,M1,uH]);_c.descriptors={_scriptable:e=>e!=="interpolate",_indexable:!1};class cD extends lH{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=Ja[t.interpolate]||Ja.blues}getColorForValue(t){return _c.prototype.getColorForValue.call(this,t)}getColor(t){let n=t;return this.options.quantize>0&&(n=cH(n,this.options.quantize)),this.interpolate(n)}_drawIndicator(){return _c.prototype._drawIndicator.call(this)}}cD.id="colorLogarithmic";cD.defaults=xr({},[Dh.defaults,M1,uH]);cD.descriptors={_scriptable:e=>e!=="interpolate",_indexable:!1};const dH={missing:1,mode:"area",range:[2,20],legend:{align:"bottom",length:90,width:70,indicatorWidth:42}};class Mc extends If{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};xv(t,p,f,h)})}}Mc.id="size";Mc.defaults=xr({},[jd.defaults,M1,dH]);Mc.descriptors={_scriptable:!0,_indexable:e=>e!=="range"};class fH extends lH{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 Mc.prototype.getSizeImpl.call(this,t)}_drawIndicator(){Mc.prototype._drawIndicator.call(this)}}fH.id="sizeLogarithmic";fH.defaults=xr({},[Dh.defaults,M1,dH]);function iwe(e,t){return[[e[0][0]-t,e[0][1]-t],[e[1][0]+t,e[1][1]+t]]}class Cl 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&&P0e(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=iwe(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())}}Cl.id="geoFeature";Cl.defaults={...ma.defaults,outlineBackgroundColor:null,outlineBorderWidth:0,graticuleBorderColor:"#CCCCCC",graticuleBorderWidth:0};Cl.defaultRoutes={outlineBorderColor:"borderColor",...ma.defaultRoutes||{}};const hH={showOutline:!1,showGraticule:!1,clipMap:!0},pH={scales:{projection:{axis:"x",type:qd.id,position:"chartArea",display:!1}}};function _5(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 mH extends Zs{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=_5(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=_5(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(O0e());else{const i=DV();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,pc(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||pc(t.ctx,t.chartArea):r&&(r=!1,mc(t.ctx)),this.showGraticule(),n===!0||n==="items"?r||pc(t.ctx,t.chartArea):r&&(r=!1,mc(t.ctx)),this.getMeta().data.forEach(s=>s.draw.call(s,t.ctx,t.chartArea)),r&&(r=!1,mc(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 xp extends mH{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])}}xp.id="choropleth";xp.defaults=xr({},[hH,{datasetElementType:Cl.id,dataElementType:Cl.id}]);xp.overrides=xr({},[pH,{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:_c.id,axis:"x"}},elements:{geoFeature:{backgroundColor(e){return e.dataIndex==null?null:e.chart.getDatasetMeta(e.datasetIndex).controller.indexToColor(e.dataIndex)}}}}]);class awe extends Kt{constructor(t,n){super(t,gH("choropleth",n,xp,Cl,[_c,qd]))}}awe.id=xp.id;class yp extends mH{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])}}yp.id="bubbleMap";yp.defaults=xr({},[hH,{dataElementType:Ju.id,datasetElementType:Cl.id,showOutline:!0,clipMap:"outline+graticule"}]);yp.overrides=xr({},[pH,{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:Mc.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 lwe extends Kt{constructor(t,n){super(t,gH("bubbleMap",n,yp,Cl,[Mc,qd]))}}lwe.id=yp.id;function cwe(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 uwe(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 dwe(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 fwe(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 hwe(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 pwe(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 mwe(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 gwe(e){var r,s;const t=J.getState().theme;let n={...e,type:"radar",options:{...e==null?void 0:e.options,scales:{x:{display:!1},y:{display:!1},r:{grid:{display:!0},angleLines:{},ticks:{}}},plugins:{...(r=e==null?void 0:e.options)==null?void 0:r.plugins,legend:{position:"bottom",align:"center"}}}};return t==="dark"&&(n={...n,options:{...n.options,scales:{...(s=n==null?void 0:n.options)==null?void 0:s.scales,r:{grid:{color:vn.slate[800]},angleLines:{color:vn.slate[800]},ticks:{color:vn.slate[800],showLabelBackdrop:!1}}}}}),n}function bwe(e,t,n){const r={interaction:{mode:"point"},plugins:{tooltip:{callbacks:{label:function(o){var p;const i=o.dataset.label,a=o.dataIndex,l=o.dataset.data,u=(p=l==null?void 0:l[a])==null?void 0:p.label,d=n==null?void 0:n[0],f=n==null?void 0:n[1],h=n==null?void 0:n[2];if(t==="bubble")return u?`${i} (${u}): ${d}: ${o.raw.x.toFixed(2)}, ${f}: ${o.raw.y.toFixed(2)}, ${h}: ${o.raw.r.toFixed(2)}`:`${i}: ${d}: ${o.raw.x.toFixed(2)}, ${f}: ${o.raw.y.toFixed(2)}, ${h}: ${o.raw.r.toFixed(2)}`;if(t==="scatter")return u?`${i} (${u}): ${d}: ${o.raw.x.toFixed(2)}, ${f}: ${o.raw.y.toFixed(2)}`:`${i}: ${d}: ${o.raw.x.toFixed(2)}, ${f}: ${o.raw.y.toFixed(2)}`}}},datalabels:{display:!1}},scales:{x:{title:{display:!0,text:n[0]},beginAtZero:!0,ticks:{precision:0}},y:{title:{display:!0,text:n[1]},beginAtZero:!0,ticks:{precision:0}}}};return{...e,options:{...e==null?void 0:e.options,...r}}}function Ks({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 D1(e,t){if(!t)return"";const n=t.find(r=>e>=r.start&&e<=r.end);return(n==null?void 0:n.color)||""}function xwe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var T,R,O,D,I;const i=((T=r==null?void 0:r.chartOptions)==null?void 0:T.indexAxis)||"y",a={...t,options:{indexAxis:i}},{keys:l}=Gn(e),u=[l[1]],d=l==null?void 0:l[0],f=mB(u,e,r,d),h=Ku(f,n);h.forEach((F,B)=>{var V,$,P;F.shrinkAnchor=((P=($=(V=n==null?void 0:n.data)==null?void 0:V.datasets)==null?void 0:$[B])==null?void 0:P.shrinkAnchor)||"top"});const{plugins:p,options:m}=Wd((r==null?void 0:r.customVisualCode)||""),g=l[0],b=zb(e,g),x=Nr((a==null?void 0:a.options)||{},(n==null?void 0:n.options)||{}),y=Nr(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 B=F.data.labels;return v.map((V,$)=>({text:V,fillStyle:S[$],hidden:!B.includes(V.toString()),index:$,datasetIndex:0,lineWidth:0}))}},onClick:(F,B,V)=>{const $=V.chart,P=B.index,H=v[P],L=$.data.datasets[0],A=$.data.labels,W=L.data,q=L.backgroundColor,Y=A.indexOf(H.toString());Y>=0?(A.splice(Y,1),W.splice(Y,1),q.splice(Y,1)):(A.splice(P,0,v[P].toString()),W.splice(P,0,Number(w[P])),q.splice(P,0,S[P])),$.update()}},datalabels:{...(D=y.plugins)==null?void 0:D.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,B)=>{var V,$,P,H;return Ks({number:Number(F),decimalPlaces:((V=r==null?void 0:r.numberAxisFormat)==null?void 0:V.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:((H=r==null?void 0:r.numberAxisFormat)==null?void 0:H.currency)||""})}},tooltip:{...(I=y.plugins)==null?void 0:I.tooltip,callbacks:{title:function(F){var H,L,A,W;const V=((L=(H=F==null?void 0:F[0])==null?void 0:H.dataset)==null?void 0:L.data).reduce((q,Y)=>q+Y,0),P=(((A=F==null?void 0:F[0])==null?void 0:A.parsed[i==="x"?"y":"x"])/V*100).toFixed(2);return`${(W=F==null?void 0:F[0])==null?void 0:W.label} (${P}%)`},label:function(F){var W,q,Y,U;F.dataset.label;const B=F.dataset.data;B.reduce((z,G)=>z+G,0);const V=F.parsed[i==="x"?"y":"x"],$=B.indexOf(V),P=B[$-1],H=Ks({number:Number(V),decimalPlaces:((W=r==null?void 0:r.numberAxisFormat)==null?void 0:W.decimalPlaces)||0,useSuffix:!!((q=r==null?void 0:r.numberAxisFormat)!=null&&q.suffix),customSuffix:"",locale:((Y=r==null?void 0:r.numberAxisFormat)==null?void 0:Y.locale)||"",currency:((U=r==null?void 0:r.numberAxisFormat)==null?void 0:U.currency)||""});let L=0;return P!==void 0&&(L=Number((V/P*100).toFixed(2))),H+(P!==void 0?` | Conversion: ${L}%`:"")},footer:function(F){var V,$,P,H;return((($=(V=o==null?void 0:o.interactionConfig)==null?void 0:V.drillHierarchies)==null?void 0:$.length)??0)>0||(((H=(P=o==null?void 0:o.interactionConfig)==null?void 0:P.interactions)==null?void 0:H.some(L=>L.mode==="drillDown"||L.mode==="drillToDetail"||L.mode==="drillThrough"||L.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},j=Nr(y,C),_=r!=null&&r.dataLabelsConfig?Vb(j,r.dataLabelsConfig,r,"funnel"):j,k=Nr(_,m);return delete k.scales,{type:s,data:{labels:b,datasets:h},options:k,plugins:[...p]}}function ywe({data:e,cfg:t,customCfg:n,preferences:r,card:s}){var C,j;const o=fwe(t),i=vwe(e),a=Ku(i,n),{plugins:l,options:u}=Wd((r==null?void 0:r.customVisualCode)||""),d=Nr((o==null?void 0:o.options)||{},(t==null?void 0:t.options)||{}),f=Nr(d,(r==null?void 0:r.chartOptions)||{}),h=Nr(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(_){if(Array.isArray(_.raw)&&_.raw.every(k=>k===null))return null},footer:function(_){var E,T,R,O;return(((T=(E=s==null?void 0:s.interactionConfig)==null?void 0:E.drillHierarchies)==null?void 0:T.length)??0)>0||(((O=(R=s==null?void 0:s.interactionConfig)==null?void 0:R.interactions)==null?void 0:O.some(D=>D.mode==="drillDown"||D.mode==="drillToDetail"||D.mode==="drillThrough"||D.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},m=Nr(p,u),g=CB(t,r),b=Nr(m,g);let x;r!=null&&r.dataLabelsConfig?x=Vb(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:(_,k)=>_.map(T=>{var R,O,D,I;return Ks({number:Number(T),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:((D=r==null?void 0:r.numberAxisFormat)==null?void 0:D.locale)||"",currency:((I=r==null?void 0:r.numberAxisFormat)==null?void 0:I.currency)||""})}).slice(0,2).join(" - ")}}};const{keys:y}=Gn(e),v=y[0];return{type:"bar",data:{labels:[...new Set(zb(e,v))],datasets:a},options:x,plugins:[...l]}}function vwe(e){var h,p,m,g;const{keys:t}=Gn(e),n=t.slice(0,2),r=t.slice(2),s=J.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 wwe({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,card:o}){var w;const i=uwe(t),{keys:a}=Gn(e),l=x1({dataArray:e,groupKey:a[0],pivotKey:a[1],valueKey:a[2]}),{keys:u}=Gn(l),d=u.slice(1),f=pB(d,l,r),h=Ku(f,n),p=u[0],m=zb(l,p),{options:g,plugins:b}=Um({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 M5={type:"treemap",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function Swe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s}){var S;if(!e||e.length===0)return M5;const{dimensionKeys:o,metricKeys:i,keys:a}=Gn(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."),M5;const d=kwe(e,l,u),f=s??J.getState().themeStyle,h=((S=r==null?void 0:r.chartOptions)==null?void 0:S.treemapColorMode)??"branch",p=Ewe(d,l,r,f),m=_we(r),g=Cwe({tree:d,dimensionKeys:l,metricKey:u,colorLookups:p,formatConfig:m,themeStyle:f,preferences:r,colorMode:h}),b=Nwe({dimensionKeys:l,metricKey:u,formatConfig:m}),{plugins:x,options:y}=Wd((r==null?void 0:r.customVisualCode)||""),v=jwe([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 Cwe({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=v1("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:_=>{if(!d)return"";const k=_==null?void 0:_.raw,E=bH(k,t),T=Number((k==null?void 0:k.v)??0),R=xH(T,s);return E?`${E}
|
|
763
|
-
${R}`:R},color:_=>{if(f)return f;const k=_==null?void 0:_.raw,E=D5({raw:k,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a});return Bo(E)},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:_=>{const k=_==null?void 0:_.raw;return D5({raw:k,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a})}}}function Nwe({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 Dwe(o==null?void 0:o.raw,e)},label:s=>{const o=s==null?void 0:s.raw,i=bH(o,e),a=Number((o==null?void 0:o.v)??0),l=xH(a,n),u=t||"Value";return i?`${i} — ${u}: ${l}`:`${u}: ${l}`}}}}}}function jwe(e){return e.reduce((t,n)=>Nr(t,n||{}),{})}function kwe(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 Ewe(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))??pp();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 _we(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 bH(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 Mwe(e._data,t);if(e.path){const r=e.path.split("."),s=r[r.length-1];if(s)return s}return""}function Mwe(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 Dwe(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 xH(e,t){return Ws(e,t.format,t.formatOptions)}function D5({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))??pp(),a=Twe(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=uD(f,0,d);if(h===0||o==="category")return u;const p=Rwe(e);return Iwe(u,p,h)}function Twe(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 Rwe(e){if(!e)return 1;const t=Number(e.v??0),n=Number(e.gs??e.s??0);return n>0&&Number.isFinite(t)?uD(t/n,0,1):1}function Iwe(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=uD(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 Awe(i,a,l)}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 Awe(e,t,n){const r=s=>s.toString(16).padStart(2,"0");return`#${r(aN(e))}${r(aN(t))}${r(aN(n))}`}function aN(e){return Math.min(255,Math.max(0,Math.round(e)))}function uD(e,t,n){return Math.max(t,Math.min(n,e))}const yH=["poor","satisfactory","good"],lN={poor:"Poor",satisfactory:"Average",good:"Good"},Pwe=["#F5F6F8","#E3E6EC","#CED4DD"],Owe=["#1F2933","#27323D","#303B47"];function Fwe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s}){var se,ce,ae,he,ye,Te,_e;if(!e||e.length===0)return{type:"bar",data:{labels:[],datasets:[]}};const{dimensionKeys:o,metricKeys:i,keys:a}=Gn(e),l=o[0]??a[0];if(!l)return{type:"bar",data:{labels:[],datasets:[]}};const u=i[0]??a.find(de=>de!==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(de=>de!==u),h=(d==null?void 0:d.comparativeMetricKey)??(d!=null&&d.disableAutoComparative?void 0:i.find(de=>de!==u&&de!==f)),p=J.getState(),m=s??p.themeStyle,g=p.theme==="dark",b=$we({data:e,dimensionKey:l,actualKey:u,targetKey:f,comparativeKey:h,bulletConfig:d}),x=b.map(de=>de.label),y=(d==null?void 0:d.showRanges)??Qwe(d),v=Bwe(b,y),w=(se=r==null?void 0:r.chartOptions)==null?void 0:se.indexAxis,C=(w?w==="y"?"horizontal":"vertical":void 0)??(d==null?void 0:d.orientation)??"horizontal",j=C==="vertical"?"x":"y",_=r?{...r,chartOptions:{...r.chartOptions||{},indexAxis:j}}:{chartOptions:{indexAxis:j}},k=Zwe(r),E=Xwe(d),T=Kwe(g),R=pp().filter(Boolean),O=(((ae=(ce=m==null?void 0:m.chart)==null?void 0:ce.dataset)==null?void 0:ae.backgroundColor)||[]).filter(Boolean),D=(((ye=(he=m==null?void 0:m.chart)==null?void 0:he.dataset)==null?void 0:ye.borderColor)||[]).filter(Boolean),I=O.length>0?O:R.length>0?R:["#3b82f6"],F=D.length>0?D:I.length>0?I:["#111827"],B=uN({metricKey:u,metricIndex:0,preferences:r,backgroundPalette:I,borderPalette:F}),$=uN({metricKey:f||`${u}__target`,metricIndex:1,preferences:r,backgroundPalette:I,borderPalette:F}).borderColor||B.borderColor||"#111827",P=uN({metricKey:h,metricIndex:2,preferences:r,backgroundPalette:I,borderPalette:F}),H=y?Vwe(b,T,C,g,E):[],L=Hwe(b,B,C,u),A=Uwe(b,P,C,h),W=[...H,L];A&&W.push(A);let q=Wwe({orientation:C,chartMax:v,formatConfig:k,series:b,preferences:_,rangeLabelMap:E,showRanges:y});const Y=(_e=(Te=r==null?void 0:r.chartOptions)==null?void 0:Te.plugins)==null?void 0:_e.legend;q=yB(q,Y);const{plugins:U=[],options:z}=Wd((r==null?void 0:r.customVisualCode)||""),G=n1e([q,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,z]),Z=b.some(de=>de.target!=null)&&v>0?Gwe({series:b,orientation:C,color:$}):null,te={type:"bar",data:{labels:x,datasets:W},options:G,plugins:Z?[...U,Z]:U},X=v1("bullet",r),ne=(r==null?void 0:r.dataLabelsConfig)??X;return te.options=Vb(te.options||{},ne,_,"bar"),te.options=Bb.applyAxisConfig(te.options||{},"bar",_),te.options=te.options||{},te.options.indexAxis=j,te}function $we({data:e,dimensionKey:t,actualKey:n,targetKey:r,comparativeKey:s,bulletConfig:o}){const i=e.map(l=>{const u=zwe(l[t]),d=Iy(l[n]),f=r&&l[r]!=null?Iy(l[r]):(o==null?void 0:o.targetValue)??null,h=s&&l[s]!=null?Iy(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=Lwe({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 Lwe({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:cN("poor",e,o,i,a*.5,s,a),satisfactory:cN("satisfactory",e,o,i,a*.8,s,a),good:cN("good",e,o,i,a,s,a)};let u=0;return yH.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 cN(e,t,n,r,s,o,i){const a=n==null?void 0:n[e];if(a&&t[a]!=null)return Iy(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 Iy(e){const t=Number(e);return Number.isFinite(t)?t:0}function zwe(e){return e==null||e===""?"(Blank)":String(e)}function Bwe(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 Vwe(e,t,n,r,s){const o=[];return yH.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:e1e(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 Hwe(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 Uwe(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 Wwe({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=>Ws(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:qwe(r,n,o,i)}},indexAxis:e==="vertical"?"x":"y"}}function qwe(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"}: ${Ws(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=Ws(o.target,t.format,t.options),d=o.actual-o.target,f=Ws(d,t.format,t.options),h=o.targetKey||"Target";i.push(`${h}: ${u} (${f})`)}const a=Ywe(o,n);r&&a&&i.push(`Range: ${a}`);const l=o.comparative;return l!=null&&i.push(`Comparative: ${Ws(l,t.format,t.options)}`),i}}}function Ywe(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 Gwe({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 Zwe(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 Kwe(e){return[...e?Owe:Pwe]}function Xwe(e){var n,r,s;const t=(e==null?void 0:e.rangeLabels)||{};return{poor:((n=t.poor)==null?void 0:n.trim())||lN.poor,satisfactory:((r=t.satisfactory)==null?void 0:r.trim())||lN.satisfactory,good:((s=t.good)==null?void 0:s.trim())||lN.good}}function Qwe(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 Jwe(e,t,n){const r=vH(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=I5(e),o=I5(t);if(!s||!o)return e;const i=Math.round(s.r+(o.r-s.r)*r),a=Math.round(s.g+(o.g-s.g)*r),l=Math.round(s.b+(o.b-s.b)*r);return t1e(i,a,l)}function e1e(e,t,n){return Jwe(e,n?"#000000":"#ffffff",t)}function uN({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 I5(e){const t=e.replace("#","");if(t.length!==6)return null;const n=parseInt(t,16);return{r:n>>16&255,g:n>>8&255,b:n&255}}function t1e(e,t,n){return`#${dN(e)}${dN(t)}${dN(n)}`}function dN(e){return vH(Math.round(e),0,255).toString(16).padStart(2,"0")}function vH(e,t,n){return Math.max(t,Math.min(n,e))}function n1e(e){return e.reduce((t,n)=>Nr(t,n||{}),{})}const Ak={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"}},wH=["#dcfce7","#15803d"],k0={type:"matrix",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function r1e({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o}){var q,Y,U;if(!Array.isArray(e)||e.length===0)return k0;const{dimensionKeys:i,metricKeys:a,keys:l}=Gn(e),u=i[0]??l[0];if(!u)return k0;const d=i[1],f=l.find(z=>z!==u&&!a.includes(z)&&z!==d)??d,h=!d&&(!f||typeof((q=e[0])==null?void 0:q[f])!="string")&&a.length>1,p=a[0]??l.find(z=>z!==u&&z!==f);if(!p&&!h)return k0;const m=r==null?void 0:r.heatmapConfig,g=(m==null?void 0:m.legendPosition)??"bottom",b=h?o1e({data:e,dimensionKey:u,metricKeys:a}):s1e({data:e,xKey:u,yKey:f||p,metricKey:p});if(b.length===0)return k0;const x=h?a.map(Ph):fN(b.map(z=>z.x)),y=fN(h?e.map(z=>Ph(z==null?void 0:z[u])):b.map(z=>z.y)),v=i1e(b),w=o??J.getState().themeStyle,S=f1e({min:v.min,max:v.max,heatmapConfig:m,themeStyle:w}),C=a1e({points:b,xLabels:x,yLabels:y,fill:(m==null?void 0:m.fillMissingCells)!==!1}),j=b1e(r),k=["auto","number","currency","percent","none"].includes(j.format)?j.format:"auto",E=v1("heatmap",r),T=E?{...E,format:E.format??k,formatOptions:E.formatOptions??j.options}:void 0,R=(r==null?void 0:r.dataLabelsConfig)??T,O=l1e({points:C,xLabels:x,yLabels:y,colorScale:S,datasetLabel:h?"Value":p||"Value",dataLabelPrefs:R,formatConfig:j}),D=c1e({xLabels:x,yLabels:y,heatmapConfig:m,formatConfig:j,themeStyle:w,legendPreferences:(U=(Y=r==null?void 0:r.chartOptions)==null?void 0:Y.plugins)==null?void 0:U.legend,cardType:s,legendPosition:g}),{plugins:I=[],options:F}=Wd((r==null?void 0:r.customVisualCode)||""),B=x1e([D,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,F]),V=(m==null?void 0:m.showLegend)===!1?null:h1e({stops:S.stops,min:v.min,max:v.max,formatConfig:j,position:g}),$={type:"matrix",data:{datasets:[O]},options:B,plugins:V?[...I,V]:I};$.options=Vb($.options||{},R,r,"matrix");const P=ek(s??"heatmap","x"),H=ek(s??"heatmap","y"),L=tk(P,r==null?void 0:r.xAxisConfig),A=tk(H,r==null?void 0:r.yAxisConfig),W=L||A||r?{...r||{},...L?{xAxisConfig:L}:{},...A?{yAxisConfig:A}:{}}:r;return $.options=Bb.applyAxisConfig($.options||{},"heatmap",W),$}function s1e({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=Ph(i),u=Ph(a),d=`${l}__${u}`,f=SH(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 o1e({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=Ph(o);n.forEach(a=>{if(a===t)return;const l=SH(s==null?void 0:s[a]),u=Ph(a);r.push({x:u,y:i,v:l,raw:{...s,_metricKey:a}})})}),r}function Ph(e){return e==null||e===""?"Unknown":String(e)}function SH(e){const t=Number(e);return Number.isFinite(t)?t:null}function fN(e){const t=new Set,n=[];return e.forEach(r=>{t.has(r)||(t.add(r),n.push(r))}),n}function i1e(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 a1e({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 l1e({points:e,xLabels:t,yLabels:n,colorScale:r,datasetLabel:s,dataLabelPrefs:o,formatConfig:i}){const a=ipe(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 g1e(h,.85)},borderWidth:1,borderColor:"rgba(255, 255, 255, 0.65)",width:({chart:d})=>{var f;return A5((f=d==null?void 0:d.chartArea)==null?void 0:f.width,t.length)},height:({chart:d})=>{var f;return A5((f=d==null?void 0:d.chartArea)==null?void 0:f.height,n.length)},datalabels:{display:a,anchor:"center",align:"center",formatter:d=>{let f=null;return typeof d=="number"?f=d:d&&typeof d=="object"&&"v"in d&&(f=Number(d.v)),f==null||Number.isNaN(f)?"":dD(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(m1e(h))},font:{size:Math.max(10,Math.min(14,120/l))}}}}function A5(e,t){return!e||t===0?0:Math.max(4,e/t-2)}function c1e({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=wB(i??"heatmap"),f=spe(d,o);return{responsive:!0,maintainAspectRatio:!1,layout:{padding:u1e(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:d1e(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 u1e(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 d1e(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=dD(n.v,e);return s?`${s}: ${o}`:`${r}: ${o}`}}}function f1e({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"?Ak[i]??Ak.blue:void 0,l=n==null?void 0:n.colorRange,u=l&&l[0]&&l[1]?l:a?[a.start,a.end]:i==="custom"?wH: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:P5(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=Bg((w-e)/g,0,1);return P5(du(d),du(f),j)}const S=Bg((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 h1e({stops:e,min:t,max:n,formatConfig:r,position:s}){if(!e||e.length===0)return null;const o=i=>dD(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(fl()),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(_=>C.addColorStop(_.offset,_.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(_=>C.addColorStop(_.offset,_.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=CH(e);return t?p1e(t.r,t.g,t.b,1):e}return e}function P5(e,t,n){const r=Fv(e),s=Fv(t);if(!r||!s)return e;const o=Bg(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 Fv(e){if(e.startsWith("#")){const n=CH(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 CH(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 p1e(e,t,n,r){return`rgba(${e}, ${t}, ${n}, ${r})`}function m1e(e){const t=Fv(e);return t?`#${hN(t.r)}${hN(t.g)}${hN(t.b)}`:"#000000"}function hN(e){return Bg(Math.round(e),0,255).toString(16).padStart(2,"0")}function g1e(e,t){const n=Fv(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${Bg(t,0,1)})`:e}function Bg(e,t,n){return Math.min(n,Math.max(t,e))}function dD(e,t){return e==null||Number.isNaN(e)?"—":Ws(e,t.format,t.options)}function b1e(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 x1e(e){return e.reduce((t,n)=>n?xh({},t,n):t,{})}function fD({card:e,data:t,cardType:n="bar",cfg:r,customCfg:s,provider:o="chartjs",userSettings:i,preferences:a,topoJson:l,queryConfig:u}){var m,g,b,x,y,v,w,S;const d=e.config;let f=t;const h=d&&d.pivotByColumns&&d.pivotByColumns.length>0,p=d&&d.groupByColumns&&d.groupByColumns.length>0;if(h&&p&&(f=tpe(t,(d==null?void 0:d.metricColumns)||[])),n==="map"){if(!l)return null;const C=(m=a==null?void 0:a.mapVisualOptions)==null?void 0:m.objectKey;if(!C)return null;const j=nwe(l,(g=l==null?void 0:l.objects)==null?void 0:g[C]).features;if(!j)return null;const _={plugins:{datalabels:{display:!1}},scales:{x:{display:!1,grid:{display:!1}},y:{display:!1,grid:{display:!1}},projection:{axis:"x",projection:((b=a==null?void 0:a.mapVisualOptions)==null?void 0:b.projection)||"mercator",projectionScale:((x=a==null?void 0:a.mapVisualOptions)==null?void 0:x.projectionScale)||1,projectionOffset:((y=a==null?void 0:a.mapVisualOptions)==null?void 0:y.projectionOffset)||[0,0]},color:{axis:"x",interpolate:((v=a==null?void 0:a.mapVisualOptions)==null?void 0:v.colorScale)||"blues",quantize:5,legend:{position:"bottom-right",align:"right"}}}},{keys:k}=Gn(f),E=j.map(F=>{var P;const B=k==null?void 0:k[0],V=k==null?void 0:k[1],$=(P=f.find(H=>(H==null?void 0:H[B])===F.properties.NAME||(H==null?void 0:H[B])===F.properties.name))==null?void 0:P[V];return{feature:F,value:$}}),R=Ku([{label:C,data:E,borderColor:"lightgray"}],s),O={type:"choropleth",data:{labels:j.map(F=>F.properties.NAME||F.properties.name),datasets:R},options:_},{options:D}=Um({cfg:O,preferences:a,customCfg:s,cardType:n});return{...O,options:D}}if(n==="bar"){const C=dwe(r);return af({card:e,data:f,cfg:C,customCfg:s,cardType:n,preferences:a})}if(n==="horizontalBar"){const C=cwe(r);return af({card:e,data:f,cfg:C,customCfg:s,cardType:n,preferences:a})}if(n==="funnel")return xwe({data:f,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="tornado"||n==="pyramid")return wwe({data:f,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="treemap")return Swe({data:f,cfg:r,customCfg:s,preferences:a});if(n==="heatmap")return r1e({data:f,cfg:r,customCfg:s,preferences:a,cardType:n});if(n==="bullet")return Fwe({data:f,cfg:r,customCfg:s,preferences:a});if(n==="stackedBar"||n==="stackedLine"){const C=hB(f),j=hwe(r,n,C),{keys:_}=Gn(f);return!C&&(!h||!p)&&(f=x1({dataArray:f,groupKey:_[0],pivotKey:_[1],valueKey:_[2],sortChart:a==null?void 0:a.sortChart})),af({card:e,data:f,cfg:j,customCfg:s,cardType:n,preferences:a})}if(n==="line"){const C=pwe(r);return af({card:e,data:f,cfg:C,customCfg:s,cardType:n,preferences:a})}if(n==="range")return ywe({data:f,cfg:r,customCfg:s,preferences:a,card:e});if(n==="pie"||n==="doughnut"||n==="polarArea"){const C=mwe(n,r),{keys:j}=Gn(f),_=j.slice(0,1),k=j.slice(1),E=mB(k,f,a,_==null?void 0:_[0]),T=Ku(E,s),{plugins:R,options:O}=Wd((a==null?void 0:a.customVisualCode)||""),D=_[0],I=zb(f,D),F=Nr((C==null?void 0:C.options)||{},(s==null?void 0:s.options)||{}),B=Nr(F,(a==null?void 0:a.chartOptions)||{}),V={...B,plugins:{...B.plugins,datalabels:{...(w=B.plugins)==null?void 0:w.datalabels,formatter:(W,q)=>{var Y,U,z,G;return Ks({number:Number(W),decimalPlaces:((Y=a==null?void 0:a.numberAxisFormat)==null?void 0:Y.decimalPlaces)||0,useSuffix:!!((U=a==null?void 0:a.numberAxisFormat)!=null&&U.suffix),customSuffix:"",locale:((z=a==null?void 0:a.numberAxisFormat)==null?void 0:z.locale)||"",currency:((G=a==null?void 0:a.numberAxisFormat)==null?void 0:G.currency)||""})}},tooltip:{...(S=B.plugins)==null?void 0:S.tooltip,callbacks:{label:function(W){var Z,te,X,ne;W.dataset.label;const Y=W.dataset.data.reduce((se,ce)=>se+ce,0),U=W.parsed,z=Ks({number:Number(U),decimalPlaces:((Z=a==null?void 0:a.numberAxisFormat)==null?void 0:Z.decimalPlaces)||0,useSuffix:!!((te=a==null?void 0:a.numberAxisFormat)!=null&&te.suffix),customSuffix:"",locale:((X=a==null?void 0:a.numberAxisFormat)==null?void 0:X.locale)||"",currency:((ne=a==null?void 0:a.numberAxisFormat)==null?void 0:ne.currency)||""}),G=(U/Y*100).toFixed(2);return z+` (${G}%)`},footer:function(W){var Y,U,z,G;return(((U=(Y=e==null?void 0:e.interactionConfig)==null?void 0:Y.drillHierarchies)==null?void 0:U.length)??0)>0||(((G=(z=e==null?void 0:e.interactionConfig)==null?void 0:z.interactions)==null?void 0:G.some(Z=>Z.mode==="drillDown"||Z.mode==="drillToDetail"||Z.mode==="drillThrough"||Z.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},$=Nr(B,V),{options:P}=Um({cfg:{options:$},preferences:a,customCfg:s,cardType:n,card:e}),H=Nr(P,O);return{type:n,data:{labels:I,datasets:T},options:H,plugins:[n==="doughnut"?{id:"doughnutLabel",beforeDatasetsDraw:function(W,q,Y){var ce,ae,he,ye;const{ctx:U,data:z}=W;U.save();const G=W.getDatasetMeta(0).data[0].x,Z=W.getDatasetMeta(0).data[0].y,te=Bo(fl()),X=window.getComputedStyle(U.canvas).fontFamily;U.font=`1em ${X}`,U.fontWeight="bolder",U.fillStyle=te,U.textAlign="center",U.textBaseline="middle";const ne=z.datasets[0].data.reduce((Te,_e)=>Te+_e,0),se=Ks({number:Number(ne),decimalPlaces:((ce=a==null?void 0:a.numberAxisFormat)==null?void 0:ce.decimalPlaces)||0,useSuffix:!!((ae=a==null?void 0:a.numberAxisFormat)!=null&&ae.suffix),customSuffix:"",locale:((he=a==null?void 0:a.numberAxisFormat)==null?void 0:he.locale)||"",currency:((ye=a==null?void 0:a.numberAxisFormat)==null?void 0:ye.currency)||""});U.fillText(se,G,Z)}}:"",...R]}}if(n==="radar"){const C=gwe(r);return af({card:e,data:f,cfg:C,customCfg:s,cardType:n,preferences:a})}if(n==="bubble"||n==="scatter"){const{metricKeys:C}=Gn(f),j=Uhe(f,n),_=Ku(j,s),k=bwe(r,n,C),{options:E}=Um({cardType:n,cfg:k,preferences:a,customCfg:s,card:e});return{type:n,data:{datasets:_},options:E}}return af({card:e,data:f,cfg:r,customCfg:s,cardType:n,preferences:a})}function y1e({chart:e,elementIndex:t,datasetIndex:n,cardType:r,cfg:s,apply:o}){const i=J.getState().theme;if(!s)return;const a=i==="dark"?"rgb(238,238,238,0.2)":"rgb(238,238,238,0.8)";["bar","line","horizontalBar","bubble","scatter"].includes(r)&&w1e(e,t,s,o,a),["pie","doughnut","polarArea","funnel"].includes(r)&&S1e(e,t,s,o,a),["stackedBar","pyramid"].includes(r)&&v1e({chart:e,elementIndex:t,datasetIndex:n,cfg:s,apply:o,blurColor:a})}function v1e(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 w1e(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 S1e(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 C1e({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}=Gn(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=x1({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}=Gn(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 N1e(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,epe("--semaphor-background")),u})}));return{...e,data:{...e.data,datasets:o}}}return e}function NH(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}=bn({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 zi(e){const{tokenProps:t}=Ge(),n=J(h=>h.authToken)||e,r=ke(h=>h.selectedConnectionId),s=ke(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}=bn({queryKey:["connections"],queryFn:()=>qn(`${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 j1e(e){const{connections:t}=zi(e),n=ke(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 k1e(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 Af(e){if(ij.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 hD(e){var b;const{tokenProps:t}=Ge(),n=J(x=>x.authToken)||e,{hasSchemaSupport:r}=j1e(e),s=ke(x=>{var y;return(y=x.card.dataSource)==null?void 0:y.connectionId}),o=ke(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=ke(x=>{var y,v;return(v=(y=x.card.dataSource)==null?void 0:y.selectedEntities)==null?void 0:v.filter(w=>ij.includes(w.type))})||[],a=ke(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:ij.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=j_({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:()=>qn(`${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=Af(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||y_(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=k1e(m);return{columnGroups:m,columns:g,isLoading:f,hasError:h,error:p,refetch:()=>{d.forEach(x=>x.refetch())}}}function E1e(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 pD(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&&E1e(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 jH(e,t,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:e===t||e===Af(n.baseEntity)||t===Af(n.baseEntity)?!0:n.joins.some(s=>{const o=Af(s.source),i=Af(s.target);return o===e&&i===t||o===t&&i===e})}function _1e(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 pD(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(!jH(i,e.qualifiedEntityName,r))return{isValid:!1,showError:!0}}return{isValid:!0}}function kH(){ze.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function EH(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 M1e(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 D1e(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 _H(e,t){return`${e}-${t.qualifiedEntityName}-${t.name}-${Date.now()}`}function MH(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 T1e(e,t,n){const r=Xs(e.dataType);return n==="kpi"?r==="date"?"groupBy":"metrics":t.length===0||r==="number"?"metrics":r==="date"||r==="string"||r==="boolean"?"groupBy":"metrics"}function DH(e,t,n=[]){const r=_H(t,e),s=Xs(e.dataType),o=s==="date",i={id:r,name:e.name,dataType:e.dataType,label:y_(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=MH(e.label,a),u=D1e({...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 R1e(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 I1e(e){var i,a;const[t]=N.useState({id:"",title:"",type:"bar"}),{getCard:n}=Gt(),r=n(e),s=qb(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 qb(e){var O;const{onChartElementClicked:t}=Ge(),[n,r]=N.useState(0),s=J(D=>D.themeStyle),o=J(D=>D.filteringCards),i=J(D=>D.selectedSheetId),a=J(D=>D.selectedLensId),l=J(D=>D.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}=Gt(),{data:g,isLoading:b,isFetching:x,isError:y,isPending:v,queryKey:w,isFilteringCard:S,isSingleCardFrame:C,pagination:j,comparisonMetadata:_}=wa(e),{data:k}=NH(e);let E;E=N.useMemo(()=>{if(!(!(g!=null&&g.records)||!(g!=null&&g.records.length)))return fD({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 T=N.useRef({filteringCards:o});N.useEffect(()=>{e.connectionId&&!S&&(u.current=l)},[l,a,e.connectionId,S]),N.useEffect(()=>{var I;S&&(T.current.filteringCards=[...o||[]]),!S&&((I=T.current.filteringCards)==null?void 0:I.find(F=>F.id===e.id))&&C&&r(F=>F+1)},[S,C,e.id,o]);function R(D,I,F,B){var P;if(R1e(e))return;let V=!1;if(!(g!=null&&g.records))return;const $=C1e({card:e,data:g==null?void 0:g.records,datasetIndex:I,clickIndex:F,value:B});if(console.log("fieldValues",$),t==null||t(e,$),!!(((P=e==null?void 0:e.preferences)==null?void 0:P.onClickFilter)??[]).length){if(S){const H=e.id;p(H),m(e)}else{if(V=!0,!$)return;const H=[];$.forEach((L,A)=>{const W=d==null?void 0:d.find(Y=>Y.columnIndex===A);if(!W)return;const q={filterId:e.id+"-"+L.columnName+"-"+i,connectionId:e==null?void 0:e.connectionId,tableName:e.lastSelectedTable,name:L.columnName,expression:W.expression,valueType:x_($[W.columnIndex].columnValue),operation:"=",values:[$[W.columnIndex].columnValue]};H.push(q)}),h(H),f(e)}y1e({chart:D,elementIndex:F,datasetIndex:I,cardType:e.type,cfg:E,apply:V})}}return{isPending:v,isError:y,isLoading:b,isFetching:x,data:g,visualKey:n,handleDatapointClick:R,cfg:E,queryKey:w,pagination:j,comparisonMetadata:_}}function TH(e){var x;const{tokenProps:t}=Ge(),n=J(y=>y.authToken)||e,r=ke(y=>y.selectedConnectionId),s=ke(y=>y.selectedDatabaseName),o=ke(y=>y.selectedDatamodelId),i=ke(y=>y.selectedSchemaName),a=ke(y=>y.selectedTableName),{selectedConnection:l}=zi(),u=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:p,refetch:m}=bn({queryKey:["columns",r,s,o,i,a],queryFn:()=>qn(`${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 tg(e,t){const[n,r]=N.useState(e);return N.useEffect(()=>{const s=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(s)}},[e,t]),n}var A1e=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 RH=zc(A1e);function E0(e,t=RH){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 P1e(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 RH(e,t)}const O5={searchQuery:"",debouncedSearchQuery:"",selectedUsers:[],usersToRemove:[],usersToUpdate:[],selectedGroups:[],groupsToRemove:[],groupsToUpdate:[],selectedTab:"org",currentContext:"org-tab",currentMode:null,orgWideRole:"VIEWER",allTenantsRole:"VIEWER",tenantWideRole:"VIEWER",groupWideRole:"VIEWER",selectedTenant:"",message:""},cs=Nl()(Nb(e=>({...O5,actions:{setSearchQuery:t=>{e(n=>{n.searchQuery=t})},setDebouncedSearchQuery:t=>{e(n=>{n.debouncedSearchQuery=t})},setSelectedUsers:t=>{e(n=>{n.selectedUsers=t})},addSelectedUser:t=>{e(n=>{n.selectedUsers.some(s=>s.id===t.id)||n.selectedUsers.push(t)})},removeSelectedUser:t=>{e(n=>{n.selectedUsers=n.selectedUsers.filter(r=>r.id!==t)})},updateSelectedUserRole:(t,n)=>{e(r=>{const s=r.selectedUsers.find(o=>o.id===t);s&&(s.role=n)})},setUsersToRemove:t=>{e(n=>{n.usersToRemove=t})},addUserToRemove:t=>{e(n=>{n.usersToRemove.includes(t)||n.usersToRemove.push(t)})},removeUserFromRemove:t=>{e(n=>{n.usersToRemove=n.usersToRemove.filter(r=>r!==t)})},setUsersToUpdate:t=>{e(n=>{n.usersToUpdate=t})},addUserToUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t.id),n.usersToUpdate.push(t)})},removeUserFromUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t)})},setSelectedTenant:t=>{e(n=>{n.selectedTenant=t})},setSelectedTab:t=>{e(n=>{n.selectedTab=t})},setCurrentContext:t=>{e(n=>{n.currentContext=t})},setCurrentMode:t=>{e(n=>{n.currentMode=t})},setOrgWideRole:t=>{e(n=>{n.orgWideRole=t})},setAllTenantsRole:t=>{e(n=>{n.allTenantsRole=t})},setTenantWideRole:t=>{e(n=>{n.tenantWideRole=t})},setGroupWideRole:t=>{e(n=>{n.groupWideRole=t})},setSelectedGroups:t=>{e(n=>{n.selectedGroups=t})},addSelectedGroup:t=>{e(n=>{n.selectedGroups.some(s=>s.id===t.id)||n.selectedGroups.push(t)})},removeSelectedGroup:t=>{e(n=>{n.selectedGroups=n.selectedGroups.filter(r=>r.id!==t)})},updateSelectedGroupRole:(t,n)=>{e(r=>{const s=r.selectedGroups.find(o=>o.id===t);s&&(s.role=n)})},setGroupsToRemove:t=>{e(n=>{n.groupsToRemove=t})},addGroupToRemove:t=>{e(n=>{n.groupsToRemove.includes(t)||n.groupsToRemove.push(t)})},removeGroupFromRemove:t=>{e(n=>{n.groupsToRemove=n.groupsToRemove.filter(r=>r!==t)})},setGroupsToUpdate:t=>{e(n=>{n.groupsToUpdate=t})},addGroupToUpdate:t=>{e(n=>{const r=n.groupsToUpdate.findIndex(s=>s.id===t.id);r!==-1?n.groupsToUpdate[r]=t:n.groupsToUpdate.push(t)})},removeGroupFromUpdate:t=>{e(n=>{n.groupsToUpdate=n.groupsToUpdate.filter(r=>r.id!==t)})},setMessage:t=>{e(n=>{n.message=t})},validateShareData:t=>cB(t),resetShareState:()=>{e(t=>{Object.assign(t,O5)})},resetUserSelections:()=>{e(t=>{t.selectedUsers=[],t.usersToRemove=[],t.usersToUpdate=[]})},resetGroupSelections:()=>{e(t=>{t.selectedGroups=[],t.groupsToRemove=[],t.groupsToUpdate=[]})}}}))),IH=()=>cs(e=>e.searchQuery),vp=()=>cs(e=>e.selectedUsers),Yd=()=>cs(e=>e.usersToRemove),wp=()=>cs(e=>e.usersToUpdate),Yb=()=>cs(e=>e.selectedTenant),mD=()=>cs(e=>e.selectedTab),AH=()=>cs(e=>e.currentContext),qc=()=>cs(e=>e.currentMode),gD=()=>cs(e=>e.orgWideRole),bD=()=>cs(e=>e.allTenantsRole),T1=()=>cs(e=>e.tenantWideRole),PH=()=>cs(e=>e.groupWideRole),Sp=()=>cs(e=>e.selectedGroups),Cp=()=>cs(e=>e.groupsToRemove),Np=()=>cs(e=>e.groupsToUpdate),Yc=()=>cs(e=>e.actions),xD=()=>{const e=IH(),t=tg(e,300),n=Yc();return N.useEffect(()=>{n.setDebouncedSearchQuery(t)},[t,n]),{searchQuery:e,debouncedSearchQuery:t,setSearchQuery:n.setSearchQuery}};function qi(e,t){var n;return((n=t.find(r=>r.value===e))==null?void 0:n.label)||e}function O1e(e){return["POWER_USER","ADMIN","EDITOR"].includes(e)}function OH(e){return"tenantId"in e&&e.tenantId?"tenant":"organization"}function F1e(e,t,n){const r=OH(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 $1e({user:e}){return OH(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 L1e({user:e,userShare:t,usersToUpdate:n,currentUser:r,getRoleOptions:s,handleUpdateAccess:o}){if(!(t!=null&&t.role))return null;const i=O1e((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(vd,{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:qi(u,d)})}):c.jsx(Fe,{variant:"outline",className:"text-xs",children:"Unknown"})}function z1e({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(vc,{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(Zu,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function B1e({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 V1e({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=qi(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=qi(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=qi(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=qi(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=qi(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=qi(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=qi(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=qi(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=qi(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 H1e({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 U1e({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:K("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(un,{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($1e,{user:e})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?c.jsx(vd,{currentRole:t==null?void 0:t.role,onRoleChange:m=>h(e.id,t.role,m),roleOptions:a,disabled:!1,allowDropdown:!0}):c.jsx(L1e,{user:e,userShare:t,usersToUpdate:u,currentUser:l,getRoleOptions:()=>a,handleUpdateAccess:h}),o&&!s&&c.jsx("div",{onClick:m=>m.stopPropagation(),children:c.jsx(vd,{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(z1e,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:s}),c.jsx(B1e,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function FH({existingShares:e,isInitialLoading:t,isSearching:n,getRoleOptions:r,allUsers:s=[],currentUser:o,handleUserToggle:i,handleUserRoleChange:a,handleRemoveAccess:l,handleUpdateAccess:u}){const d=vp(),f=Yd(),h=wp(),p=IH(),m=Yc(),g=i||(S=>{const C=d.some(_=>_.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(le,{className:"text-sm font-medium",children:["All Users (",(v??[]).length,")"]}),c.jsx(er,{children:c.jsxs(wn,{children:[c.jsx(Sn,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:c.jsx(gr,{className:"h-4 w-4"})})}),c.jsx(En,{className:"w-48 max-w-sm",children:c.jsx(V1e,{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(H1e,{isInitialLoading:t,isSearching:n,searchQuery:p,availableUsers:v||[]}),!t&&!n&&(v==null?void 0:v.length)>0&&v.map(S=>{const C=e?F1e(S,e,o):void 0,j=w.includes(S.id),_=!!C,k=_&&!j,E=d.some(O=>O.id===S.id),T=d.find(O=>O.id===S.id),R=r(S.type);return c.jsx(U1e,{user:S,userShare:C,isUserRemoving:j,hasAccess:k,hasAccessFromAPI:_,isSelected:E,selectedUser:T,roleOptions:R,currentUser:o,usersToUpdate:h,handleUserToggle:g,handleRemoveAccess:x,handleUpdateAccess:y,handleUserRoleChange:b},S.id)})]})]})}var yD="Radio",[W1e,$H]=Er(yD),[q1e,Y1e]=W1e(yD),LH=M.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]=M.useState(null),p=ft(t,b=>h(b)),m=M.useRef(!1),g=f?u||!!f.closest("form"):!0;return c.jsxs(q1e,{scope:n,checked:s,disabled:i,children:[c.jsx(Be.button,{type:"button",role:"radio","aria-checked":s,"data-state":VH(s),"data-disabled":i?"":void 0,disabled:i,value:a,...d,ref:p,onClick:je(e.onClick,b=>{s||l==null||l(),g&&(m.current=b.isPropagationStopped(),m.current||b.stopPropagation())})}),g&&c.jsx(G1e,{control:f,bubbles:!m.current,name:r,value:a,checked:s,required:o,disabled:i,form:u,style:{transform:"translateX(-100%)"}})]})});LH.displayName=yD;var zH="RadioIndicator",BH=M.forwardRef((e,t)=>{const{__scopeRadio:n,forceMount:r,...s}=e,o=Y1e(zH,n);return c.jsx(sr,{present:r||o.checked,children:c.jsx(Be.span,{"data-state":VH(o.checked),"data-disabled":o.disabled?"":void 0,...s,ref:t})})});BH.displayName=zH;var G1e=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=M.useRef(null),i=f1(n),a=i1(t);return M.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 VH(e){return e?"checked":"unchecked"}var Z1e=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],vD="RadioGroup",[K1e]=Er(vD,[np,$H]),HH=np(),UH=$H(),[X1e,Q1e]=K1e(vD),WH=M.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=HH(n),m=$d(u),[g,b]=Fr({prop:o,defaultProp:s,onChange:f});return c.jsx(X1e,{scope:n,name:r,required:i,disabled:a,value:g,onValueChange:b,children:c.jsx(tM,{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})})})});WH.displayName=vD;var qH="RadioGroupItem",YH=M.forwardRef((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...s}=e,o=Q1e(qH,n),i=o.disabled||r,a=HH(n),l=UH(n),u=M.useRef(null),d=ft(t,u),f=o.value===s.value,h=M.useRef(!1);return M.useEffect(()=>{const p=g=>{Z1e.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(nM,{asChild:!0,...a,focusable:!i,active:f,children:c.jsx(LH,{disabled:i,required:o.required,checked:f,...l,...s,name:o.name,ref:d,onCheck:()=>o.onValueChange(s.value),onKeyDown:je(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:je(s.onFocus,()=>{var p;h.current&&((p=u.current)==null||p.click())})})})});YH.displayName=qH;var J1e="RadioGroupIndicator",GH=M.forwardRef((e,t)=>{const{__scopeRadioGroup:n,...r}=e,s=UH(n);return c.jsx(BH,{...s,...r,ref:t})});GH.displayName=J1e;var ZH=WH,KH=YH,eSe=GH;const Na=M.forwardRef(({className:e,...t},n)=>c.jsx(ZH,{className:K("grid gap-2",e),...t,ref:n}));Na.displayName=ZH.displayName;const Cr=M.forwardRef(({className:e,...t},n)=>c.jsx(KH,{ref:n,className:K("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(eSe,{className:"flex items-center justify-center",children:c.jsx(q6,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Cr.displayName=KH.displayName;function wD({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(Na,{value:e,onValueChange:t,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>c.jsxs("div",{children:[c.jsx(Cr,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),c.jsxs(le,{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(wc,{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, and super admins can share with all users."})]})}var pN,SD="HoverCard",[XH]=Er(SD,[Ma]),R1=Ma(),[tSe,I1]=XH(SD),QH=e=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:s,onOpenChange:o,openDelay:i=700,closeDelay:a=300}=e,l=R1(t),u=M.useRef(0),d=M.useRef(0),f=M.useRef(!1),h=M.useRef(!1),[p=!1,m]=Fr({prop:r,defaultProp:s,onChange:o}),g=M.useCallback(()=>{clearTimeout(d.current),u.current=window.setTimeout(()=>m(!0),i)},[i,m]),b=M.useCallback(()=>{clearTimeout(u.current),!f.current&&!h.current&&(d.current=window.setTimeout(()=>m(!1),a))},[a,m]),x=M.useCallback(()=>m(!1),[m]);return M.useEffect(()=>()=>{clearTimeout(u.current),clearTimeout(d.current)},[]),c.jsx(tSe,{scope:t,open:p,onOpenChange:m,onOpen:g,onClose:b,onDismiss:x,hasSelectionRef:f,isPointerDownOnContentRef:h,children:c.jsx(ep,{...l,children:n})})};QH.displayName=SD;var JH="HoverCardTrigger",eU=M.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=I1(JH,n),o=R1(n);return c.jsx(tp,{asChild:!0,...o,children:c.jsx(Be.a,{"data-state":s.open?"open":"closed",...r,ref:t,onPointerEnter:je(e.onPointerEnter,Lv(s.onOpen)),onPointerLeave:je(e.onPointerLeave,Lv(s.onClose)),onFocus:je(e.onFocus,s.onOpen),onBlur:je(e.onBlur,s.onClose),onTouchStart:je(e.onTouchStart,i=>i.preventDefault())})})});eU.displayName=JH;var CD="HoverCardPortal",[nSe,rSe]=XH(CD,{forceMount:void 0}),tU=e=>{const{__scopeHoverCard:t,forceMount:n,children:r,container:s}=e,o=I1(CD,t);return c.jsx(nSe,{scope:t,forceMount:n,children:c.jsx(sr,{present:n||o.open,children:c.jsx(zd,{asChild:!0,container:s,children:r})})})};tU.displayName=CD;var $v="HoverCardContent",nU=M.forwardRef((e,t)=>{const n=rSe($v,e.__scopeHoverCard),{forceMount:r=n.forceMount,...s}=e,o=I1($v,e.__scopeHoverCard);return c.jsx(sr,{present:r||o.open,children:c.jsx(sSe,{"data-state":o.open?"open":"closed",...s,onPointerEnter:je(e.onPointerEnter,Lv(o.onOpen)),onPointerLeave:je(e.onPointerLeave,Lv(o.onClose)),ref:t})})});nU.displayName=$v;var sSe=M.forwardRef((e,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:i,...a}=e,l=I1($v,n),u=R1(n),d=M.useRef(null),f=ft(t,d),[h,p]=M.useState(!1);return M.useEffect(()=>{if(h){const m=document.body;return pN=m.style.userSelect||m.style.webkitUserSelect,m.style.userSelect="none",m.style.webkitUserSelect="none",()=>{m.style.userSelect=pN,m.style.webkitUserSelect=pN}}},[h]),M.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]),M.useEffect(()=>{d.current&&aSe(d.current).forEach(g=>g.setAttribute("tabindex","-1"))}),c.jsx(Ld,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:i,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:je(o,m=>{m.preventDefault()}),onDismiss:l.onDismiss,children:c.jsx(Rb,{...u,...a,onPointerDown:je(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)"}})})}),oSe="HoverCardArrow",iSe=M.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=R1(n);return c.jsx(Ib,{...s,...r,ref:t})});iSe.displayName=oSe;function Lv(e){return t=>t.pointerType==="touch"?void 0:e()}function aSe(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 lSe=QH,cSe=eU,rU=nU;const jp=lSe,kp=cSe,Gd=M.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>c.jsx(rU,{ref:s,align:t,sideOffset:n,className:K("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}));Gd.displayName=rU.displayName;const mi=()=>[{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 uSe({currentUser:e,currentShare:t,isSharing:n,onUpdateAccess:r,allUsersToUpdate:s=null,allUsersToRemove:o=!1,isUpdating:i=!1,isRemoving:a=!1}){const l=qc(),u=mi().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(vc,{className:"h-4 w-4"});case"EDITOR":return c.jsx(Jw,{className:"h-4 w-4"});case"CONTRIBUTOR":return c.jsx(gie,{className:"h-4 w-4"});default:return c.jsx(vc,{className:"h-4 w-4"})}},x=y=>{r(d,y)};return c.jsx("div",{className:"space-y-4",children:c.jsxs(xo,{className:K("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(Ei,{children:[c.jsxs(_i,{className:"flex items-center gap-2 text-base",children:[c.jsx(os,{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(D6,{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(Mi,{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(jp,{children:[c.jsx(kp,{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(gr,{className:"h-3 w-3"})})}),c.jsx(Gd,{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 sU({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(uSe,{currentUser:e,currentShare:f,isSharing:n,isUpdating:r,isRemoving:s,onUpdateAccess:p,onRemoveAccess:m,allUsersToUpdate:h,allUsersToRemove:l})}const dSe=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 qn(s,t,r)};function ND(e={}){var o,i,a;const{authToken:t,tokenProps:n}=Ge(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=bn({queryKey:["unified-users",e],queryFn:()=>dSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(l,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:l<2,retryDelay:l=>Math.min(1e3*2**l,3e4)});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 Oh(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=$t.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}=ND(i),d=dde(r,n);return{allUsers:a,isLoadingUsers:l,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function fSe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var L,A;const a=mD(),l=Yb(),{searchQuery:u,setSearchQuery:d,debouncedSearchQuery:f}=xD(),h=vp(),p=Yd(),m=wp(),g=qc(),b=gD(),x=Yc(),[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:_}=Oh({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,U;const q=W;if(v(q),r==null||r(q),x.setCurrentContext("org-tab"),q==="specific_users")x.setCurrentMode("specificOrgUsers");else if(q==="all_users"){x.setCurrentMode("allOrgUsers");const z=(U=(Y=j==null?void 0:j.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:U[0];z&&z.role!==void 0&&x.setOrgWideRole(z.role)}},E=C.filter(W=>W.name.toLowerCase().includes(u.toLowerCase())||W.email.toLowerCase().includes(u.toLowerCase())),T=C.filter(W=>h.some(q=>q.id===W.id)),R=W=>{var z,G;const q=h.some(Z=>Z.id===W),Y=p.includes(W),U=(G=(z=j==null?void 0:j.shares)==null?void 0:z.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===W);q?x.removeSelectedUser(W):Y?x.removeUserFromRemove(W):U||x.addSelectedUser({id:W,role:"VIEWER"})},O=(W,q)=>{x.updateSelectedUserRole(W,q)},D=W=>{x.addUserToRemove(W),x.removeSelectedUser(W)},I=W=>{x.removeUserFromRemove(W)},F=W=>{x.removeUserFromUpdate(W)},B=(W,q)=>{x.setOrgWideRole(q)},V=()=>{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=_,H=!1;return n?c.jsxs(c.Fragment,{children:[c.jsx(wD,{shareType:y,onShareTypeChange:k,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:c.jsx(wc,{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(os,{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(fv,{value:u,onChange:d}),c.jsx(B7,{selectedUsers:h,selectedUserObjects:T,onRemove:R,onRoleChange:O,getRoleOptions:mi}),c.jsx(V7,{usersToRemove:p,allUsers:E,onRemove:I}),c.jsx(H7,{usersToUpdate:m,allUsers:E,onRemove:F,getRoleOptions:mi}),c.jsx(FH,{existingShares:j,isInitialLoading:P,isSearching:H,resource:e,onShare:()=>{},getRoleOptions:mi,allUsers:E,currentUser:n,handleUserToggle:R,handleUserRoleChange:O,handleRemoveAccess:D,handleUpdateAccess:(W,q,Y)=>{x.addUserToUpdate({id:W,currentRole:q,newRole:Y})}})]}):c.jsx("div",{className:"mt-3",children:c.jsx(sU,{currentUser:n,currentShare:$,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:B,onRemoveAccess:V,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 hSe(e){switch(e){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function pSe(e){switch(e){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function oU({groups:e,existingGroupShares:t,isLoading:n,resource:r,getRoleOptions:s,currentUser:o,handleGroupToggle:i,handleGroupRoleChange:a,handleRemoveAccess:l,handleUpdateAccess:u}){const d=Sp(),f=Cp(),h=Np(),p=Yc(),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(le,{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(_=>_.id===g.id);C=(j==null?void 0:j.role)||"VIEWER"}else v&&(C=v.newRole);return c.jsxs("div",{className:K("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(un,{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(pd,{className:"h-3 w-3 text-blue-600"}):c.jsx(os,{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:K("text-xs",pSe(g.type)),children:hSe(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(vd,{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(vd,{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 iU({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(pd,{className:"h-4 w-4 text-blue-600"}):c.jsx(os,{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(vd,{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 mSe=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 qn(s,t,r)},gSe=async(e,t,n)=>{const r=`${e}/management/v1/groups/${n}/members`;return await qn(r,t)};function jD(e={}){var o,i,a;const{authToken:t,tokenProps:n}=Ge(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=bn({queryKey:["groups",e],queryFn:()=>mSe(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 bSe(e){const{authToken:t,tokenProps:n}=Ge(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId);return bn({queryKey:["group-members",e],queryFn:()=>gSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r&&!!e,retry:1,staleTime:6e4})}function aU(e,t){const{tokenProps:n}=Ge(),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)),jD(r)}function Pk(e,[t,n]){return Math.min(n,Math.max(t,e))}var lU=M.forwardRef((e,t)=>{const{children:n,...r}=e,s=M.Children.toArray(n),o=s.find(ySe);if(o){const i=o.props.children,a=s.map(l=>l===o?M.Children.count(i)>1?M.Children.only(null):M.isValidElement(i)?i.props.children:null:l);return c.jsx(Ok,{...r,ref:t,children:M.isValidElement(i)?M.cloneElement(i,void 0,a):null})}return c.jsx(Ok,{...r,ref:t,children:n})});lU.displayName="Slot";var Ok=M.forwardRef((e,t)=>{const{children:n,...r}=e;if(M.isValidElement(n)){const s=wSe(n),o=vSe(r,n.props);return n.type!==M.Fragment&&(o.ref=t?js(t,s):s),M.cloneElement(n,o)}return M.Children.count(n)>1?M.Children.only(null):null});Ok.displayName="SlotClone";var xSe=({children:e})=>c.jsx(c.Fragment,{children:e});function ySe(e){return M.isValidElement(e)&&e.type===xSe}function vSe(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 wSe(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 SSe=[" ","Enter","ArrowUp","ArrowDown"],CSe=[" ","Enter"],Gb="Select",[A1,P1,NSe]=t1(Gb),[Ep]=Er(Gb,[NSe,Ma]),O1=Ma(),[jSe,Gc]=Ep(Gb),[kSe,ESe]=Ep(Gb),cU=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=O1(t),[b,x]=M.useState(null),[y,v]=M.useState(null),[w,S]=M.useState(!1),C=$d(u),[j=!1,_]=Fr({prop:r,defaultProp:s,onChange:o}),[k,E]=Fr({prop:i,defaultProp:a,onChange:l}),T=M.useRef(null),R=b?m||!!b.closest("form"):!0,[O,D]=M.useState(new Set),I=Array.from(O).map(F=>F.props.value).join(";");return c.jsx(ep,{...g,children:c.jsxs(jSe,{required:p,scope:t,trigger:b,onTriggerChange:x,valueNode:y,onValueNodeChange:v,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:rr(),value:k,onValueChange:E,open:j,onOpenChange:_,dir:C,triggerPointerDownPosRef:T,disabled:h,children:[c.jsx(A1.Provider,{scope:t,children:c.jsx(kSe,{scope:e.__scopeSelect,onNativeOptionAdd:M.useCallback(F=>{D(B=>new Set(B).add(F))},[]),onNativeOptionRemove:M.useCallback(F=>{D(B=>{const V=new Set(B);return V.delete(F),V})},[]),children:n})}),R?c.jsxs(PU,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:k,onChange:F=>E(F.target.value),disabled:h,form:m,children:[k===void 0?c.jsx("option",{value:""}):null,Array.from(O)]},I):null]})})};cU.displayName=Gb;var uU="SelectTrigger",dU=M.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=O1(n),i=Gc(uU,n),a=i.disabled||r,l=ft(t,i.onTriggerChange),u=P1(n),d=M.useRef("touch"),[f,h,p]=OU(g=>{const b=u().filter(v=>!v.disabled),x=b.find(v=>v.value===i.value),y=FU(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(tp,{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":AU(i.value)?"":void 0,...s,ref:l,onClick:je(s.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&m(g)}),onPointerDown:je(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:je(s.onKeyDown,g=>{const b=f.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(b&&g.key===" ")&&SSe.includes(g.key)&&(m(),g.preventDefault())})})})});dU.displayName=uU;var fU="SelectValue",hU=M.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:i="",...a}=e,l=Gc(fU,n),{onValueNodeHasChildrenChange:u}=l,d=o!==void 0,f=ft(t,l.onValueNodeChange);return $r(()=>{u(d)},[u,d]),c.jsx(Be.span,{...a,ref:f,style:{pointerEvents:"none"},children:AU(l.value)?c.jsx(c.Fragment,{children:i}):o})});hU.displayName=fU;var _Se="SelectIcon",pU=M.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return c.jsx(Be.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});pU.displayName=_Se;var MSe="SelectPortal",mU=e=>c.jsx(zd,{asChild:!0,...e});mU.displayName=MSe;var _d="SelectContent",gU=M.forwardRef((e,t)=>{const n=Gc(_d,e.__scopeSelect),[r,s]=M.useState();if($r(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?yc.createPortal(c.jsx(bU,{scope:e.__scopeSelect,children:c.jsx(A1.Slot,{scope:e.__scopeSelect,children:c.jsx("div",{children:e.children})})}),o):null}return c.jsx(xU,{...e,ref:t})});gU.displayName=_d;var oi=10,[bU,Zc]=Ep(_d),DSe="SelectContentImpl",xU=M.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=Gc(_d,n),[v,w]=M.useState(null),[S,C]=M.useState(null),j=ft(t,U=>w(U)),[_,k]=M.useState(null),[E,T]=M.useState(null),R=P1(n),[O,D]=M.useState(!1),I=M.useRef(!1);M.useEffect(()=>{if(v)return Ab(v)},[v]),n1();const F=M.useCallback(U=>{const[z,...G]=R().map(X=>X.ref.current),[Z]=G.slice(-1),te=document.activeElement;for(const X of U)if(X===te||(X==null||X.scrollIntoView({block:"nearest"}),X===z&&S&&(S.scrollTop=0),X===Z&&S&&(S.scrollTop=S.scrollHeight),X==null||X.focus(),document.activeElement!==te))return},[R,S]),B=M.useCallback(()=>F([_,v]),[F,_,v]);M.useEffect(()=>{O&&B()},[O,B]);const{onOpenChange:V,triggerPointerDownPosRef:$}=y;M.useEffect(()=>{if(v){let U={x:0,y:0};const z=Z=>{var te,X;U={x:Math.abs(Math.round(Z.pageX)-(((te=$.current)==null?void 0:te.x)??0)),y:Math.abs(Math.round(Z.pageY)-(((X=$.current)==null?void 0:X.y)??0))}},G=Z=>{U.x<=10&&U.y<=10?Z.preventDefault():v.contains(Z.target)||V(!1),document.removeEventListener("pointermove",z),$.current=null};return $.current!==null&&(document.addEventListener("pointermove",z),document.addEventListener("pointerup",G,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",z),document.removeEventListener("pointerup",G,{capture:!0})}}},[v,V,$]),M.useEffect(()=>{const U=()=>V(!1);return window.addEventListener("blur",U),window.addEventListener("resize",U),()=>{window.removeEventListener("blur",U),window.removeEventListener("resize",U)}},[V]);const[P,H]=OU(U=>{const z=R().filter(te=>!te.disabled),G=z.find(te=>te.ref.current===document.activeElement),Z=FU(z,U,G);Z&&setTimeout(()=>Z.ref.current.focus())}),L=M.useCallback((U,z,G)=>{const Z=!I.current&&!G;(y.value!==void 0&&y.value===z||Z)&&(k(U),Z&&(I.current=!0))},[y.value]),A=M.useCallback(()=>v==null?void 0:v.focus(),[v]),W=M.useCallback((U,z,G)=>{const Z=!I.current&&!G;(y.value!==void 0&&y.value===z||Z)&&T(U)},[y.value]),q=r==="popper"?Fk:yU,Y=q===Fk?{side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:b}:{};return c.jsx(bU,{scope:n,content:v,viewport:S,onViewportChange:C,itemRefCallback:L,selectedItem:_,onItemLeave:A,itemTextRefCallback:W,focusSelectedItem:B,selectedItemText:E,position:r,isPositioned:O,searchRef:P,children:c.jsx(rp,{as:lU,allowPinchZoom:!0,children:c.jsx(Xh,{asChild:!0,trapped:y.open,onMountAutoFocus:U=>{U.preventDefault()},onUnmountAutoFocus:je(s,U=>{var z;(z=y.trigger)==null||z.focus({preventScroll:!0}),U.preventDefault()}),children:c.jsx(Ld,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:U=>U.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:c.jsx(q,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:U=>U.preventDefault(),...x,...Y,onPlaced:()=>D(!0),ref:j,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:je(x.onKeyDown,U=>{const z=U.ctrlKey||U.altKey||U.metaKey;if(U.key==="Tab"&&U.preventDefault(),!z&&U.key.length===1&&H(U.key),["ArrowUp","ArrowDown","Home","End"].includes(U.key)){let Z=R().filter(te=>!te.disabled).map(te=>te.ref.current);if(["ArrowUp","End"].includes(U.key)&&(Z=Z.slice().reverse()),["ArrowUp","ArrowDown"].includes(U.key)){const te=U.target,X=Z.indexOf(te);Z=Z.slice(X+1)}setTimeout(()=>F(Z)),U.preventDefault()}})})})})})})});xU.displayName=DSe;var TSe="SelectItemAlignedPosition",yU=M.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=Gc(_d,n),i=Zc(_d,n),[a,l]=M.useState(null),[u,d]=M.useState(null),f=ft(t,j=>d(j)),h=P1(n),p=M.useRef(!1),m=M.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:x,focusSelectedItem:y}=i,v=M.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&u&&g&&b&&x){const j=o.trigger.getBoundingClientRect(),_=u.getBoundingClientRect(),k=o.valueNode.getBoundingClientRect(),E=x.getBoundingClientRect();if(o.dir!=="rtl"){const te=E.left-_.left,X=k.left-te,ne=j.left-X,se=j.width+ne,ce=Math.max(se,_.width),ae=window.innerWidth-oi,he=Pk(X,[oi,Math.max(oi,ae-ce)]);a.style.minWidth=se+"px",a.style.left=he+"px"}else{const te=_.right-E.right,X=window.innerWidth-k.right-te,ne=window.innerWidth-j.right-X,se=j.width+ne,ce=Math.max(se,_.width),ae=window.innerWidth-oi,he=Pk(X,[oi,Math.max(oi,ae-ce)]);a.style.minWidth=se+"px",a.style.right=he+"px"}const T=h(),R=window.innerHeight-oi*2,O=g.scrollHeight,D=window.getComputedStyle(u),I=parseInt(D.borderTopWidth,10),F=parseInt(D.paddingTop,10),B=parseInt(D.borderBottomWidth,10),V=parseInt(D.paddingBottom,10),$=I+F+O+V+B,P=Math.min(b.offsetHeight*5,$),H=window.getComputedStyle(g),L=parseInt(H.paddingTop,10),A=parseInt(H.paddingBottom,10),W=j.top+j.height/2-oi,q=R-W,Y=b.offsetHeight/2,U=b.offsetTop+Y,z=I+F+U,G=$-z;if(z<=W){const te=T.length>0&&b===T[T.length-1].ref.current;a.style.bottom="0px";const X=u.clientHeight-g.offsetTop-g.offsetHeight,ne=Math.max(q,Y+(te?A:0)+X+B),se=z+ne;a.style.height=se+"px"}else{const te=T.length>0&&b===T[0].ref.current;a.style.top="0px";const ne=Math.max(W,I+g.offsetTop+(te?L:0)+Y)+G;a.style.height=ne+"px",g.scrollTop=z-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]);$r(()=>v(),[v]);const[w,S]=M.useState();$r(()=>{u&&S(window.getComputedStyle(u).zIndex)},[u]);const C=M.useCallback(j=>{j&&m.current===!0&&(v(),y==null||y(),m.current=!1)},[v,y]);return c.jsx(ISe,{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}})})})});yU.displayName=TSe;var RSe="SelectPopperPosition",Fk=M.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=oi,...o}=e,i=O1(n);return c.jsx(Rb,{...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)"}})});Fk.displayName=RSe;var[ISe,kD]=Ep(_d,{}),$k="SelectViewport",vU=M.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Zc($k,n),i=kD($k,n),a=ft(t,o.onViewportChange),l=M.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(A1.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:je(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})})})]})});vU.displayName=$k;var wU="SelectGroup",[ASe,PSe]=Ep(wU),SU=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=rr();return c.jsx(ASe,{scope:n,id:s,children:c.jsx(Be.div,{role:"group","aria-labelledby":s,...r,ref:t})})});SU.displayName=wU;var CU="SelectLabel",NU=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=PSe(CU,n);return c.jsx(Be.div,{id:s.id,...r,ref:t})});NU.displayName=CU;var zv="SelectItem",[OSe,jU]=Ep(zv),kU=M.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...i}=e,a=Gc(zv,n),l=Zc(zv,n),u=a.value===r,[d,f]=M.useState(o??""),[h,p]=M.useState(!1),m=ft(t,y=>{var v;return(v=l.itemRefCallback)==null?void 0:v.call(l,y,r,s)}),g=rr(),b=M.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(OSe,{scope:n,value:r,disabled:s,textId:g,isSelected:u,onItemTextChange:M.useCallback(y=>{f(v=>v||((y==null?void 0:y.textContent)??"").trim())},[]),children:c.jsx(A1.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:je(i.onFocus,()=>p(!0)),onBlur:je(i.onBlur,()=>p(!1)),onClick:je(i.onClick,()=>{b.current!=="mouse"&&x()}),onPointerUp:je(i.onPointerUp,()=>{b.current==="mouse"&&x()}),onPointerDown:je(i.onPointerDown,y=>{b.current=y.pointerType}),onPointerMove:je(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:je(i.onPointerLeave,y=>{var v;y.currentTarget===document.activeElement&&((v=l.onItemLeave)==null||v.call(l))}),onKeyDown:je(i.onKeyDown,y=>{var w;((w=l.searchRef)==null?void 0:w.current)!==""&&y.key===" "||(CSe.includes(y.key)&&x(),y.key===" "&&y.preventDefault())})})})})});kU.displayName=zv;var Mm="SelectItemText",EU=M.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,i=Gc(Mm,n),a=Zc(Mm,n),l=jU(Mm,n),u=ESe(Mm,n),[d,f]=M.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=M.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 $r(()=>(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?yc.createPortal(o.children,i.valueNode):null]})});EU.displayName=Mm;var _U="SelectItemIndicator",MU=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return jU(_U,n).isSelected?c.jsx(Be.span,{"aria-hidden":!0,...r,ref:t}):null});MU.displayName=_U;var Lk="SelectScrollUpButton",DU=M.forwardRef((e,t)=>{const n=Zc(Lk,e.__scopeSelect),r=kD(Lk,e.__scopeSelect),[s,o]=M.useState(!1),i=ft(t,r.onScrollButtonChange);return $r(()=>{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(RU,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});DU.displayName=Lk;var zk="SelectScrollDownButton",TU=M.forwardRef((e,t)=>{const n=Zc(zk,e.__scopeSelect),r=kD(zk,e.__scopeSelect),[s,o]=M.useState(!1),i=ft(t,r.onScrollButtonChange);return $r(()=>{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(RU,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});TU.displayName=zk;var RU=M.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Zc("SelectScrollButton",n),i=M.useRef(null),a=P1(n),l=M.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return M.useEffect(()=>()=>l(),[l]),$r(()=>{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:je(s.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:je(s.onPointerMove,()=>{var u;(u=o.onItemLeave)==null||u.call(o),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:je(s.onPointerLeave,()=>{l()})})}),FSe="SelectSeparator",IU=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c.jsx(Be.div,{"aria-hidden":!0,...r,ref:t})});IU.displayName=FSe;var Bk="SelectArrow",$Se=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=O1(n),o=Gc(Bk,n),i=Zc(Bk,n);return o.open&&i.position==="popper"?c.jsx(Ib,{...s,...r,ref:t}):null});$Se.displayName=Bk;function AU(e){return e===""||e===void 0}var PU=M.forwardRef((e,t)=>{const{value:n,...r}=e,s=M.useRef(null),o=ft(t,s),i=f1(n);return M.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(EM,{asChild:!0,children:c.jsx("select",{...r,ref:o,defaultValue:n})})});PU.displayName="BubbleSelect";function OU(e){const t=br(e),n=M.useRef(""),r=M.useRef(0),s=M.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=M.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return M.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function FU(e,t,n){const s=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let i=LSe(e,Math.max(o,0));s.length===1&&(i=i.filter(u=>u!==n));const l=i.find(u=>u.textValue.toLowerCase().startsWith(s.toLowerCase()));return l!==n?l:void 0}function LSe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var zSe=cU,$U=dU,BSe=hU,VSe=pU,HSe=mU,LU=gU,USe=vU,WSe=SU,zU=NU,BU=kU,qSe=EU,YSe=MU,VU=DU,HU=TU,UU=IU;const rt=zSe,WU=WSe,lt=BSe,Je=M.forwardRef(({className:e,children:t,...n},r)=>c.jsxs($U,{ref:r,className:K("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-0 focus:ring-ring focus:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,c.jsx(VSe,{asChild:!0,children:c.jsx(Gs,{className:"h-4 w-4 opacity-50"})})]}));Je.displayName=$U.displayName;const qU=M.forwardRef(({className:e,...t},n)=>c.jsx(VU,{ref:n,className:K("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Vm,{className:"h-4 w-4"})}));qU.displayName=VU.displayName;const YU=M.forwardRef(({className:e,...t},n)=>c.jsx(HU,{ref:n,className:K("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Gs,{className:"h-4 w-4"})}));YU.displayName=HU.displayName;const et=M.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>c.jsx(HSe,{children:c.jsx(Da,{children:c.jsxs(LU,{ref:s,className:K("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(qU,{}),c.jsx(USe,{className:K("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),c.jsx(YU,{})]})})}));et.displayName=LU.displayName;const ED=M.forwardRef(({className:e,...t},n)=>c.jsx(zU,{ref:n,className:K("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));ED.displayName=zU.displayName;const pe=M.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(BU,{ref:r,className:K("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx(YSe,{children:c.jsx(Rr,{className:"h-4 w-4"})})}),c.jsx(qSe,{children:t})]}));pe.displayName=BU.displayName;const GSe=M.forwardRef(({className:e,...t},n)=>c.jsx(UU,{ref:n,className:K("-mx-1 my-1 h-px bg-muted",e),...t}));GSe.displayName=UU.displayName;function F5({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var _e;const{searchQuery:a,debouncedSearchQuery:l,setSearchQuery:u}=xD(),d=vp(),f=Yd(),h=wp(),p=Sp(),m=Cp(),g=Np(),b=qc(),x=T1(),y=bD(),v=Yb(),w=Yc(),{data:S,isLoading:C}=r9({enabled:(n==null?void 0:n.type)==="organization"}),{groups:j,isLoading:_}=aU("tenant",(n==null?void 0:n.tenantId)||v),[k,E]=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 T=de=>{var Oe,mt,be,re;E(de);let Re;if(de==="specific_tenant_users"?Re="specific_users":de==="all_tenant_users"||de==="all_tenants"?Re="all_users":de==="groups"?Re="groups":Re="specific_users",r==null||r(Re),de==="groups"?(w.setCurrentContext("group-share"),w.setCurrentMode("specificGroups")):(n==null?void 0:n.type)==="tenant"?(w.setCurrentContext("tenant-dialog"),de==="specific_tenant_users"?w.setCurrentMode("specificTenantUsers"):de==="all_tenant_users"&&(w.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&w.setSelectedTenant(n.tenantId))):(w.setCurrentContext("tenant-tab"),de==="specific_tenant_users"?w.setCurrentMode("specificTenantUsers"):de==="all_tenant_users"?w.setCurrentMode("allTenantUsers"):de==="all_tenants"&&w.setCurrentMode("allTenants")),de==="all_tenant_users"){const ue=(mt=(Oe=D==null?void 0:D.shares)==null?void 0:Oe.tenantWide)==null?void 0:mt[0];ue&&ue.role!==void 0&&w.setTenantWideRole(ue.role)}else if(de==="all_tenants"){const ue=(re=(be=D==null?void 0:D.shares)==null?void 0:be.allTenantsOnly)==null?void 0:re[0];ue&&ue.role!==void 0&&w.setAllTenantsRole(ue.role)}},R=de=>{w.setSelectedTenant(de)},{allUsers:O,existingShares:D,isLoadingUsers:I,isErrorLoadingUsers:F,isLoadingShares:B,isErrorLoadingShares:V}=Oh({debouncedSearchQuery:l,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),$=de=>{var be,re;const Re=d.some(ue=>ue.id===de),Oe=f.includes(de),mt=(re=(be=D==null?void 0:D.shares)==null?void 0:be.specificTenantUsers)==null?void 0:re.some(ue=>ue.tenantUserId===de);Re?w.removeSelectedUser(de):Oe?w.removeUserFromRemove(de):mt||w.addSelectedUser({id:de,role:"VIEWER"})},P=(de,Re)=>{w.updateSelectedUserRole(de,Re)},H=de=>{w.addUserToRemove(de),w.removeSelectedUser(de)},L=de=>{w.removeUserFromRemove(de)},A=de=>{w.removeUserFromUpdate(de)},W=(de,Re,Oe)=>{w.addUserToUpdate({id:de,currentRole:Re,newRole:Oe})},q=(de,Re)=>{k==="all_tenant_users"?w.setTenantWideRole(Re):k==="all_tenants"&&w.setAllTenantsRole(Re)},Y=()=>{k==="all_tenant_users"?w.setTenantWideRole("VIEWER"):k==="all_tenants"&&w.setAllTenantsRole("VIEWER")},z=(()=>{var de,Re,Oe,mt;return b==="allTenants"?(Re=(de=D==null?void 0:D.shares)==null?void 0:de.allTenantsOnly)==null?void 0:Re[0]:b==="allTenantUsers"?(mt=(Oe=D==null?void 0:D.shares)==null?void 0:Oe.tenantWide)==null?void 0:mt[0]:null})();N.useEffect(()=>{var de,Re,Oe,mt;if(k==="all_tenant_users"){const be=(Re=(de=D==null?void 0:D.shares)==null?void 0:de.tenantWide)==null?void 0:Re[0];be&&be.role!==void 0&&w.setTenantWideRole(be.role)}else if(k==="all_tenants"){const be=(mt=(Oe=D==null?void 0:D.shares)==null?void 0:Oe.allTenantsOnly)==null?void 0:mt[0];be&&be.role!==void 0&&w.setAllTenantsRole(be.role)}},[k,D,w]);const G=O.filter(de=>d.some(Re=>Re.id===de.id)),Z=de=>{const Re=p.some(be=>be.id===de),Oe=m.includes(de),mt=ae==null?void 0:ae.some(be=>be.groupId===de);Re?w.removeSelectedGroup(de):Oe?w.removeGroupFromRemove(de):mt||w.addSelectedGroup({id:de,role:"VIEWER"})},te=(de,Re)=>{w.updateSelectedGroupRole(de,Re)},X=de=>{w.addGroupToRemove(de),w.removeSelectedGroup(de)},ne=(de,Re,Oe)=>{w.addGroupToUpdate({id:de,currentRole:Re,newRole:Oe})},se=j.filter(de=>p.some(Re=>Re.id===de.id)),ce=N.useMemo(()=>k!=="groups"?[]:j.filter(de=>de.type!=="TENANT_GROUP"?!1:de.name.toLowerCase().includes(a.toLowerCase())||de.description&&de.description.toLowerCase().includes(a.toLowerCase())),[j,k,a]),ae=N.useMemo(()=>{var Re,Oe;const de=((Re=D==null?void 0:D.shares)==null?void 0:Re.specificGroups)||((Oe=D==null?void 0:D.shares)==null?void 0:Oe.groups)||[];return!de||de.length===0?[]:de.filter(mt=>{const be=j.find(re=>re.id===mt.groupId);return(be==null?void 0:be.type)==="TENANT_GROUP"})},[D,j]),he=I||B||k==="groups"&&_,ye=F||V,Te=()=>(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:[ye&&c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsxs("div",{className:"text-center",children:[c.jsx(md,{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"})]})}),!ye&&n&&c.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[c.jsx(wD,{shareType:k,onShareTypeChange:T,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(os,{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(wc,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:c.jsx(os,{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(DA,{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(R_,{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(wc,{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(le,{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:(_e=S==null?void 0:S.tenants)==null?void 0:_e.map(de=>c.jsx(pe,{value:de.id,children:de.name},de.id))})]})]}),Te()?c.jsx(c.Fragment,{children:k==="specific_tenant_users"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(fv,{value:a,onChange:u}),c.jsx(B7,{selectedUsers:d,selectedUserObjects:G,onRemove:de=>$(de),onRoleChange:P,getRoleOptions:mi}),c.jsx(V7,{usersToRemove:f,allUsers:O,onRemove:L}),c.jsx(H7,{usersToUpdate:h,allUsers:O,onRemove:A,getRoleOptions:mi}),c.jsx(FH,{existingShares:D,isInitialLoading:!!he,isSearching:!1,resource:e,onShare:()=>{},getRoleOptions:mi,allUsers:O,currentUser:n,handleUserToggle:$,handleUserRoleChange:P,handleRemoveAccess:H,handleUpdateAccess:W})]}):k==="groups"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(fv,{value:a,onChange:u,placeholder:"Search groups..."}),c.jsx(iU,{selectedGroups:p,groupObjects:se,onRemove:Z,onRoleChange:te,getRoleOptions:mi}),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(oU,{groups:ce,existingGroupShares:ae,isLoading:_,resource:e,getRoleOptions:mi,currentUser:n,handleGroupToggle:Z,handleGroupRoleChange:te,handleRemoveAccess:X,handleUpdateAccess:ne})]}):k==="all_tenant_users"||k==="all_tenants"?c.jsx("div",{className:"mt-6",children:c.jsx(sU,{currentUser:n,currentShare:z,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:q,onRemoveAccess:Y,allUsersToUpdate:b==="allTenantUsers"&&((z==null?void 0:z.role)===void 0||x!==z.role)||b==="allTenants"&&((z==null?void 0:z.role)===void 0||y!==z.role)?{currentRole:(z==null?void 0:z.role)||"VIEWER",newRole:b==="allTenantUsers"?x:y}:null,allUsersToRemove:b==="allTenantUsers"&&(z==null?void 0:z.role)===void 0||b==="allTenants"&&(z==null?void 0:z.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(DA,{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 ZSe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var F,B;const{searchQuery:a,setSearchQuery:l}=xD(),u=Sp(),d=Cp(),f=Np(),h=Yc(),[p,m]=N.useState("org_groups"),[g,b]=N.useState(""),{data:x,isLoading:y}=r9({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}=aU(w(),p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"?g:n==null?void 0:n.tenantId),{existingShares:j}=Oh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t}),_=S.filter(V=>p==="org_groups"&&V.type!=="ORG_GROUP"||p==="tenant_groups"&&V.type!=="TENANT_GROUP"||p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&(!g||V.tenantId&&V.tenantId!==g)?!1:V.name.toLowerCase().includes(a.toLowerCase())||V.description&&V.description.toLowerCase().includes(a.toLowerCase())),k=((F=j==null?void 0:j.shares)==null?void 0:F.specificGroups)||((B=j==null?void 0:j.shares)==null?void 0:B.groups)||[];N.useEffect(()=>{h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},[h]);const E=V=>{const $=V;m($),$==="org_groups"&&b(""),r==null||r($==="org_groups"?"specific_groups":"all_groups"),h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},T=S.filter(V=>u.some($=>$.id===V.id)),R=V=>{const $=u.some(L=>L.id===V),P=d.includes(V),H=k==null?void 0:k.some(L=>L.groupId===V);$?h.removeSelectedGroup(V):P?h.removeGroupFromRemove(V):H||h.addSelectedGroup({id:V,role:"VIEWER"})},O=(V,$)=>{h.updateSelectedGroupRole(V,$)},D=V=>{h.addGroupToRemove(V),h.removeSelectedGroup(V)},I=(V,$,P)=>{h.addGroupToUpdate({id:V,currentRole:$,newRole:P})};return n?c.jsxs(c.Fragment,{children:[c.jsx(wD,{shareType:p,onShareTypeChange:E,currentUser:n,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:c.jsx(pd,{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(os,{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(le,{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(V=>c.jsx(pe,{className:"hover:bg-muted",value:V.id,children:V.name},V.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(fv,{value:a,onChange:l,placeholder:"Search groups..."}),c.jsx(iU,{selectedGroups:u,groupObjects:T,onRemove:R,onRoleChange:O,getRoleOptions:mi}),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(oU,{groups:_,existingGroupShares:k,isLoading:C,resource:e,getRoleOptions:mi,currentUser:n,handleGroupToggle:R,handleGroupRoleChange:O,handleRemoveAccess:D,handleUpdateAccess:I})]})})]}):null}const GU=()=>{const e=AH(),t=qc(),n=vp(),r=Yd(),s=wp(),o=Sp(),i=Cp(),a=Np(),l=Yb(),u=gD(),d=bD(),f=T1(),h=PH(),p=N.useMemo(()=>()=>xhe({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=>cB(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 $5({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllUsersShare:l,onRemoveAccess:u}){const d=vp(),f=Yd(),h=wp(),p=Yb(),m=gD(),g=bD(),b=T1(),{buildShareData:x,validateShareData:y,isCurrentStateValid:v}=GU(),w=n||r||s,S=()=>{var E,T,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 D=d.length+f.length+h.length;return D===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${D} user${D!==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 ${D} user${D!==1?"s":""}`}else if(a==="all_users"){if(!l||l.role===void 0)return"Share with All Users";const D=l.role;return m===D?"Remove Access":"Update Access"}else if(a==="all_tenants"){const D=(T=(E=t==null?void 0:t.shares)==null?void 0:E.allTenantsOnly)==null?void 0:T[0];if(!D||D.role===void 0)return"Share with All Tenants";const I=D.role;return g===I?"Remove Access":"Update Access"}else if(a==="all_tenant_users"){const D=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!D||D.role===void 0)return"Share with All Tenant Users";const I=D.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 D=d.length+f.length+h.length;return D===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${D} user${D!==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 ${D} user${D!==1?"s":""}`}return"Share"},C=()=>w||!e||a==="all_tenant_users"&&!p||a==="specific_tenant_users"&&!p?!0:!v,j=()=>{const E=x();E&&y(E)&&o(E)},_=()=>{var E,T,R,O;if(a==="all_users")if(!l||l.role===void 0){const D=x();D&&y(D)&&o(D)}else{const D=l.role;if(m===D)u==null||u();else{const F=x();if(F&&y(F)){const B={...F,updateAccess:!0};o(B)}}}else if(a==="all_tenants"){const D=(T=(E=t==null?void 0:t.shares)==null?void 0:E.allTenantsOnly)==null?void 0:T[0];if(!D||D.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=D.role;if(g===I)u==null||u();else{const B=x();if(B&&y(B)){const V={...B,updateAccess:!0};o(V)}}}}else if(a==="all_tenant_users"){const D=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!D||D.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=D.role;if(b===I)u==null||u();else{const B=x();if(B&&y(B)){const V={...B,updateAccess:!0};o(V)}}}}},k=()=>{var E,T,R,O;if(a==="all_users"){if(!l||l.role===void 0)return"default";const D=l.role;return m===D?"destructive":"default"}else if(a==="all_tenants"){const D=(T=(E=t==null?void 0:t.shares)==null?void 0:E.allTenantsOnly)==null?void 0:T[0];if(!D||D.role===void 0)return"default";const I=D.role;return g===I?"destructive":"default"}else if(a==="all_tenant_users"){const D=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!D||D.role===void 0)return"default";const I=D.role;return b===I?"destructive":"default"}return"default"};return c.jsxs(Ms,{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(Zu,{className:"mr-2 h-4 w-4"}),!w&&S()]})}),(a==="all_users"||a==="all_tenants"||a==="all_tenant_users")&&c.jsxs(oe,{onClick:_,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(os,{className:"mr-2 h-4 w-4"}),!w&&S()]})]})}function KSe({resource:e,isSharing:t,isRemoving:n,isUpdating:r,onShare:s,onClose:o,shareTabType:i,currentAllUsersShare:a}){const l=vp(),u=Yd(),d=wp(),f=Sp(),h=Cp(),p=Np();qc(),AH();const m=T1();Yb();const{buildShareData:g,validateShareData:b,isCurrentStateValid:x}=GU(),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 T=g();if(T&&b(T)){const R={...T,removeAccess:!0};s(R)}}else{const T=g();if(T&&b(T)){const R={...T,updateAccess:!0};s(R)}}}},_=()=>!a||a.role==="NONE"?"default":"destructive";return c.jsxs(Ms,{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(Zu,{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(Zu,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="all_users"&&c.jsxs(oe,{onClick:j,disabled:w(),variant:_(),children:[y?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Zu,{className:"mr-2 h-4 w-4"}),!y&&v()]})]})}function XSe({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllGroupsShare:l,onRemoveAccess:u}){const d=Sp(),f=Cp(),h=Np();PH(),qc();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 to(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function el(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function QSe(e,t,n){const{resourceType:r,resourceId:s,shareMutation:o,removeMutation:i,existingShares:a,resetUserSelections:l}=t;if(s)switch(e.context){case"org-tab":if(e.mode==="allOrgUsers"){const u=to(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=to(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=el(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=to(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=to(r,s,[{scope:"all_tenants_only",role:e.allTenantsRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="allTenantUsers"){const u=to(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=el(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=to(r,s,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.newRole}]);o(m,{onSuccess:()=>{l()}})}),u&&u.length>0){const p=to(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=el(r,s,[{scope:"all_tenant_users",role:"VIEWER"}]);i(u,{onSuccess:()=>{l()}})}else if(e.updateAccess){const u=to(r,s,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:e.tenantWideRole}]);o(u,{onSuccess:()=>{l()}})}else{const u=to(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=to(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=el(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=to(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=to(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),ze.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(d&&d.length>0){const h=el(r,s,d.map(p=>({scope:"group",groupId:p,role:"VIEWER"})));i(h,{onSuccess:()=>{var p;l(),(p=t.resetGroupSelections)==null||p.call(t),ze.success(`Removed access from ${d.length} group${d.length!==1?"s":""}`)}})}f&&f.length>0&&f.forEach(h=>{const p=to(r,s,[{scope:"group",groupId:h.id,role:h.newRole}]);o(p,{onSuccess:()=>{var m;l(),(m=t.resetGroupSelections)==null||m.call(t),ze.success("Updated access for group")}})})}break}}function JSe(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=el(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=el(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=el(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=el(s,o,[{scope:"org_users_only",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove org-wide access failed:",v)}})}}}}function eCe(e,t,n){const r=Yc(),s=Yd(),o=mD(),i=qc(),{currentUser:a}=_s(),{existingShares:l}=Oh({debouncedSearchQuery:"",resourceId:e||"",resourceType:$t.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:$t.DASHBOARD,resourceId:e,shareMutation:t,removeMutation:n,existingShares:l,resetUserSelections:u,resetGroupSelections:d};QSe(p,m,a)},[e,t,n,l,u,d,a]),h=N.useCallback(()=>{if(!e)return;const p={resourceType:$t.DASHBOARD,resourceId:e,removeMutation:n,existingShares:l,resetUserSelections:u};JSe(s,o||"",i||"",p)},[e,t,n,l,u,d,s,o,i]);return{handleShareSubmit:f,handleRemoveAccess:h}}function ZU({resource:e,resourceType:t,onClose:n,onShareSuccess:r,onRemoveSuccess:s}){var O,D,I,F,B,V,$,P;const{currentUser:o}=_s(),[i,a]=N.useState("specific_users"),[l,u]=N.useState("specific_users"),[d,f]=N.useState("specific_groups"),h=Yc(),p=mD(),m=qc(),g=o9(),b=i9(),{handleShareSubmit:x,handleRemoveAccess:y}=eCe(e.id,(H,L)=>{g.mutate(H,{...L,onSuccess:()=>{var A;(A=L==null?void 0:L.onSuccess)==null||A.call(L),r==null||r()}})},(H,L)=>{b.mutate(H,{...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}=Oh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant"}),{existingShares:j}=Oh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"organization"}),_=(D=(O=C==null?void 0:C.shares)==null?void 0:O.tenantWide)==null?void 0:D[0],k=(F=(I=j==null?void 0:j.shares)==null?void 0:I.orgUsersOnly)==null?void 0:F[0],E=()=>{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"}},T=N.useCallback(()=>{h.resetShareState(),n()},[h,n]),R=(o==null?void 0:o.type)==="organization";return c.jsx(as,{open:!0,onOpenChange:T,children:c.jsxs(Br,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[c.jsxs(Vr,{children:[c.jsx(Hr,{children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Zu,{className:"h-5 w-5"}),' Share "',e==null?void 0:e.title,'"']})}),c.jsx(Ds,{children:R?"Share this resource with org users or tenant users. As a super admin, you can share with all users.":"Share this resource with other users in your tenant."})]}),R?c.jsxs(ls,{value:p,onValueChange:H=>{const L=H;h.setSelectedTab(L),h.resetUserSelections(),h.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[c.jsxs(Ur,{className:"mb-2 grid w-full grid-cols-3",children:[c.jsx(Ut,{value:"org",children:"Org Users"}),c.jsx(Ut,{value:"tenant",children:"Tenant Users"}),c.jsx(Ut,{value:"groups",children:"Groups"})]}),c.jsx(Yn,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(fSe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:u,isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx(Yn,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(F5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:H=>a(H),isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx(Yn,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(ZSe,{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(F5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:H=>a(H),isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx("div",{className:"mt-auto flex-shrink-0",children:R?p==="org"?c.jsx($5,{resource:e,existingShares:j,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:l,currentAllUsersShare:k,onRemoveAccess:y}):p==="tenant"?c.jsx($5,{resource:e,existingShares:C,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:E(),currentAllUsersShare:_,onRemoveAccess:y}):c.jsx(XSe,{resource:e,existingShares:j,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:d,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(V=(B=j==null?void 0:j.shares)==null?void 0:B.allOrgGroups)==null?void 0:V[0]:(P=($=C==null?void 0:C.shares)==null?void 0:$.allTenantGroups)==null?void 0:P[0],onRemoveAccess:y}):c.jsx(KSe,{resource:e,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:i,currentAllUsersShare:_,onRemoveAccess:y})})]})})}const Cn=M.forwardRef(({className:e,type:t,...n},r)=>c.jsx("input",{type:t,className:K("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}));Cn.displayName="Input";function KU({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(as,{open:e,onOpenChange:h=>h?null:s(),children:c.jsx(Br,{className:"sm:max-w-md",children:c.jsxs("form",{onSubmit:f,className:"space-y-4",children:[c.jsxs(Vr,{children:[c.jsxs(Hr,{children:["Edit ",t]}),c.jsxs(Ds,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(le,{htmlFor:"resource-title",children:"Title"}),c.jsx(Cn,{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(le,{htmlFor:"resource-description",children:"Description"}),c.jsx(Ud,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),c.jsxs(Ms,{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 tCe({onDashboardSelect:e}){var q;const{authToken:t}=Ge(),[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),b=Ys(Y=>Y.actions.selectDashboard),{userContext:x}=_s(),y=((q=x==null?void 0:x.permissions)==null?void 0:q.canCreateDashboard)??!1,{onCreateSuccess:v}=u9({onDashboardSelect:e}),{resources:w,isLoading:S,isError:C,createResource:j,updateResource:_,deleteResource:k,duplicateResource:E,isCreating:T,isDeleting:R,refetch:O}=c9(()=>{u(!1),f(null)},Y=>{r(!1),v(Y,O)}),{startUpdating:D,stopUpdating:I,isUpdating:F}=l9(),B=Y=>{const U=w.find(z=>z.id===Y);U&&(b(U),e==null||e(Y))},V=Y=>{j({title:Y.title,description:Y.description,isPrivate:!1})},$=Y=>{f(Y),u(!0)},P=()=>{d&&k(d.id)},H=Y=>{p(Y),E(Y,{onSettled:()=>p(null)})},L=(Y,U,z)=>{var X;const G=Object.fromEntries(Object.entries(U).filter(([,ne])=>ne!==void 0));if(Object.keys(G).length===0){(X=z==null?void 0:z.onSuccess)==null||X.call(z);return}const Z=Object.keys(G),te=Z.length===1?Z[0]:void 0;D(Y,te),_({resourceId:Y,data:G},{onSuccess:()=>{var ne;I(Y,te),(ne=z==null?void 0:z.onSuccess)==null||ne.call(z)},onError:()=>{var ne;I(Y,te),(ne=z==null?void 0:z.onError)==null||ne.call(z)}})},A=Y=>{a(Y),o(!0)},W=Y=>new Date(Y).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return t?S?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..."})]})}):C?c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"text-center",children:[c.jsx(md,{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"}),w.length>0&&y&&c.jsx("div",{className:"mt-6 flex gap-3",children:c.jsxs(oe,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(jr,{className:"h-4 w-4"}),"Create New Dashboard"]})})]}),w.length>0&&c.jsxs("div",{className:"rounded-md bg-orange-500 px-3 py-1 text-sm font-medium text-white",children:[w.length," dashboard",w.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:w.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(I_,{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:y?"Create your first dashboard to get started with analytics":"No dashboards have been shared with you yet"}),y&&c.jsxs(oe,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(jr,{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:w.map(Y=>c.jsx(jue,{dashboard:Y,onView:B,isDeleting:R&&(d==null?void 0:d.id)===Y.id,isDuplicating:h===Y.id,onEditDetails:g,onDeleteClick:$,onDuplicateDashboard:H,onShareDashboard:A,formatDate:W},Y.id))})]})})}),c.jsx(z9,{open:n,onOpenChange:r,onSubmit:V,isCreating:T}),m&&c.jsx(KU,{open:!!m,resourceLabel:"Dashboard",initialTitle:m.title||"",initialDescription:m.description||"",onClose:()=>g(null),onSave:Y=>{L(m.id,Y,{onSuccess:()=>{g(null)}})},isSaving:F(m.id)}),c.jsx($b,{open:l,onOpenChange:u,children:c.jsxs(ap,{children:[c.jsxs(lp,{children:[c.jsx(up,{children:"Delete Dashboard?"}),c.jsxs(dp,{children:['Are you sure you want to delete "',d==null?void 0:d.title,'"? This action cannot be undone.']})]}),c.jsxs(cp,{children:[c.jsx(hp,{disabled:R,children:"Cancel"}),c.jsx(fp,{onClick:P,disabled:R,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:R?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete"})]})]})}),i&&s&&c.jsx(ZU,{resource:i,resourceType:$t.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(md,{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 nd=Nl()(Sne(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})})),XU=e=>nd(t=>t.panels[e]),QU=()=>nd(e=>e.fullscreen),JU=e=>nd(t=>t.panels[e].container??null);function eW(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 nCe(e){const{selectedEntities:t}=e,n=t.map(r=>({...r,qualifiedEntityName:Af(r)}));return{...e,selectedEntities:n}}const L5={selectedEntities:[]},Bi=Nl()(Nb((e,t)=>({currentAIContext:L5,activeAssistantType:null,reasoningEffort:"low",showReasoning:!1,messageQueues:{dashboard:[],editor:[]},fileAttachments:{dashboard:[],editor:[]},uploadProgress:new Map,actions:{setCurrentAIContext:n=>{e(r=>{r.currentAIContext=nCe(n)})},setActiveAssistantType:n=>{e(r=>{r.activeAssistantType=n})},updateSelectedEntities:n=>{e(r=>{r.currentAIContext.selectedEntities=n})},clearAIContext:()=>{e(n=>{n.currentAIContext=L5})},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]}}))),_p=()=>Bi(e=>e.currentAIContext),_D=()=>Bi(e=>e.activeAssistantType),rCe=()=>Bi(e=>e.reasoningEffort),sCe=()=>Bi(e=>e.showReasoning),F1=()=>Bi(e=>e.actions),tW=e=>Bi(t=>t.messageQueues[e]),Mp=()=>Bi(e=>({queueMessage:e.actions.queueMessage,dequeueMessage:e.actions.dequeueMessage,removeFromQueue:e.actions.removeFromQueue,clearQueue:e.actions.clearQueue})),MD=e=>Bi(t=>t.fileAttachments[e]),DD=()=>Bi(e=>({addFileAttachment:e.actions.addFileAttachment,removeFileAttachment:e.actions.removeFileAttachment,clearFileAttachments:e.actions.clearFileAttachments,updateUploadProgress:e.actions.updateUploadProgress,getFileAttachments:e.actions.getFileAttachments}));function nW(){const{tokenProps:e,id:t}=Ge(),n=Ys(s=>s.selectedDashboard);return!!(n!=null&&n.id||t||e!=null&&e.dashboard_id)}function TD({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}=Ge();Ys(O=>O.selectedDashboard);const _=J(O=>O.themeStyle),k=J(O=>O.isSessionExpired),{isLoading:E,isError:T}=Yoe({customStyle:t,currentTheme:u,onSave:n,onEvent:r,defaultFilterValues:p,onFilterValuesChange:m,selectedSheetId:g}),R=nW();return l&&!R&&!E?c.jsx(tCe,{}):E||!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]"})})):T?(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(_i,{children:"Session Expired"}),c.jsx("p",{className:"text-muted-foreground",children:"Please refresh your page to continue"})]})})):c.jsx("div",{className:K("isolate flex grow flex-col",{"h-full":x==="visual"},_==null?void 0:_.dashboardPanel,e),style:{},"data-role":"semaphor-container",...w})}var rW={exports:{}},Zb={},Vk={exports:{}};(function(e,t){(function(n,r){r(t)})(nl,function(n){function r(z){return function(Z,te,X,ne,se,ce,ae){return z(Z,te,ae)}}function s(z){return function(Z,te,X,ne){if(!Z||!te||typeof Z!="object"||typeof te!="object")return z(Z,te,X,ne);var se=ne.get(Z),ce=ne.get(te);if(se&&ce)return se===te&&ce===Z;ne.set(Z,te),ne.set(te,Z);var ae=z(Z,te,X,ne);return ne.delete(Z),ne.delete(te),ae}}function o(z,G){var Z={};for(var te in z)Z[te]=z[te];for(var te in G)Z[te]=G[te];return Z}function i(z){return z.constructor===Object||z.constructor==null}function a(z){return typeof z.then=="function"}function l(z,G){return z===G||z!==z&&G!==G}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(z){var G=z.areArraysEqual,Z=z.areDatesEqual,te=z.areMapsEqual,X=z.areObjectsEqual,ne=z.areRegExpsEqual,se=z.areSetsEqual,ce=z.createIsNestedEqual,ae=ce(he);function he(ye,Te,_e){if(ye===Te)return!0;if(!ye||!Te||typeof ye!="object"||typeof Te!="object")return ye!==ye&&Te!==Te;if(i(ye)&&i(Te))return X(ye,Te,ae,_e);var de=Array.isArray(ye),Re=Array.isArray(Te);if(de||Re)return de===Re&&G(ye,Te,ae,_e);var Oe=y.call(ye);return Oe!==y.call(Te)?!1:Oe===f?Z(ye,Te,ae,_e):Oe===h?ne(ye,Te,ae,_e):Oe===p?te(ye,Te,ae,_e):Oe===b?se(ye,Te,ae,_e):Oe===g||Oe===u?a(ye)||a(Te)?!1:X(ye,Te,ae,_e):Oe===d||Oe===m||Oe===x?l(ye.valueOf(),Te.valueOf()):!1}return he}function w(z,G,Z,te){var X=z.length;if(G.length!==X)return!1;for(;X-- >0;)if(!Z(z[X],G[X],X,X,z,G,te))return!1;return!0}var S=s(w);function C(z,G){return l(z.valueOf(),G.valueOf())}function j(z,G,Z,te){var X=z.size===G.size;if(!X)return!1;if(!z.size)return!0;var ne={},se=0;return z.forEach(function(ce,ae){if(X){var he=!1,ye=0;G.forEach(function(Te,_e){!he&&!ne[ye]&&(he=Z(ae,_e,se,ye,z,G,te)&&Z(ce,Te,ae,_e,z,G,te))&&(ne[ye]=!0),ye++}),se++,X=he}}),X}var _=s(j),k="_owner",E=Object.prototype.hasOwnProperty;function T(z,G,Z,te){var X=Object.keys(z),ne=X.length;if(Object.keys(G).length!==ne)return!1;for(var se;ne-- >0;){if(se=X[ne],se===k){var ce=!!z.$$typeof,ae=!!G.$$typeof;if((ce||ae)&&ce!==ae)return!1}if(!E.call(G,se)||!Z(z[se],G[se],se,se,z,G,te))return!1}return!0}var R=s(T);function O(z,G){return z.source===G.source&&z.flags===G.flags}function D(z,G,Z,te){var X=z.size===G.size;if(!X)return!1;if(!z.size)return!0;var ne={};return z.forEach(function(se,ce){if(X){var ae=!1,he=0;G.forEach(function(ye,Te){!ae&&!ne[he]&&(ae=Z(se,ye,ce,Te,z,G,te))&&(ne[he]=!0),he++}),X=ae}}),X}var I=s(D),F=Object.freeze({areArraysEqual:w,areDatesEqual:C,areMapsEqual:j,areObjectsEqual:T,areRegExpsEqual:O,areSetsEqual:D,createIsNestedEqual:r}),B=Object.freeze({areArraysEqual:S,areDatesEqual:C,areMapsEqual:_,areObjectsEqual:R,areRegExpsEqual:O,areSetsEqual:I,createIsNestedEqual:r}),V=v(F);function $(z,G){return V(z,G,void 0)}var P=v(o(F,{createIsNestedEqual:function(){return l}}));function H(z,G){return P(z,G,void 0)}var L=v(B);function A(z,G){return L(z,G,new WeakMap)}var W=v(o(B,{createIsNestedEqual:function(){return l}}));function q(z,G){return W(z,G,new WeakMap)}function Y(z){return v(o(F,z(F)))}function U(z){var G=v(o(B,z(B)));return function(Z,te,X){return X===void 0&&(X=new WeakMap),G(Z,te,X)}}n.circularDeepEqual=A,n.circularShallowEqual=q,n.createCustomCircularEqual=U,n.createCustomEqual=Y,n.deepEqual=$,n.sameValueZeroEqual=l,n.shallowEqual=H,Object.defineProperty(n,"__esModule",{value:!0})})})(Vk,Vk.exports);var RD=Vk.exports;const ID=o_(ute);var At={},oCe=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(At,"__esModule",{value:!0});At.bottom=AD;At.childrenEqual=cCe;At.cloneLayout=sW;At.cloneLayoutItem=rd;At.collides=$1;At.compact=iW;At.compactItem=aW;At.compactType=SCe;At.correctBounds=lW;At.fastPositionEqual=uCe;At.fastRGLPropsEqual=void 0;At.getAllCollisions=cW;At.getFirstCollision=Ru;At.getLayoutItem=PD;At.getStatics=OD;At.modifyLayout=oW;At.moveElement=Tm;At.moveElementAwayFromCollision=Uk;At.noop=void 0;At.perc=fCe;At.resizeItemInDirection=xCe;At.setTopLeft=vCe;At.setTransform=yCe;At.sortLayoutItems=VD;At.sortLayoutItemsByColRow=pW;At.sortLayoutItemsByRowCol=hW;At.synchronizeLayoutWithChildren=wCe;At.validateLayout=mW;At.withLayoutItem=lCe;var z5=RD,Dm=iCe(N);function iCe(e){return e&&e.__esModule?e:{default:e}}const aCe=process.env.NODE_ENV==="production";function AD(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 sW(e){const t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=rd(e[n]);return t}function oW(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 lCe(e,t,n){let r=PD(e,t);return r?(r=n(rd(r)),e=oW(e,r),[e,r]):[e,null]}function rd(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 cCe(e,t){return(0,z5.deepEqual)(Dm.default.Children.map(e,n=>n==null?void 0:n.key),Dm.default.Children.map(t,n=>n==null?void 0:n.key))&&(0,z5.deepEqual)(Dm.default.Children.map(e,n=>n==null?void 0:n.props["data-grid"]),Dm.default.Children.map(t,n=>n==null?void 0:n.props["data-grid"]))}At.fastRGLPropsEqual=oCe;function uCe(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function $1(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 iW(e,t,n,r){const s=OD(e),o=VD(e,t),i=Array(e.length);for(let a=0,l=o.length;a<l;a++){let u=rd(o[a]);u.static||(u=aW(s,u,t,n,o,r),s.push(u)),i[e.indexOf(o[a])]=u,u.moved=!1}return i}const dCe={x:"w",y:"h"};function Hk(e,t,n,r){const s=dCe[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;$1(t,a)&&Hk(e,a,n+t[s],r)}}t[r]=n}function aW(e,t,n,r,s,o){const i=n==="vertical",a=n==="horizontal";if(i)for(t.y=Math.min(AD(e),t.y);t.y>0&&!Ru(e,t);)t.y--;else if(a)for(;t.x>0&&!Ru(e,t);)t.x--;let l;for(;(l=Ru(e,t))&&!(n===null&&o);)if(a?Hk(s,t,l.x+l.w,"x"):Hk(s,t,l.y+l.h,"y"),a&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!Ru(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function lW(e,t){const n=OD(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(;Ru(n,o);)o.y++}return e}function PD(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function Ru(e,t){for(let n=0,r=e.length;n<r;n++)if($1(e[n],t))return e[n]}function cW(e,t){return e.filter(n=>$1(n,t))}function OD(e){return e.filter(t=>t.static)}function Tm(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=VD(e,i);(i==="vertical"&&typeof r=="number"?d>=r:i==="horizontal"&&typeof n=="number"?u>=n:!1)&&(f=f.reverse());const p=cW(f,t),m=p.length>0;if(m&&l)return sW(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=Uk(e,x,t,s,i):e=Uk(e,t,x,s,i))}return e}function Uk(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=Ru(e,f),p=h&&h.y+h.h>t.y,m=h&&t.x+t.w>h.x;if(h){if(p&&a)return Tm(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 Tm(e,t,n.x,void 0,r,l,s)}else return`${n.i}${f.x}${f.y}`,Tm(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:Tm(e,n,i?n.x+1:void 0,a?n.y+1:void 0,r,l,s)}function fCe(e){return e*100+"%"}const uW=(e,t,n,r)=>e+n>r?t:n,dW=(e,t,n)=>e<0?t:n,fW=e=>Math.max(0,e),FD=e=>Math.max(0,e),$D=(e,t,n)=>{let{left:r,height:s,width:o}=t;const i=e.top-(s-e.height);return{left:r,width:o,height:dW(i,e.height,s),top:FD(i)}},LD=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{top:r,height:o,width:uW(e.left,e.width,i,n),left:fW(s)}},zD=(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:uW(e.left,e.width,o,n),top:FD(r),left:fW(i)}},BD=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{width:i,left:s,height:dW(r,e.height,o),top:FD(r)}},hCe=function(){return $D(arguments.length<=0?void 0:arguments[0],LD(...arguments))},pCe=function(){return $D(arguments.length<=0?void 0:arguments[0],zD(...arguments))},mCe=function(){return BD(arguments.length<=0?void 0:arguments[0],LD(...arguments))},gCe=function(){return BD(arguments.length<=0?void 0:arguments[0],zD(...arguments))},bCe={n:$D,ne:hCe,e:LD,se:mCe,s:BD,sw:gCe,w:zD,nw:pCe};function xCe(e,t,n,r){const s=bCe[e];return s?s(t,{...t,...n},r):n}function yCe(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 vCe(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 VD(e,t){return t==="horizontal"?pW(e):t==="vertical"?hW(e):e}function hW(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 pW(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 wCe(e,t,n,r,s){e=e||[];const o=[];Dm.default.Children.forEach(t,a=>{if((a==null?void 0:a.key)==null)return;const l=PD(e,String(a.key)),u=a.props["data-grid"];l&&u==null?o.push(rd(l)):u?(aCe||mW([u],"ReactGridLayout.children"),o.push(rd({...u,i:a.key}))):o.push(rd({w:1,h:1,x:0,y:AD(o),i:String(a.key)}))});const i=lW(o,{cols:n});return s?i:iW(i,r,n)}function mW(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 SCe(e){const{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}const CCe=()=>{};At.noop=CCe;var Ta={};Object.defineProperty(Ta,"__esModule",{value:!0});Ta.calcGridColWidth=L1;Ta.calcGridItemPosition=NCe;Ta.calcGridItemWHPx=Wk;Ta.calcWH=kCe;Ta.calcXY=jCe;Ta.clamp=Iu;function L1(e){const{margin:t,containerPadding:n,containerWidth:r,cols:s}=e;return(r-t[0]*(s-1)-n[0]*2)/s}function Wk(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function NCe(e,t,n,r,s,o){const{margin:i,containerPadding:a,rowHeight:l}=e,u=L1(e),d={};return o&&o.resizing?(d.width=Math.round(o.resizing.width),d.height=Math.round(o.resizing.height)):(d.width=Wk(r,u,i[0]),d.height=Wk(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 jCe(e,t,n,r,s){const{margin:o,containerPadding:i,cols:a,rowHeight:l,maxRows:u}=e,d=L1(e);let f=Math.round((n-i[0])/(d+o[0])),h=Math.round((t-i[1])/(l+o[1]));return f=Iu(f,0,a-r),h=Iu(h,0,u-s),{x:f,y:h}}function kCe(e,t,n,r,s,o){const{margin:i,maxRows:a,cols:l,rowHeight:u}=e,d=L1(e);let f=Math.round((t+i[0])/(d+i[0])),h=Math.round((n+i[1])/(u+i[1])),p=Iu(f,0,l-r),m=Iu(h,0,a-s);return["sw","w","nw"].indexOf(o)!==-1&&(p=Iu(f,0,l)),["nw","n","ne"].indexOf(o)!==-1&&(m=Iu(h,0,a)),{w:p,h:m}}function Iu(e,t,n){return Math.max(Math.min(e,n),t)}var z1={},qk={exports:{}},_0={exports:{}},nn={};/** @license React v16.13.1
|
|
763
|
+
${R}`:R},color:_=>{if(f)return f;const k=_==null?void 0:_.raw,E=D5({raw:k,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a});return Bo(E)},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:_=>{const k=_==null?void 0:_.raw;return D5({raw:k,dimensionKeys:t,colorLookups:r,themeStyle:o,preferences:i,colorMode:a})}}}function Nwe({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 Dwe(o==null?void 0:o.raw,e)},label:s=>{const o=s==null?void 0:s.raw,i=bH(o,e),a=Number((o==null?void 0:o.v)??0),l=xH(a,n),u=t||"Value";return i?`${i} — ${u}: ${l}`:`${u}: ${l}`}}}}}}function jwe(e){return e.reduce((t,n)=>Nr(t,n||{}),{})}function kwe(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 Ewe(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))??pp();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 _we(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 bH(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 Mwe(e._data,t);if(e.path){const r=e.path.split("."),s=r[r.length-1];if(s)return s}return""}function Mwe(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 Dwe(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 xH(e,t){return Ws(e,t.format,t.formatOptions)}function D5({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))??pp(),a=Twe(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=uD(f,0,d);if(h===0||o==="category")return u;const p=Rwe(e);return Iwe(u,p,h)}function Twe(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 Rwe(e){if(!e)return 1;const t=Number(e.v??0),n=Number(e.gs??e.s??0);return n>0&&Number.isFinite(t)?uD(t/n,0,1):1}function Iwe(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=uD(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 Awe(i,a,l)}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 Awe(e,t,n){const r=s=>s.toString(16).padStart(2,"0");return`#${r(aN(e))}${r(aN(t))}${r(aN(n))}`}function aN(e){return Math.min(255,Math.max(0,Math.round(e)))}function uD(e,t,n){return Math.max(t,Math.min(n,e))}const yH=["poor","satisfactory","good"],lN={poor:"Poor",satisfactory:"Average",good:"Good"},Pwe=["#F5F6F8","#E3E6EC","#CED4DD"],Owe=["#1F2933","#27323D","#303B47"];function Fwe({data:e,cfg:t,customCfg:n,preferences:r,themeStyle:s}){var se,ce,ae,he,ye,Te,_e;if(!e||e.length===0)return{type:"bar",data:{labels:[],datasets:[]}};const{dimensionKeys:o,metricKeys:i,keys:a}=Gn(e),l=o[0]??a[0];if(!l)return{type:"bar",data:{labels:[],datasets:[]}};const u=i[0]??a.find(de=>de!==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(de=>de!==u),h=(d==null?void 0:d.comparativeMetricKey)??(d!=null&&d.disableAutoComparative?void 0:i.find(de=>de!==u&&de!==f)),p=J.getState(),m=s??p.themeStyle,g=p.theme==="dark",b=$we({data:e,dimensionKey:l,actualKey:u,targetKey:f,comparativeKey:h,bulletConfig:d}),x=b.map(de=>de.label),y=(d==null?void 0:d.showRanges)??Qwe(d),v=Bwe(b,y),w=(se=r==null?void 0:r.chartOptions)==null?void 0:se.indexAxis,C=(w?w==="y"?"horizontal":"vertical":void 0)??(d==null?void 0:d.orientation)??"horizontal",j=C==="vertical"?"x":"y",_=r?{...r,chartOptions:{...r.chartOptions||{},indexAxis:j}}:{chartOptions:{indexAxis:j}},k=Zwe(r),E=Xwe(d),T=Kwe(g),R=pp().filter(Boolean),O=(((ae=(ce=m==null?void 0:m.chart)==null?void 0:ce.dataset)==null?void 0:ae.backgroundColor)||[]).filter(Boolean),D=(((ye=(he=m==null?void 0:m.chart)==null?void 0:he.dataset)==null?void 0:ye.borderColor)||[]).filter(Boolean),I=O.length>0?O:R.length>0?R:["#3b82f6"],F=D.length>0?D:I.length>0?I:["#111827"],B=uN({metricKey:u,metricIndex:0,preferences:r,backgroundPalette:I,borderPalette:F}),$=uN({metricKey:f||`${u}__target`,metricIndex:1,preferences:r,backgroundPalette:I,borderPalette:F}).borderColor||B.borderColor||"#111827",P=uN({metricKey:h,metricIndex:2,preferences:r,backgroundPalette:I,borderPalette:F}),H=y?Vwe(b,T,C,g,E):[],L=Hwe(b,B,C,u),A=Uwe(b,P,C,h),W=[...H,L];A&&W.push(A);let q=Wwe({orientation:C,chartMax:v,formatConfig:k,series:b,preferences:_,rangeLabelMap:E,showRanges:y});const Y=(_e=(Te=r==null?void 0:r.chartOptions)==null?void 0:Te.plugins)==null?void 0:_e.legend;q=yB(q,Y);const{plugins:U=[],options:z}=Wd((r==null?void 0:r.customVisualCode)||""),G=n1e([q,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,z]),Z=b.some(de=>de.target!=null)&&v>0?Gwe({series:b,orientation:C,color:$}):null,te={type:"bar",data:{labels:x,datasets:W},options:G,plugins:Z?[...U,Z]:U},X=v1("bullet",r),ne=(r==null?void 0:r.dataLabelsConfig)??X;return te.options=Vb(te.options||{},ne,_,"bar"),te.options=Bb.applyAxisConfig(te.options||{},"bar",_),te.options=te.options||{},te.options.indexAxis=j,te}function $we({data:e,dimensionKey:t,actualKey:n,targetKey:r,comparativeKey:s,bulletConfig:o}){const i=e.map(l=>{const u=zwe(l[t]),d=Iy(l[n]),f=r&&l[r]!=null?Iy(l[r]):(o==null?void 0:o.targetValue)??null,h=s&&l[s]!=null?Iy(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=Lwe({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 Lwe({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:cN("poor",e,o,i,a*.5,s,a),satisfactory:cN("satisfactory",e,o,i,a*.8,s,a),good:cN("good",e,o,i,a,s,a)};let u=0;return yH.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 cN(e,t,n,r,s,o,i){const a=n==null?void 0:n[e];if(a&&t[a]!=null)return Iy(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 Iy(e){const t=Number(e);return Number.isFinite(t)?t:0}function zwe(e){return e==null||e===""?"(Blank)":String(e)}function Bwe(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 Vwe(e,t,n,r,s){const o=[];return yH.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:e1e(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 Hwe(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 Uwe(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 Wwe({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=>Ws(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:qwe(r,n,o,i)}},indexAxis:e==="vertical"?"x":"y"}}function qwe(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"}: ${Ws(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=Ws(o.target,t.format,t.options),d=o.actual-o.target,f=Ws(d,t.format,t.options),h=o.targetKey||"Target";i.push(`${h}: ${u} (${f})`)}const a=Ywe(o,n);r&&a&&i.push(`Range: ${a}`);const l=o.comparative;return l!=null&&i.push(`Comparative: ${Ws(l,t.format,t.options)}`),i}}}function Ywe(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 Gwe({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 Zwe(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 Kwe(e){return[...e?Owe:Pwe]}function Xwe(e){var n,r,s;const t=(e==null?void 0:e.rangeLabels)||{};return{poor:((n=t.poor)==null?void 0:n.trim())||lN.poor,satisfactory:((r=t.satisfactory)==null?void 0:r.trim())||lN.satisfactory,good:((s=t.good)==null?void 0:s.trim())||lN.good}}function Qwe(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 Jwe(e,t,n){const r=vH(n,0,1);if(r<=0)return e;if(r>=1)return t;const s=I5(e),o=I5(t);if(!s||!o)return e;const i=Math.round(s.r+(o.r-s.r)*r),a=Math.round(s.g+(o.g-s.g)*r),l=Math.round(s.b+(o.b-s.b)*r);return t1e(i,a,l)}function e1e(e,t,n){return Jwe(e,n?"#000000":"#ffffff",t)}function uN({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 I5(e){const t=e.replace("#","");if(t.length!==6)return null;const n=parseInt(t,16);return{r:n>>16&255,g:n>>8&255,b:n&255}}function t1e(e,t,n){return`#${dN(e)}${dN(t)}${dN(n)}`}function dN(e){return vH(Math.round(e),0,255).toString(16).padStart(2,"0")}function vH(e,t,n){return Math.max(t,Math.min(n,e))}function n1e(e){return e.reduce((t,n)=>Nr(t,n||{}),{})}const Ak={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"}},wH=["#dcfce7","#15803d"],k0={type:"matrix",data:{datasets:[]},options:{responsive:!0,maintainAspectRatio:!1}};function r1e({data:e,cfg:t,customCfg:n,preferences:r,cardType:s,themeStyle:o}){var q,Y,U;if(!Array.isArray(e)||e.length===0)return k0;const{dimensionKeys:i,metricKeys:a,keys:l}=Gn(e),u=i[0]??l[0];if(!u)return k0;const d=i[1],f=l.find(z=>z!==u&&!a.includes(z)&&z!==d)??d,h=!d&&(!f||typeof((q=e[0])==null?void 0:q[f])!="string")&&a.length>1,p=a[0]??l.find(z=>z!==u&&z!==f);if(!p&&!h)return k0;const m=r==null?void 0:r.heatmapConfig,g=(m==null?void 0:m.legendPosition)??"bottom",b=h?o1e({data:e,dimensionKey:u,metricKeys:a}):s1e({data:e,xKey:u,yKey:f||p,metricKey:p});if(b.length===0)return k0;const x=h?a.map(Ph):fN(b.map(z=>z.x)),y=fN(h?e.map(z=>Ph(z==null?void 0:z[u])):b.map(z=>z.y)),v=i1e(b),w=o??J.getState().themeStyle,S=f1e({min:v.min,max:v.max,heatmapConfig:m,themeStyle:w}),C=a1e({points:b,xLabels:x,yLabels:y,fill:(m==null?void 0:m.fillMissingCells)!==!1}),j=b1e(r),k=["auto","number","currency","percent","none"].includes(j.format)?j.format:"auto",E=v1("heatmap",r),T=E?{...E,format:E.format??k,formatOptions:E.formatOptions??j.options}:void 0,R=(r==null?void 0:r.dataLabelsConfig)??T,O=l1e({points:C,xLabels:x,yLabels:y,colorScale:S,datasetLabel:h?"Value":p||"Value",dataLabelPrefs:R,formatConfig:j}),D=c1e({xLabels:x,yLabels:y,heatmapConfig:m,formatConfig:j,themeStyle:w,legendPreferences:(U=(Y=r==null?void 0:r.chartOptions)==null?void 0:Y.plugins)==null?void 0:U.legend,cardType:s,legendPosition:g}),{plugins:I=[],options:F}=Wd((r==null?void 0:r.customVisualCode)||""),B=x1e([D,t==null?void 0:t.options,(r==null?void 0:r.chartOptions)||void 0,n==null?void 0:n.options,F]),V=(m==null?void 0:m.showLegend)===!1?null:h1e({stops:S.stops,min:v.min,max:v.max,formatConfig:j,position:g}),$={type:"matrix",data:{datasets:[O]},options:B,plugins:V?[...I,V]:I};$.options=Vb($.options||{},R,r,"matrix");const P=ek(s??"heatmap","x"),H=ek(s??"heatmap","y"),L=tk(P,r==null?void 0:r.xAxisConfig),A=tk(H,r==null?void 0:r.yAxisConfig),W=L||A||r?{...r||{},...L?{xAxisConfig:L}:{},...A?{yAxisConfig:A}:{}}:r;return $.options=Bb.applyAxisConfig($.options||{},"heatmap",W),$}function s1e({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=Ph(i),u=Ph(a),d=`${l}__${u}`,f=SH(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 o1e({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=Ph(o);n.forEach(a=>{if(a===t)return;const l=SH(s==null?void 0:s[a]),u=Ph(a);r.push({x:u,y:i,v:l,raw:{...s,_metricKey:a}})})}),r}function Ph(e){return e==null||e===""?"Unknown":String(e)}function SH(e){const t=Number(e);return Number.isFinite(t)?t:null}function fN(e){const t=new Set,n=[];return e.forEach(r=>{t.has(r)||(t.add(r),n.push(r))}),n}function i1e(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 a1e({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 l1e({points:e,xLabels:t,yLabels:n,colorScale:r,datasetLabel:s,dataLabelPrefs:o,formatConfig:i}){const a=ipe(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 g1e(h,.85)},borderWidth:1,borderColor:"rgba(255, 255, 255, 0.65)",width:({chart:d})=>{var f;return A5((f=d==null?void 0:d.chartArea)==null?void 0:f.width,t.length)},height:({chart:d})=>{var f;return A5((f=d==null?void 0:d.chartArea)==null?void 0:f.height,n.length)},datalabels:{display:a,anchor:"center",align:"center",formatter:d=>{let f=null;return typeof d=="number"?f=d:d&&typeof d=="object"&&"v"in d&&(f=Number(d.v)),f==null||Number.isNaN(f)?"":dD(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(m1e(h))},font:{size:Math.max(10,Math.min(14,120/l))}}}}function A5(e,t){return!e||t===0?0:Math.max(4,e/t-2)}function c1e({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=wB(i??"heatmap"),f=spe(d,o);return{responsive:!0,maintainAspectRatio:!1,layout:{padding:u1e(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:d1e(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 u1e(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 d1e(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=dD(n.v,e);return s?`${s}: ${o}`:`${r}: ${o}`}}}function f1e({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"?Ak[i]??Ak.blue:void 0,l=n==null?void 0:n.colorRange,u=l&&l[0]&&l[1]?l:a?[a.start,a.end]:i==="custom"?wH: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:P5(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=Bg((w-e)/g,0,1);return P5(du(d),du(f),j)}const S=Bg((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 h1e({stops:e,min:t,max:n,formatConfig:r,position:s}){if(!e||e.length===0)return null;const o=i=>dD(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(fl()),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(_=>C.addColorStop(_.offset,_.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(_=>C.addColorStop(_.offset,_.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=CH(e);return t?p1e(t.r,t.g,t.b,1):e}return e}function P5(e,t,n){const r=Fv(e),s=Fv(t);if(!r||!s)return e;const o=Bg(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 Fv(e){if(e.startsWith("#")){const n=CH(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 CH(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 p1e(e,t,n,r){return`rgba(${e}, ${t}, ${n}, ${r})`}function m1e(e){const t=Fv(e);return t?`#${hN(t.r)}${hN(t.g)}${hN(t.b)}`:"#000000"}function hN(e){return Bg(Math.round(e),0,255).toString(16).padStart(2,"0")}function g1e(e,t){const n=Fv(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${Bg(t,0,1)})`:e}function Bg(e,t,n){return Math.min(n,Math.max(t,e))}function dD(e,t){return e==null||Number.isNaN(e)?"—":Ws(e,t.format,t.options)}function b1e(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 x1e(e){return e.reduce((t,n)=>n?xh({},t,n):t,{})}function fD({card:e,data:t,cardType:n="bar",cfg:r,customCfg:s,provider:o="chartjs",userSettings:i,preferences:a,topoJson:l,queryConfig:u}){var m,g,b,x,y,v,w,S;const d=e.config;let f=t;const h=d&&d.pivotByColumns&&d.pivotByColumns.length>0,p=d&&d.groupByColumns&&d.groupByColumns.length>0;if(h&&p&&(f=tpe(t,(d==null?void 0:d.metricColumns)||[])),n==="map"){if(!l)return null;const C=(m=a==null?void 0:a.mapVisualOptions)==null?void 0:m.objectKey;if(!C)return null;const j=nwe(l,(g=l==null?void 0:l.objects)==null?void 0:g[C]).features;if(!j)return null;const _={plugins:{datalabels:{display:!1}},scales:{x:{display:!1,grid:{display:!1}},y:{display:!1,grid:{display:!1}},projection:{axis:"x",projection:((b=a==null?void 0:a.mapVisualOptions)==null?void 0:b.projection)||"mercator",projectionScale:((x=a==null?void 0:a.mapVisualOptions)==null?void 0:x.projectionScale)||1,projectionOffset:((y=a==null?void 0:a.mapVisualOptions)==null?void 0:y.projectionOffset)||[0,0]},color:{axis:"x",interpolate:((v=a==null?void 0:a.mapVisualOptions)==null?void 0:v.colorScale)||"blues",quantize:5,legend:{position:"bottom-right",align:"right"}}}},{keys:k}=Gn(f),E=j.map(F=>{var P;const B=k==null?void 0:k[0],V=k==null?void 0:k[1],$=(P=f.find(H=>(H==null?void 0:H[B])===F.properties.NAME||(H==null?void 0:H[B])===F.properties.name))==null?void 0:P[V];return{feature:F,value:$}}),R=Ku([{label:C,data:E,borderColor:"lightgray"}],s),O={type:"choropleth",data:{labels:j.map(F=>F.properties.NAME||F.properties.name),datasets:R},options:_},{options:D}=Um({cfg:O,preferences:a,customCfg:s,cardType:n});return{...O,options:D}}if(n==="bar"){const C=dwe(r);return af({card:e,data:f,cfg:C,customCfg:s,cardType:n,preferences:a})}if(n==="horizontalBar"){const C=cwe(r);return af({card:e,data:f,cfg:C,customCfg:s,cardType:n,preferences:a})}if(n==="funnel")return xwe({data:f,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="tornado"||n==="pyramid")return wwe({data:f,cfg:r,customCfg:s,preferences:a,cardType:n,card:e});if(n==="treemap")return Swe({data:f,cfg:r,customCfg:s,preferences:a});if(n==="heatmap")return r1e({data:f,cfg:r,customCfg:s,preferences:a,cardType:n});if(n==="bullet")return Fwe({data:f,cfg:r,customCfg:s,preferences:a});if(n==="stackedBar"||n==="stackedLine"){const C=hB(f),j=hwe(r,n,C),{keys:_}=Gn(f);return!C&&(!h||!p)&&(f=x1({dataArray:f,groupKey:_[0],pivotKey:_[1],valueKey:_[2],sortChart:a==null?void 0:a.sortChart})),af({card:e,data:f,cfg:j,customCfg:s,cardType:n,preferences:a})}if(n==="line"){const C=pwe(r);return af({card:e,data:f,cfg:C,customCfg:s,cardType:n,preferences:a})}if(n==="range")return ywe({data:f,cfg:r,customCfg:s,preferences:a,card:e});if(n==="pie"||n==="doughnut"||n==="polarArea"){const C=mwe(n,r),{keys:j}=Gn(f),_=j.slice(0,1),k=j.slice(1),E=mB(k,f,a,_==null?void 0:_[0]),T=Ku(E,s),{plugins:R,options:O}=Wd((a==null?void 0:a.customVisualCode)||""),D=_[0],I=zb(f,D),F=Nr((C==null?void 0:C.options)||{},(s==null?void 0:s.options)||{}),B=Nr(F,(a==null?void 0:a.chartOptions)||{}),V={...B,plugins:{...B.plugins,datalabels:{...(w=B.plugins)==null?void 0:w.datalabels,formatter:(W,q)=>{var Y,U,z,G;return Ks({number:Number(W),decimalPlaces:((Y=a==null?void 0:a.numberAxisFormat)==null?void 0:Y.decimalPlaces)||0,useSuffix:!!((U=a==null?void 0:a.numberAxisFormat)!=null&&U.suffix),customSuffix:"",locale:((z=a==null?void 0:a.numberAxisFormat)==null?void 0:z.locale)||"",currency:((G=a==null?void 0:a.numberAxisFormat)==null?void 0:G.currency)||""})}},tooltip:{...(S=B.plugins)==null?void 0:S.tooltip,callbacks:{label:function(W){var Z,te,X,ne;W.dataset.label;const Y=W.dataset.data.reduce((se,ce)=>se+ce,0),U=W.parsed,z=Ks({number:Number(U),decimalPlaces:((Z=a==null?void 0:a.numberAxisFormat)==null?void 0:Z.decimalPlaces)||0,useSuffix:!!((te=a==null?void 0:a.numberAxisFormat)!=null&&te.suffix),customSuffix:"",locale:((X=a==null?void 0:a.numberAxisFormat)==null?void 0:X.locale)||"",currency:((ne=a==null?void 0:a.numberAxisFormat)==null?void 0:ne.currency)||""}),G=(U/Y*100).toFixed(2);return z+` (${G}%)`},footer:function(W){var Y,U,z,G;return(((U=(Y=e==null?void 0:e.interactionConfig)==null?void 0:Y.drillHierarchies)==null?void 0:U.length)??0)>0||(((G=(z=e==null?void 0:e.interactionConfig)==null?void 0:z.interactions)==null?void 0:G.some(Z=>Z.mode==="drillDown"||Z.mode==="drillToDetail"||Z.mode==="drillThrough"||Z.mode==="drillToURL"))??!1)?["─────────────────","Click to drill"]:[]}}}}},$=Nr(B,V),{options:P}=Um({cfg:{options:$},preferences:a,customCfg:s,cardType:n,card:e}),H=Nr(P,O);return{type:n,data:{labels:I,datasets:T},options:H,plugins:[n==="doughnut"?{id:"doughnutLabel",beforeDatasetsDraw:function(W,q,Y){var ce,ae,he,ye;const{ctx:U,data:z}=W;U.save();const G=W.getDatasetMeta(0).data[0].x,Z=W.getDatasetMeta(0).data[0].y,te=Bo(fl()),X=window.getComputedStyle(U.canvas).fontFamily;U.font=`1em ${X}`,U.fontWeight="bolder",U.fillStyle=te,U.textAlign="center",U.textBaseline="middle";const ne=z.datasets[0].data.reduce((Te,_e)=>Te+_e,0),se=Ks({number:Number(ne),decimalPlaces:((ce=a==null?void 0:a.numberAxisFormat)==null?void 0:ce.decimalPlaces)||0,useSuffix:!!((ae=a==null?void 0:a.numberAxisFormat)!=null&&ae.suffix),customSuffix:"",locale:((he=a==null?void 0:a.numberAxisFormat)==null?void 0:he.locale)||"",currency:((ye=a==null?void 0:a.numberAxisFormat)==null?void 0:ye.currency)||""});U.fillText(se,G,Z)}}:"",...R]}}if(n==="radar"){const C=gwe(r);return af({card:e,data:f,cfg:C,customCfg:s,cardType:n,preferences:a})}if(n==="bubble"||n==="scatter"){const{metricKeys:C}=Gn(f),j=Uhe(f,n),_=Ku(j,s),k=bwe(r,n,C),{options:E}=Um({cardType:n,cfg:k,preferences:a,customCfg:s,card:e});return{type:n,data:{datasets:_},options:E}}return af({card:e,data:f,cfg:r,customCfg:s,cardType:n,preferences:a})}function y1e({chart:e,elementIndex:t,datasetIndex:n,cardType:r,cfg:s,apply:o}){const i=J.getState().theme;if(!s)return;const a=i==="dark"?"rgb(238,238,238,0.2)":"rgb(238,238,238,0.8)";["bar","line","horizontalBar","bubble","scatter"].includes(r)&&w1e(e,t,s,o,a),["pie","doughnut","polarArea","funnel"].includes(r)&&S1e(e,t,s,o,a),["stackedBar","pyramid"].includes(r)&&v1e({chart:e,elementIndex:t,datasetIndex:n,cfg:s,apply:o,blurColor:a})}function v1e(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 w1e(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 S1e(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 C1e({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}=Gn(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=x1({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}=Gn(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 N1e(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,epe("--semaphor-background")),u})}));return{...e,data:{...e.data,datasets:o}}}return e}function NH(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}=bn({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 zi(e){const{tokenProps:t}=Ge(),n=J(h=>h.authToken)||e,r=ke(h=>h.selectedConnectionId),s=ke(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}=bn({queryKey:["connections"],queryFn:()=>qn(`${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 j1e(e){const{connections:t}=zi(e),n=ke(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 k1e(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 Af(e){if(ij.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 hD(e){var b;const{tokenProps:t}=Ge(),n=J(x=>x.authToken)||e,{hasSchemaSupport:r}=j1e(e),s=ke(x=>{var y;return(y=x.card.dataSource)==null?void 0:y.connectionId}),o=ke(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=ke(x=>{var y,v;return(v=(y=x.card.dataSource)==null?void 0:y.selectedEntities)==null?void 0:v.filter(w=>ij.includes(w.type))})||[],a=ke(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:ij.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=j_({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:()=>qn(`${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=Af(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||y_(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=k1e(m);return{columnGroups:m,columns:g,isLoading:f,hasError:h,error:p,refetch:()=>{d.forEach(x=>x.refetch())}}}function E1e(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 pD(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&&E1e(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 jH(e,t,n){var r;return!n||!((r=n.baseEntity)!=null&&r.name)||!n.joins?!1:e===t||e===Af(n.baseEntity)||t===Af(n.baseEntity)?!0:n.joins.some(s=>{const o=Af(s.source),i=Af(s.target);return o===e&&i===t||o===t&&i===e})}function _1e(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 pD(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(!jH(i,e.qualifiedEntityName,r))return{isValid:!1,showError:!0}}return{isValid:!0}}function kH(){ze.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})}function EH(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 M1e(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 D1e(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 _H(e,t){return`${e}-${t.qualifiedEntityName}-${t.name}-${Date.now()}`}function MH(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 T1e(e,t,n){const r=Xs(e.dataType);return n==="kpi"?r==="date"?"groupBy":"metrics":t.length===0||r==="number"?"metrics":r==="date"||r==="string"||r==="boolean"?"groupBy":"metrics"}function DH(e,t,n=[]){const r=_H(t,e),s=Xs(e.dataType),o=s==="date",i={id:r,name:e.name,dataType:e.dataType,label:y_(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=MH(e.label,a),u=D1e({...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 R1e(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 I1e(e){var i,a;const[t]=N.useState({id:"",title:"",type:"bar"}),{getCard:n}=Gt(),r=n(e),s=qb(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 qb(e){var O;const{onChartElementClicked:t}=Ge(),[n,r]=N.useState(0),s=J(D=>D.themeStyle),o=J(D=>D.filteringCards),i=J(D=>D.selectedSheetId),a=J(D=>D.selectedLensId),l=J(D=>D.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}=Gt(),{data:g,isLoading:b,isFetching:x,isError:y,isPending:v,queryKey:w,isFilteringCard:S,isSingleCardFrame:C,pagination:j,comparisonMetadata:_}=wa(e),{data:k}=NH(e);let E;E=N.useMemo(()=>{if(!(!(g!=null&&g.records)||!(g!=null&&g.records.length)))return fD({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 T=N.useRef({filteringCards:o});N.useEffect(()=>{e.connectionId&&!S&&(u.current=l)},[l,a,e.connectionId,S]),N.useEffect(()=>{var I;S&&(T.current.filteringCards=[...o||[]]),!S&&((I=T.current.filteringCards)==null?void 0:I.find(F=>F.id===e.id))&&C&&r(F=>F+1)},[S,C,e.id,o]);function R(D,I,F,B){var P;if(R1e(e))return;let V=!1;if(!(g!=null&&g.records))return;const $=C1e({card:e,data:g==null?void 0:g.records,datasetIndex:I,clickIndex:F,value:B});if(console.log("fieldValues",$),t==null||t(e,$),!!(((P=e==null?void 0:e.preferences)==null?void 0:P.onClickFilter)??[]).length){if(S){const H=e.id;p(H),m(e)}else{if(V=!0,!$)return;const H=[];$.forEach((L,A)=>{const W=d==null?void 0:d.find(Y=>Y.columnIndex===A);if(!W)return;const q={filterId:e.id+"-"+L.columnName+"-"+i,connectionId:e==null?void 0:e.connectionId,tableName:e.lastSelectedTable,name:L.columnName,expression:W.expression,valueType:x_($[W.columnIndex].columnValue),operation:"=",values:[$[W.columnIndex].columnValue]};H.push(q)}),h(H),f(e)}y1e({chart:D,elementIndex:F,datasetIndex:I,cardType:e.type,cfg:E,apply:V})}}return{isPending:v,isError:y,isLoading:b,isFetching:x,data:g,visualKey:n,handleDatapointClick:R,cfg:E,queryKey:w,pagination:j,comparisonMetadata:_}}function TH(e){var x;const{tokenProps:t}=Ge(),n=J(y=>y.authToken)||e,r=ke(y=>y.selectedConnectionId),s=ke(y=>y.selectedDatabaseName),o=ke(y=>y.selectedDatamodelId),i=ke(y=>y.selectedSchemaName),a=ke(y=>y.selectedTableName),{selectedConnection:l}=zi(),u=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:p,refetch:m}=bn({queryKey:["columns",r,s,o,i,a],queryFn:()=>qn(`${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 tg(e,t){const[n,r]=N.useState(e);return N.useEffect(()=>{const s=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(s)}},[e,t]),n}var A1e=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 RH=zc(A1e);function E0(e,t=RH){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 P1e(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 RH(e,t)}const O5={searchQuery:"",debouncedSearchQuery:"",selectedUsers:[],usersToRemove:[],usersToUpdate:[],selectedGroups:[],groupsToRemove:[],groupsToUpdate:[],selectedTab:"org",currentContext:"org-tab",currentMode:null,orgWideRole:"VIEWER",allTenantsRole:"VIEWER",tenantWideRole:"VIEWER",groupWideRole:"VIEWER",selectedTenant:"",message:""},cs=Nl()(Nb(e=>({...O5,actions:{setSearchQuery:t=>{e(n=>{n.searchQuery=t})},setDebouncedSearchQuery:t=>{e(n=>{n.debouncedSearchQuery=t})},setSelectedUsers:t=>{e(n=>{n.selectedUsers=t})},addSelectedUser:t=>{e(n=>{n.selectedUsers.some(s=>s.id===t.id)||n.selectedUsers.push(t)})},removeSelectedUser:t=>{e(n=>{n.selectedUsers=n.selectedUsers.filter(r=>r.id!==t)})},updateSelectedUserRole:(t,n)=>{e(r=>{const s=r.selectedUsers.find(o=>o.id===t);s&&(s.role=n)})},setUsersToRemove:t=>{e(n=>{n.usersToRemove=t})},addUserToRemove:t=>{e(n=>{n.usersToRemove.includes(t)||n.usersToRemove.push(t)})},removeUserFromRemove:t=>{e(n=>{n.usersToRemove=n.usersToRemove.filter(r=>r!==t)})},setUsersToUpdate:t=>{e(n=>{n.usersToUpdate=t})},addUserToUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t.id),n.usersToUpdate.push(t)})},removeUserFromUpdate:t=>{e(n=>{n.usersToUpdate=n.usersToUpdate.filter(r=>r.id!==t)})},setSelectedTenant:t=>{e(n=>{n.selectedTenant=t})},setSelectedTab:t=>{e(n=>{n.selectedTab=t})},setCurrentContext:t=>{e(n=>{n.currentContext=t})},setCurrentMode:t=>{e(n=>{n.currentMode=t})},setOrgWideRole:t=>{e(n=>{n.orgWideRole=t})},setAllTenantsRole:t=>{e(n=>{n.allTenantsRole=t})},setTenantWideRole:t=>{e(n=>{n.tenantWideRole=t})},setGroupWideRole:t=>{e(n=>{n.groupWideRole=t})},setSelectedGroups:t=>{e(n=>{n.selectedGroups=t})},addSelectedGroup:t=>{e(n=>{n.selectedGroups.some(s=>s.id===t.id)||n.selectedGroups.push(t)})},removeSelectedGroup:t=>{e(n=>{n.selectedGroups=n.selectedGroups.filter(r=>r.id!==t)})},updateSelectedGroupRole:(t,n)=>{e(r=>{const s=r.selectedGroups.find(o=>o.id===t);s&&(s.role=n)})},setGroupsToRemove:t=>{e(n=>{n.groupsToRemove=t})},addGroupToRemove:t=>{e(n=>{n.groupsToRemove.includes(t)||n.groupsToRemove.push(t)})},removeGroupFromRemove:t=>{e(n=>{n.groupsToRemove=n.groupsToRemove.filter(r=>r!==t)})},setGroupsToUpdate:t=>{e(n=>{n.groupsToUpdate=t})},addGroupToUpdate:t=>{e(n=>{const r=n.groupsToUpdate.findIndex(s=>s.id===t.id);r!==-1?n.groupsToUpdate[r]=t:n.groupsToUpdate.push(t)})},removeGroupFromUpdate:t=>{e(n=>{n.groupsToUpdate=n.groupsToUpdate.filter(r=>r.id!==t)})},setMessage:t=>{e(n=>{n.message=t})},validateShareData:t=>cB(t),resetShareState:()=>{e(t=>{Object.assign(t,O5)})},resetUserSelections:()=>{e(t=>{t.selectedUsers=[],t.usersToRemove=[],t.usersToUpdate=[]})},resetGroupSelections:()=>{e(t=>{t.selectedGroups=[],t.groupsToRemove=[],t.groupsToUpdate=[]})}}}))),IH=()=>cs(e=>e.searchQuery),vp=()=>cs(e=>e.selectedUsers),Yd=()=>cs(e=>e.usersToRemove),wp=()=>cs(e=>e.usersToUpdate),Yb=()=>cs(e=>e.selectedTenant),mD=()=>cs(e=>e.selectedTab),AH=()=>cs(e=>e.currentContext),qc=()=>cs(e=>e.currentMode),gD=()=>cs(e=>e.orgWideRole),bD=()=>cs(e=>e.allTenantsRole),T1=()=>cs(e=>e.tenantWideRole),PH=()=>cs(e=>e.groupWideRole),Sp=()=>cs(e=>e.selectedGroups),Cp=()=>cs(e=>e.groupsToRemove),Np=()=>cs(e=>e.groupsToUpdate),Yc=()=>cs(e=>e.actions),xD=()=>{const e=IH(),t=tg(e,300),n=Yc();return N.useEffect(()=>{n.setDebouncedSearchQuery(t)},[t,n]),{searchQuery:e,debouncedSearchQuery:t,setSearchQuery:n.setSearchQuery}};function qi(e,t){var n;return((n=t.find(r=>r.value===e))==null?void 0:n.label)||e}function O1e(e){return["POWER_USER","ADMIN","EDITOR"].includes(e)}function OH(e){return"tenantId"in e&&e.tenantId?"tenant":"organization"}function F1e(e,t,n){const r=OH(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 $1e({user:e}){return OH(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 L1e({user:e,userShare:t,usersToUpdate:n,currentUser:r,getRoleOptions:s,handleUpdateAccess:o}){if(!(t!=null&&t.role))return null;const i=O1e((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(vd,{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:qi(u,d)})}):c.jsx(Fe,{variant:"outline",className:"text-xs",children:"Unknown"})}function z1e({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(vc,{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(Zu,{className:"mr-1 h-3 w-3"}),"Will Share"]})]})}function B1e({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 V1e({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=qi(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=qi(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=qi(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=qi(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=qi(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=qi(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=qi(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=qi(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=qi(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 H1e({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 U1e({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:K("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(un,{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($1e,{user:e})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[r&&!n?c.jsx(vd,{currentRole:t==null?void 0:t.role,onRoleChange:m=>h(e.id,t.role,m),roleOptions:a,disabled:!1,allowDropdown:!0}):c.jsx(L1e,{user:e,userShare:t,usersToUpdate:u,currentUser:l,getRoleOptions:()=>a,handleUpdateAccess:h}),o&&!s&&c.jsx("div",{onClick:m=>m.stopPropagation(),children:c.jsx(vd,{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(z1e,{hasAccess:r,isUserRemoving:n,isSelected:o,hasAccessFromAPI:s}),c.jsx(B1e,{isUserRemoving:n,isSelected:o,hasAccess:r,isRemoving:!1,isSharing:!1})]})]})}function FH({existingShares:e,isInitialLoading:t,isSearching:n,getRoleOptions:r,allUsers:s=[],currentUser:o,handleUserToggle:i,handleUserRoleChange:a,handleRemoveAccess:l,handleUpdateAccess:u}){const d=vp(),f=Yd(),h=wp(),p=IH(),m=Yc(),g=i||(S=>{const C=d.some(_=>_.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(le,{className:"text-sm font-medium",children:["All Users (",(v??[]).length,")"]}),c.jsx(er,{children:c.jsxs(wn,{children:[c.jsx(Sn,{asChild:!0,children:c.jsx(oe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",children:c.jsx(gr,{className:"h-4 w-4"})})}),c.jsx(En,{className:"w-48 max-w-sm",children:c.jsx(V1e,{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(H1e,{isInitialLoading:t,isSearching:n,searchQuery:p,availableUsers:v||[]}),!t&&!n&&(v==null?void 0:v.length)>0&&v.map(S=>{const C=e?F1e(S,e,o):void 0,j=w.includes(S.id),_=!!C,k=_&&!j,E=d.some(O=>O.id===S.id),T=d.find(O=>O.id===S.id),R=r(S.type);return c.jsx(U1e,{user:S,userShare:C,isUserRemoving:j,hasAccess:k,hasAccessFromAPI:_,isSelected:E,selectedUser:T,roleOptions:R,currentUser:o,usersToUpdate:h,handleUserToggle:g,handleRemoveAccess:x,handleUpdateAccess:y,handleUserRoleChange:b},S.id)})]})]})}var yD="Radio",[W1e,$H]=Er(yD),[q1e,Y1e]=W1e(yD),LH=M.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]=M.useState(null),p=ft(t,b=>h(b)),m=M.useRef(!1),g=f?u||!!f.closest("form"):!0;return c.jsxs(q1e,{scope:n,checked:s,disabled:i,children:[c.jsx(Be.button,{type:"button",role:"radio","aria-checked":s,"data-state":VH(s),"data-disabled":i?"":void 0,disabled:i,value:a,...d,ref:p,onClick:je(e.onClick,b=>{s||l==null||l(),g&&(m.current=b.isPropagationStopped(),m.current||b.stopPropagation())})}),g&&c.jsx(G1e,{control:f,bubbles:!m.current,name:r,value:a,checked:s,required:o,disabled:i,form:u,style:{transform:"translateX(-100%)"}})]})});LH.displayName=yD;var zH="RadioIndicator",BH=M.forwardRef((e,t)=>{const{__scopeRadio:n,forceMount:r,...s}=e,o=Y1e(zH,n);return c.jsx(sr,{present:r||o.checked,children:c.jsx(Be.span,{"data-state":VH(o.checked),"data-disabled":o.disabled?"":void 0,...s,ref:t})})});BH.displayName=zH;var G1e=e=>{const{control:t,checked:n,bubbles:r=!0,...s}=e,o=M.useRef(null),i=f1(n),a=i1(t);return M.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 VH(e){return e?"checked":"unchecked"}var Z1e=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],vD="RadioGroup",[K1e]=Er(vD,[np,$H]),HH=np(),UH=$H(),[X1e,Q1e]=K1e(vD),WH=M.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=HH(n),m=$d(u),[g,b]=Fr({prop:o,defaultProp:s,onChange:f});return c.jsx(X1e,{scope:n,name:r,required:i,disabled:a,value:g,onValueChange:b,children:c.jsx(tM,{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})})})});WH.displayName=vD;var qH="RadioGroupItem",YH=M.forwardRef((e,t)=>{const{__scopeRadioGroup:n,disabled:r,...s}=e,o=Q1e(qH,n),i=o.disabled||r,a=HH(n),l=UH(n),u=M.useRef(null),d=ft(t,u),f=o.value===s.value,h=M.useRef(!1);return M.useEffect(()=>{const p=g=>{Z1e.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(nM,{asChild:!0,...a,focusable:!i,active:f,children:c.jsx(LH,{disabled:i,required:o.required,checked:f,...l,...s,name:o.name,ref:d,onCheck:()=>o.onValueChange(s.value),onKeyDown:je(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:je(s.onFocus,()=>{var p;h.current&&((p=u.current)==null||p.click())})})})});YH.displayName=qH;var J1e="RadioGroupIndicator",GH=M.forwardRef((e,t)=>{const{__scopeRadioGroup:n,...r}=e,s=UH(n);return c.jsx(BH,{...s,...r,ref:t})});GH.displayName=J1e;var ZH=WH,KH=YH,eSe=GH;const Na=M.forwardRef(({className:e,...t},n)=>c.jsx(ZH,{className:K("grid gap-2",e),...t,ref:n}));Na.displayName=ZH.displayName;const Cr=M.forwardRef(({className:e,...t},n)=>c.jsx(KH,{ref:n,className:K("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(eSe,{className:"flex items-center justify-center",children:c.jsx(q6,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Cr.displayName=KH.displayName;function wD({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(Na,{value:e,onValueChange:t,className:`grid grid-cols-${r.length} gap-4`,children:r.map(o=>c.jsxs("div",{children:[c.jsx(Cr,{value:o.value,id:o.value,className:"peer sr-only",disabled:o.disabled}),c.jsxs(le,{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(wc,{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 pN,SD="HoverCard",[XH]=Er(SD,[Ma]),R1=Ma(),[tSe,I1]=XH(SD),QH=e=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:s,onOpenChange:o,openDelay:i=700,closeDelay:a=300}=e,l=R1(t),u=M.useRef(0),d=M.useRef(0),f=M.useRef(!1),h=M.useRef(!1),[p=!1,m]=Fr({prop:r,defaultProp:s,onChange:o}),g=M.useCallback(()=>{clearTimeout(d.current),u.current=window.setTimeout(()=>m(!0),i)},[i,m]),b=M.useCallback(()=>{clearTimeout(u.current),!f.current&&!h.current&&(d.current=window.setTimeout(()=>m(!1),a))},[a,m]),x=M.useCallback(()=>m(!1),[m]);return M.useEffect(()=>()=>{clearTimeout(u.current),clearTimeout(d.current)},[]),c.jsx(tSe,{scope:t,open:p,onOpenChange:m,onOpen:g,onClose:b,onDismiss:x,hasSelectionRef:f,isPointerDownOnContentRef:h,children:c.jsx(ep,{...l,children:n})})};QH.displayName=SD;var JH="HoverCardTrigger",eU=M.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=I1(JH,n),o=R1(n);return c.jsx(tp,{asChild:!0,...o,children:c.jsx(Be.a,{"data-state":s.open?"open":"closed",...r,ref:t,onPointerEnter:je(e.onPointerEnter,Lv(s.onOpen)),onPointerLeave:je(e.onPointerLeave,Lv(s.onClose)),onFocus:je(e.onFocus,s.onOpen),onBlur:je(e.onBlur,s.onClose),onTouchStart:je(e.onTouchStart,i=>i.preventDefault())})})});eU.displayName=JH;var CD="HoverCardPortal",[nSe,rSe]=XH(CD,{forceMount:void 0}),tU=e=>{const{__scopeHoverCard:t,forceMount:n,children:r,container:s}=e,o=I1(CD,t);return c.jsx(nSe,{scope:t,forceMount:n,children:c.jsx(sr,{present:n||o.open,children:c.jsx(zd,{asChild:!0,container:s,children:r})})})};tU.displayName=CD;var $v="HoverCardContent",nU=M.forwardRef((e,t)=>{const n=rSe($v,e.__scopeHoverCard),{forceMount:r=n.forceMount,...s}=e,o=I1($v,e.__scopeHoverCard);return c.jsx(sr,{present:r||o.open,children:c.jsx(sSe,{"data-state":o.open?"open":"closed",...s,onPointerEnter:je(e.onPointerEnter,Lv(o.onOpen)),onPointerLeave:je(e.onPointerLeave,Lv(o.onClose)),ref:t})})});nU.displayName=$v;var sSe=M.forwardRef((e,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:o,onInteractOutside:i,...a}=e,l=I1($v,n),u=R1(n),d=M.useRef(null),f=ft(t,d),[h,p]=M.useState(!1);return M.useEffect(()=>{if(h){const m=document.body;return pN=m.style.userSelect||m.style.webkitUserSelect,m.style.userSelect="none",m.style.webkitUserSelect="none",()=>{m.style.userSelect=pN,m.style.webkitUserSelect=pN}}},[h]),M.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]),M.useEffect(()=>{d.current&&aSe(d.current).forEach(g=>g.setAttribute("tabindex","-1"))}),c.jsx(Ld,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:i,onEscapeKeyDown:r,onPointerDownOutside:s,onFocusOutside:je(o,m=>{m.preventDefault()}),onDismiss:l.onDismiss,children:c.jsx(Rb,{...u,...a,onPointerDown:je(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)"}})})}),oSe="HoverCardArrow",iSe=M.forwardRef((e,t)=>{const{__scopeHoverCard:n,...r}=e,s=R1(n);return c.jsx(Ib,{...s,...r,ref:t})});iSe.displayName=oSe;function Lv(e){return t=>t.pointerType==="touch"?void 0:e()}function aSe(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 lSe=QH,cSe=eU,rU=nU;const jp=lSe,kp=cSe,Gd=M.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},s)=>c.jsx(rU,{ref:s,align:t,sideOffset:n,className:K("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}));Gd.displayName=rU.displayName;const mi=()=>[{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 uSe({currentUser:e,currentShare:t,isSharing:n,onUpdateAccess:r,allUsersToUpdate:s=null,allUsersToRemove:o=!1,isUpdating:i=!1,isRemoving:a=!1}){const l=qc(),u=mi().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(vc,{className:"h-4 w-4"});case"EDITOR":return c.jsx(Jw,{className:"h-4 w-4"});case"CONTRIBUTOR":return c.jsx(gie,{className:"h-4 w-4"});default:return c.jsx(vc,{className:"h-4 w-4"})}},x=y=>{r(d,y)};return c.jsx("div",{className:"space-y-4",children:c.jsxs(xo,{className:K("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(Ei,{children:[c.jsxs(_i,{className:"flex items-center gap-2 text-base",children:[c.jsx(os,{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(D6,{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(Mi,{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(jp,{children:[c.jsx(kp,{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(gr,{className:"h-3 w-3"})})}),c.jsx(Gd,{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 sU({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(uSe,{currentUser:e,currentShare:f,isSharing:n,isUpdating:r,isRemoving:s,onUpdateAccess:p,onRemoveAccess:m,allUsersToUpdate:h,allUsersToRemove:l})}const dSe=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 qn(s,t,r)};function ND(e={}){var o,i,a;const{authToken:t,tokenProps:n}=Ge(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=bn({queryKey:["unified-users",e],queryFn:()=>dSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(l,u)=>u instanceof Error&&u.message.includes("401")||u instanceof Error&&u.message.includes("403")?!1:l<2,retryDelay:l=>Math.min(1e3*2**l,3e4)});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 Oh(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=$t.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}=ND(i),d=dde(r,n);return{allUsers:a,isLoadingUsers:l,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function fSe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var L,A;const a=mD(),l=Yb(),{searchQuery:u,setSearchQuery:d,debouncedSearchQuery:f}=xD(),h=vp(),p=Yd(),m=wp(),g=qc(),b=gD(),x=Yc(),[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:_}=Oh({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,U;const q=W;if(v(q),r==null||r(q),x.setCurrentContext("org-tab"),q==="specific_users")x.setCurrentMode("specificOrgUsers");else if(q==="all_users"){x.setCurrentMode("allOrgUsers");const z=(U=(Y=j==null?void 0:j.shares)==null?void 0:Y.orgUsersOnly)==null?void 0:U[0];z&&z.role!==void 0&&x.setOrgWideRole(z.role)}},E=C.filter(W=>W.name.toLowerCase().includes(u.toLowerCase())||W.email.toLowerCase().includes(u.toLowerCase())),T=C.filter(W=>h.some(q=>q.id===W.id)),R=W=>{var z,G;const q=h.some(Z=>Z.id===W),Y=p.includes(W),U=(G=(z=j==null?void 0:j.shares)==null?void 0:z.specificOrgUsers)==null?void 0:G.some(Z=>Z.orgUserId===W);q?x.removeSelectedUser(W):Y?x.removeUserFromRemove(W):U||x.addSelectedUser({id:W,role:"VIEWER"})},O=(W,q)=>{x.updateSelectedUserRole(W,q)},D=W=>{x.addUserToRemove(W),x.removeSelectedUser(W)},I=W=>{x.removeUserFromRemove(W)},F=W=>{x.removeUserFromUpdate(W)},B=(W,q)=>{x.setOrgWideRole(q)},V=()=>{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=_,H=!1;return n?c.jsxs(c.Fragment,{children:[c.jsx(wD,{shareType:y,onShareTypeChange:k,currentUser:n,options:[{value:"specific_users",label:"Specific Org User",description:"Choose individual users to share with",icon:c.jsx(wc,{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(os,{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(fv,{value:u,onChange:d}),c.jsx(B7,{selectedUsers:h,selectedUserObjects:T,onRemove:R,onRoleChange:O,getRoleOptions:mi}),c.jsx(V7,{usersToRemove:p,allUsers:E,onRemove:I}),c.jsx(H7,{usersToUpdate:m,allUsers:E,onRemove:F,getRoleOptions:mi}),c.jsx(FH,{existingShares:j,isInitialLoading:P,isSearching:H,resource:e,onShare:()=>{},getRoleOptions:mi,allUsers:E,currentUser:n,handleUserToggle:R,handleUserRoleChange:O,handleRemoveAccess:D,handleUpdateAccess:(W,q,Y)=>{x.addUserToUpdate({id:W,currentRole:q,newRole:Y})}})]}):c.jsx("div",{className:"mt-3",children:c.jsx(sU,{currentUser:n,currentShare:$,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:B,onRemoveAccess:V,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 hSe(e){switch(e){case"ORG_GROUP":return"Organization Group";case"TENANT_GROUP":return"Tenant Group";default:return"Group"}}function pSe(e){switch(e){case"ORG_GROUP":return"text-blue-600";case"TENANT_GROUP":return"text-green-600";default:return"text-gray-600"}}function oU({groups:e,existingGroupShares:t,isLoading:n,resource:r,getRoleOptions:s,currentUser:o,handleGroupToggle:i,handleGroupRoleChange:a,handleRemoveAccess:l,handleUpdateAccess:u}){const d=Sp(),f=Cp(),h=Np(),p=Yc(),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(le,{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(_=>_.id===g.id);C=(j==null?void 0:j.role)||"VIEWER"}else v&&(C=v.newRole);return c.jsxs("div",{className:K("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(un,{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(pd,{className:"h-3 w-3 text-blue-600"}):c.jsx(os,{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:K("text-xs",pSe(g.type)),children:hSe(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(vd,{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(vd,{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 iU({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(pd,{className:"h-4 w-4 text-blue-600"}):c.jsx(os,{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(vd,{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 mSe=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 qn(s,t,r)},gSe=async(e,t,n)=>{const r=`${e}/management/v1/groups/${n}/members`;return await qn(r,t)};function jD(e={}){var o,i,a;const{authToken:t,tokenProps:n}=Ge(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),s=bn({queryKey:["groups",e],queryFn:()=>mSe(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 bSe(e){const{authToken:t,tokenProps:n}=Ge(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId);return bn({queryKey:["group-members",e],queryFn:()=>gSe(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r&&!!e,retry:1,staleTime:6e4})}function aU(e,t){const{tokenProps:n}=Ge(),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)),jD(r)}function Pk(e,[t,n]){return Math.min(n,Math.max(t,e))}var lU=M.forwardRef((e,t)=>{const{children:n,...r}=e,s=M.Children.toArray(n),o=s.find(ySe);if(o){const i=o.props.children,a=s.map(l=>l===o?M.Children.count(i)>1?M.Children.only(null):M.isValidElement(i)?i.props.children:null:l);return c.jsx(Ok,{...r,ref:t,children:M.isValidElement(i)?M.cloneElement(i,void 0,a):null})}return c.jsx(Ok,{...r,ref:t,children:n})});lU.displayName="Slot";var Ok=M.forwardRef((e,t)=>{const{children:n,...r}=e;if(M.isValidElement(n)){const s=wSe(n),o=vSe(r,n.props);return n.type!==M.Fragment&&(o.ref=t?js(t,s):s),M.cloneElement(n,o)}return M.Children.count(n)>1?M.Children.only(null):null});Ok.displayName="SlotClone";var xSe=({children:e})=>c.jsx(c.Fragment,{children:e});function ySe(e){return M.isValidElement(e)&&e.type===xSe}function vSe(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 wSe(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 SSe=[" ","Enter","ArrowUp","ArrowDown"],CSe=[" ","Enter"],Gb="Select",[A1,P1,NSe]=t1(Gb),[Ep]=Er(Gb,[NSe,Ma]),O1=Ma(),[jSe,Gc]=Ep(Gb),[kSe,ESe]=Ep(Gb),cU=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=O1(t),[b,x]=M.useState(null),[y,v]=M.useState(null),[w,S]=M.useState(!1),C=$d(u),[j=!1,_]=Fr({prop:r,defaultProp:s,onChange:o}),[k,E]=Fr({prop:i,defaultProp:a,onChange:l}),T=M.useRef(null),R=b?m||!!b.closest("form"):!0,[O,D]=M.useState(new Set),I=Array.from(O).map(F=>F.props.value).join(";");return c.jsx(ep,{...g,children:c.jsxs(jSe,{required:p,scope:t,trigger:b,onTriggerChange:x,valueNode:y,onValueNodeChange:v,valueNodeHasChildren:w,onValueNodeHasChildrenChange:S,contentId:rr(),value:k,onValueChange:E,open:j,onOpenChange:_,dir:C,triggerPointerDownPosRef:T,disabled:h,children:[c.jsx(A1.Provider,{scope:t,children:c.jsx(kSe,{scope:e.__scopeSelect,onNativeOptionAdd:M.useCallback(F=>{D(B=>new Set(B).add(F))},[]),onNativeOptionRemove:M.useCallback(F=>{D(B=>{const V=new Set(B);return V.delete(F),V})},[]),children:n})}),R?c.jsxs(PU,{"aria-hidden":!0,required:p,tabIndex:-1,name:d,autoComplete:f,value:k,onChange:F=>E(F.target.value),disabled:h,form:m,children:[k===void 0?c.jsx("option",{value:""}):null,Array.from(O)]},I):null]})})};cU.displayName=Gb;var uU="SelectTrigger",dU=M.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...s}=e,o=O1(n),i=Gc(uU,n),a=i.disabled||r,l=ft(t,i.onTriggerChange),u=P1(n),d=M.useRef("touch"),[f,h,p]=OU(g=>{const b=u().filter(v=>!v.disabled),x=b.find(v=>v.value===i.value),y=FU(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(tp,{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":AU(i.value)?"":void 0,...s,ref:l,onClick:je(s.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&m(g)}),onPointerDown:je(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:je(s.onKeyDown,g=>{const b=f.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&h(g.key),!(b&&g.key===" ")&&SSe.includes(g.key)&&(m(),g.preventDefault())})})})});dU.displayName=uU;var fU="SelectValue",hU=M.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,children:o,placeholder:i="",...a}=e,l=Gc(fU,n),{onValueNodeHasChildrenChange:u}=l,d=o!==void 0,f=ft(t,l.onValueNodeChange);return $r(()=>{u(d)},[u,d]),c.jsx(Be.span,{...a,ref:f,style:{pointerEvents:"none"},children:AU(l.value)?c.jsx(c.Fragment,{children:i}):o})});hU.displayName=fU;var _Se="SelectIcon",pU=M.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...s}=e;return c.jsx(Be.span,{"aria-hidden":!0,...s,ref:t,children:r||"▼"})});pU.displayName=_Se;var MSe="SelectPortal",mU=e=>c.jsx(zd,{asChild:!0,...e});mU.displayName=MSe;var _d="SelectContent",gU=M.forwardRef((e,t)=>{const n=Gc(_d,e.__scopeSelect),[r,s]=M.useState();if($r(()=>{s(new DocumentFragment)},[]),!n.open){const o=r;return o?yc.createPortal(c.jsx(bU,{scope:e.__scopeSelect,children:c.jsx(A1.Slot,{scope:e.__scopeSelect,children:c.jsx("div",{children:e.children})})}),o):null}return c.jsx(xU,{...e,ref:t})});gU.displayName=_d;var oi=10,[bU,Zc]=Ep(_d),DSe="SelectContentImpl",xU=M.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=Gc(_d,n),[v,w]=M.useState(null),[S,C]=M.useState(null),j=ft(t,U=>w(U)),[_,k]=M.useState(null),[E,T]=M.useState(null),R=P1(n),[O,D]=M.useState(!1),I=M.useRef(!1);M.useEffect(()=>{if(v)return Ab(v)},[v]),n1();const F=M.useCallback(U=>{const[z,...G]=R().map(X=>X.ref.current),[Z]=G.slice(-1),te=document.activeElement;for(const X of U)if(X===te||(X==null||X.scrollIntoView({block:"nearest"}),X===z&&S&&(S.scrollTop=0),X===Z&&S&&(S.scrollTop=S.scrollHeight),X==null||X.focus(),document.activeElement!==te))return},[R,S]),B=M.useCallback(()=>F([_,v]),[F,_,v]);M.useEffect(()=>{O&&B()},[O,B]);const{onOpenChange:V,triggerPointerDownPosRef:$}=y;M.useEffect(()=>{if(v){let U={x:0,y:0};const z=Z=>{var te,X;U={x:Math.abs(Math.round(Z.pageX)-(((te=$.current)==null?void 0:te.x)??0)),y:Math.abs(Math.round(Z.pageY)-(((X=$.current)==null?void 0:X.y)??0))}},G=Z=>{U.x<=10&&U.y<=10?Z.preventDefault():v.contains(Z.target)||V(!1),document.removeEventListener("pointermove",z),$.current=null};return $.current!==null&&(document.addEventListener("pointermove",z),document.addEventListener("pointerup",G,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",z),document.removeEventListener("pointerup",G,{capture:!0})}}},[v,V,$]),M.useEffect(()=>{const U=()=>V(!1);return window.addEventListener("blur",U),window.addEventListener("resize",U),()=>{window.removeEventListener("blur",U),window.removeEventListener("resize",U)}},[V]);const[P,H]=OU(U=>{const z=R().filter(te=>!te.disabled),G=z.find(te=>te.ref.current===document.activeElement),Z=FU(z,U,G);Z&&setTimeout(()=>Z.ref.current.focus())}),L=M.useCallback((U,z,G)=>{const Z=!I.current&&!G;(y.value!==void 0&&y.value===z||Z)&&(k(U),Z&&(I.current=!0))},[y.value]),A=M.useCallback(()=>v==null?void 0:v.focus(),[v]),W=M.useCallback((U,z,G)=>{const Z=!I.current&&!G;(y.value!==void 0&&y.value===z||Z)&&T(U)},[y.value]),q=r==="popper"?Fk:yU,Y=q===Fk?{side:a,sideOffset:l,align:u,alignOffset:d,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:m,hideWhenDetached:g,avoidCollisions:b}:{};return c.jsx(bU,{scope:n,content:v,viewport:S,onViewportChange:C,itemRefCallback:L,selectedItem:_,onItemLeave:A,itemTextRefCallback:W,focusSelectedItem:B,selectedItemText:E,position:r,isPositioned:O,searchRef:P,children:c.jsx(rp,{as:lU,allowPinchZoom:!0,children:c.jsx(Xh,{asChild:!0,trapped:y.open,onMountAutoFocus:U=>{U.preventDefault()},onUnmountAutoFocus:je(s,U=>{var z;(z=y.trigger)==null||z.focus({preventScroll:!0}),U.preventDefault()}),children:c.jsx(Ld,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:U=>U.preventDefault(),onDismiss:()=>y.onOpenChange(!1),children:c.jsx(q,{role:"listbox",id:y.contentId,"data-state":y.open?"open":"closed",dir:y.dir,onContextMenu:U=>U.preventDefault(),...x,...Y,onPlaced:()=>D(!0),ref:j,style:{display:"flex",flexDirection:"column",outline:"none",...x.style},onKeyDown:je(x.onKeyDown,U=>{const z=U.ctrlKey||U.altKey||U.metaKey;if(U.key==="Tab"&&U.preventDefault(),!z&&U.key.length===1&&H(U.key),["ArrowUp","ArrowDown","Home","End"].includes(U.key)){let Z=R().filter(te=>!te.disabled).map(te=>te.ref.current);if(["ArrowUp","End"].includes(U.key)&&(Z=Z.slice().reverse()),["ArrowUp","ArrowDown"].includes(U.key)){const te=U.target,X=Z.indexOf(te);Z=Z.slice(X+1)}setTimeout(()=>F(Z)),U.preventDefault()}})})})})})})});xU.displayName=DSe;var TSe="SelectItemAlignedPosition",yU=M.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...s}=e,o=Gc(_d,n),i=Zc(_d,n),[a,l]=M.useState(null),[u,d]=M.useState(null),f=ft(t,j=>d(j)),h=P1(n),p=M.useRef(!1),m=M.useRef(!0),{viewport:g,selectedItem:b,selectedItemText:x,focusSelectedItem:y}=i,v=M.useCallback(()=>{if(o.trigger&&o.valueNode&&a&&u&&g&&b&&x){const j=o.trigger.getBoundingClientRect(),_=u.getBoundingClientRect(),k=o.valueNode.getBoundingClientRect(),E=x.getBoundingClientRect();if(o.dir!=="rtl"){const te=E.left-_.left,X=k.left-te,ne=j.left-X,se=j.width+ne,ce=Math.max(se,_.width),ae=window.innerWidth-oi,he=Pk(X,[oi,Math.max(oi,ae-ce)]);a.style.minWidth=se+"px",a.style.left=he+"px"}else{const te=_.right-E.right,X=window.innerWidth-k.right-te,ne=window.innerWidth-j.right-X,se=j.width+ne,ce=Math.max(se,_.width),ae=window.innerWidth-oi,he=Pk(X,[oi,Math.max(oi,ae-ce)]);a.style.minWidth=se+"px",a.style.right=he+"px"}const T=h(),R=window.innerHeight-oi*2,O=g.scrollHeight,D=window.getComputedStyle(u),I=parseInt(D.borderTopWidth,10),F=parseInt(D.paddingTop,10),B=parseInt(D.borderBottomWidth,10),V=parseInt(D.paddingBottom,10),$=I+F+O+V+B,P=Math.min(b.offsetHeight*5,$),H=window.getComputedStyle(g),L=parseInt(H.paddingTop,10),A=parseInt(H.paddingBottom,10),W=j.top+j.height/2-oi,q=R-W,Y=b.offsetHeight/2,U=b.offsetTop+Y,z=I+F+U,G=$-z;if(z<=W){const te=T.length>0&&b===T[T.length-1].ref.current;a.style.bottom="0px";const X=u.clientHeight-g.offsetTop-g.offsetHeight,ne=Math.max(q,Y+(te?A:0)+X+B),se=z+ne;a.style.height=se+"px"}else{const te=T.length>0&&b===T[0].ref.current;a.style.top="0px";const ne=Math.max(W,I+g.offsetTop+(te?L:0)+Y)+G;a.style.height=ne+"px",g.scrollTop=z-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]);$r(()=>v(),[v]);const[w,S]=M.useState();$r(()=>{u&&S(window.getComputedStyle(u).zIndex)},[u]);const C=M.useCallback(j=>{j&&m.current===!0&&(v(),y==null||y(),m.current=!1)},[v,y]);return c.jsx(ISe,{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}})})})});yU.displayName=TSe;var RSe="SelectPopperPosition",Fk=M.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:s=oi,...o}=e,i=O1(n);return c.jsx(Rb,{...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)"}})});Fk.displayName=RSe;var[ISe,kD]=Ep(_d,{}),$k="SelectViewport",vU=M.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...s}=e,o=Zc($k,n),i=kD($k,n),a=ft(t,o.onViewportChange),l=M.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(A1.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:je(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})})})]})});vU.displayName=$k;var wU="SelectGroup",[ASe,PSe]=Ep(wU),SU=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=rr();return c.jsx(ASe,{scope:n,id:s,children:c.jsx(Be.div,{role:"group","aria-labelledby":s,...r,ref:t})})});SU.displayName=wU;var CU="SelectLabel",NU=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=PSe(CU,n);return c.jsx(Be.div,{id:s.id,...r,ref:t})});NU.displayName=CU;var zv="SelectItem",[OSe,jU]=Ep(zv),kU=M.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:s=!1,textValue:o,...i}=e,a=Gc(zv,n),l=Zc(zv,n),u=a.value===r,[d,f]=M.useState(o??""),[h,p]=M.useState(!1),m=ft(t,y=>{var v;return(v=l.itemRefCallback)==null?void 0:v.call(l,y,r,s)}),g=rr(),b=M.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(OSe,{scope:n,value:r,disabled:s,textId:g,isSelected:u,onItemTextChange:M.useCallback(y=>{f(v=>v||((y==null?void 0:y.textContent)??"").trim())},[]),children:c.jsx(A1.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:je(i.onFocus,()=>p(!0)),onBlur:je(i.onBlur,()=>p(!1)),onClick:je(i.onClick,()=>{b.current!=="mouse"&&x()}),onPointerUp:je(i.onPointerUp,()=>{b.current==="mouse"&&x()}),onPointerDown:je(i.onPointerDown,y=>{b.current=y.pointerType}),onPointerMove:je(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:je(i.onPointerLeave,y=>{var v;y.currentTarget===document.activeElement&&((v=l.onItemLeave)==null||v.call(l))}),onKeyDown:je(i.onKeyDown,y=>{var w;((w=l.searchRef)==null?void 0:w.current)!==""&&y.key===" "||(CSe.includes(y.key)&&x(),y.key===" "&&y.preventDefault())})})})})});kU.displayName=zv;var Mm="SelectItemText",EU=M.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:s,...o}=e,i=Gc(Mm,n),a=Zc(Mm,n),l=jU(Mm,n),u=ESe(Mm,n),[d,f]=M.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=M.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 $r(()=>(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?yc.createPortal(o.children,i.valueNode):null]})});EU.displayName=Mm;var _U="SelectItemIndicator",MU=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return jU(_U,n).isSelected?c.jsx(Be.span,{"aria-hidden":!0,...r,ref:t}):null});MU.displayName=_U;var Lk="SelectScrollUpButton",DU=M.forwardRef((e,t)=>{const n=Zc(Lk,e.__scopeSelect),r=kD(Lk,e.__scopeSelect),[s,o]=M.useState(!1),i=ft(t,r.onScrollButtonChange);return $r(()=>{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(RU,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});DU.displayName=Lk;var zk="SelectScrollDownButton",TU=M.forwardRef((e,t)=>{const n=Zc(zk,e.__scopeSelect),r=kD(zk,e.__scopeSelect),[s,o]=M.useState(!1),i=ft(t,r.onScrollButtonChange);return $r(()=>{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(RU,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});TU.displayName=zk;var RU=M.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...s}=e,o=Zc("SelectScrollButton",n),i=M.useRef(null),a=P1(n),l=M.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return M.useEffect(()=>()=>l(),[l]),$r(()=>{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:je(s.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:je(s.onPointerMove,()=>{var u;(u=o.onItemLeave)==null||u.call(o),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:je(s.onPointerLeave,()=>{l()})})}),FSe="SelectSeparator",IU=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c.jsx(Be.div,{"aria-hidden":!0,...r,ref:t})});IU.displayName=FSe;var Bk="SelectArrow",$Se=M.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,s=O1(n),o=Gc(Bk,n),i=Zc(Bk,n);return o.open&&i.position==="popper"?c.jsx(Ib,{...s,...r,ref:t}):null});$Se.displayName=Bk;function AU(e){return e===""||e===void 0}var PU=M.forwardRef((e,t)=>{const{value:n,...r}=e,s=M.useRef(null),o=ft(t,s),i=f1(n);return M.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(EM,{asChild:!0,children:c.jsx("select",{...r,ref:o,defaultValue:n})})});PU.displayName="BubbleSelect";function OU(e){const t=br(e),n=M.useRef(""),r=M.useRef(0),s=M.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=M.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return M.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,s,o]}function FU(e,t,n){const s=t.length>1&&Array.from(t).every(u=>u===t[0])?t[0]:t,o=n?e.indexOf(n):-1;let i=LSe(e,Math.max(o,0));s.length===1&&(i=i.filter(u=>u!==n));const l=i.find(u=>u.textValue.toLowerCase().startsWith(s.toLowerCase()));return l!==n?l:void 0}function LSe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var zSe=cU,$U=dU,BSe=hU,VSe=pU,HSe=mU,LU=gU,USe=vU,WSe=SU,zU=NU,BU=kU,qSe=EU,YSe=MU,VU=DU,HU=TU,UU=IU;const rt=zSe,WU=WSe,lt=BSe,Je=M.forwardRef(({className:e,children:t,...n},r)=>c.jsxs($U,{ref:r,className:K("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-0 focus:ring-ring focus:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,c.jsx(VSe,{asChild:!0,children:c.jsx(Gs,{className:"h-4 w-4 opacity-50"})})]}));Je.displayName=$U.displayName;const qU=M.forwardRef(({className:e,...t},n)=>c.jsx(VU,{ref:n,className:K("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Vm,{className:"h-4 w-4"})}));qU.displayName=VU.displayName;const YU=M.forwardRef(({className:e,...t},n)=>c.jsx(HU,{ref:n,className:K("flex cursor-default items-center justify-center py-1",e),...t,children:c.jsx(Gs,{className:"h-4 w-4"})}));YU.displayName=HU.displayName;const et=M.forwardRef(({className:e,children:t,position:n="popper",...r},s)=>c.jsx(HSe,{children:c.jsx(Da,{children:c.jsxs(LU,{ref:s,className:K("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(qU,{}),c.jsx(USe,{className:K("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),c.jsx(YU,{})]})})}));et.displayName=LU.displayName;const ED=M.forwardRef(({className:e,...t},n)=>c.jsx(zU,{ref:n,className:K("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));ED.displayName=zU.displayName;const pe=M.forwardRef(({className:e,children:t,...n},r)=>c.jsxs(BU,{ref:r,className:K("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[c.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:c.jsx(YSe,{children:c.jsx(Rr,{className:"h-4 w-4"})})}),c.jsx(qSe,{children:t})]}));pe.displayName=BU.displayName;const GSe=M.forwardRef(({className:e,...t},n)=>c.jsx(UU,{ref:n,className:K("-mx-1 my-1 h-px bg-muted",e),...t}));GSe.displayName=UU.displayName;function F5({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var _e;const{searchQuery:a,debouncedSearchQuery:l,setSearchQuery:u}=xD(),d=vp(),f=Yd(),h=wp(),p=Sp(),m=Cp(),g=Np(),b=qc(),x=T1(),y=bD(),v=Yb(),w=Yc(),{data:S,isLoading:C}=r9({enabled:(n==null?void 0:n.type)==="organization"}),{groups:j,isLoading:_}=aU("tenant",(n==null?void 0:n.tenantId)||v),[k,E]=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 T=de=>{var Oe,mt,be,re;E(de);let Re;if(de==="specific_tenant_users"?Re="specific_users":de==="all_tenant_users"||de==="all_tenants"?Re="all_users":de==="groups"?Re="groups":Re="specific_users",r==null||r(Re),de==="groups"?(w.setCurrentContext("group-share"),w.setCurrentMode("specificGroups")):(n==null?void 0:n.type)==="tenant"?(w.setCurrentContext("tenant-dialog"),de==="specific_tenant_users"?w.setCurrentMode("specificTenantUsers"):de==="all_tenant_users"&&(w.setCurrentMode("allTenantUsers"),n!=null&&n.tenantId&&w.setSelectedTenant(n.tenantId))):(w.setCurrentContext("tenant-tab"),de==="specific_tenant_users"?w.setCurrentMode("specificTenantUsers"):de==="all_tenant_users"?w.setCurrentMode("allTenantUsers"):de==="all_tenants"&&w.setCurrentMode("allTenants")),de==="all_tenant_users"){const ue=(mt=(Oe=D==null?void 0:D.shares)==null?void 0:Oe.tenantWide)==null?void 0:mt[0];ue&&ue.role!==void 0&&w.setTenantWideRole(ue.role)}else if(de==="all_tenants"){const ue=(re=(be=D==null?void 0:D.shares)==null?void 0:be.allTenantsOnly)==null?void 0:re[0];ue&&ue.role!==void 0&&w.setAllTenantsRole(ue.role)}},R=de=>{w.setSelectedTenant(de)},{allUsers:O,existingShares:D,isLoadingUsers:I,isErrorLoadingUsers:F,isLoadingShares:B,isErrorLoadingShares:V}=Oh({debouncedSearchQuery:l,resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant",tenantId:(n==null?void 0:n.type)==="tenant"?n.tenantId:v}),$=de=>{var be,re;const Re=d.some(ue=>ue.id===de),Oe=f.includes(de),mt=(re=(be=D==null?void 0:D.shares)==null?void 0:be.specificTenantUsers)==null?void 0:re.some(ue=>ue.tenantUserId===de);Re?w.removeSelectedUser(de):Oe?w.removeUserFromRemove(de):mt||w.addSelectedUser({id:de,role:"VIEWER"})},P=(de,Re)=>{w.updateSelectedUserRole(de,Re)},H=de=>{w.addUserToRemove(de),w.removeSelectedUser(de)},L=de=>{w.removeUserFromRemove(de)},A=de=>{w.removeUserFromUpdate(de)},W=(de,Re,Oe)=>{w.addUserToUpdate({id:de,currentRole:Re,newRole:Oe})},q=(de,Re)=>{k==="all_tenant_users"?w.setTenantWideRole(Re):k==="all_tenants"&&w.setAllTenantsRole(Re)},Y=()=>{k==="all_tenant_users"?w.setTenantWideRole("VIEWER"):k==="all_tenants"&&w.setAllTenantsRole("VIEWER")},z=(()=>{var de,Re,Oe,mt;return b==="allTenants"?(Re=(de=D==null?void 0:D.shares)==null?void 0:de.allTenantsOnly)==null?void 0:Re[0]:b==="allTenantUsers"?(mt=(Oe=D==null?void 0:D.shares)==null?void 0:Oe.tenantWide)==null?void 0:mt[0]:null})();N.useEffect(()=>{var de,Re,Oe,mt;if(k==="all_tenant_users"){const be=(Re=(de=D==null?void 0:D.shares)==null?void 0:de.tenantWide)==null?void 0:Re[0];be&&be.role!==void 0&&w.setTenantWideRole(be.role)}else if(k==="all_tenants"){const be=(mt=(Oe=D==null?void 0:D.shares)==null?void 0:Oe.allTenantsOnly)==null?void 0:mt[0];be&&be.role!==void 0&&w.setAllTenantsRole(be.role)}},[k,D,w]);const G=O.filter(de=>d.some(Re=>Re.id===de.id)),Z=de=>{const Re=p.some(be=>be.id===de),Oe=m.includes(de),mt=ae==null?void 0:ae.some(be=>be.groupId===de);Re?w.removeSelectedGroup(de):Oe?w.removeGroupFromRemove(de):mt||w.addSelectedGroup({id:de,role:"VIEWER"})},te=(de,Re)=>{w.updateSelectedGroupRole(de,Re)},X=de=>{w.addGroupToRemove(de),w.removeSelectedGroup(de)},ne=(de,Re,Oe)=>{w.addGroupToUpdate({id:de,currentRole:Re,newRole:Oe})},se=j.filter(de=>p.some(Re=>Re.id===de.id)),ce=N.useMemo(()=>k!=="groups"?[]:j.filter(de=>de.type!=="TENANT_GROUP"?!1:de.name.toLowerCase().includes(a.toLowerCase())||de.description&&de.description.toLowerCase().includes(a.toLowerCase())),[j,k,a]),ae=N.useMemo(()=>{var Re,Oe;const de=((Re=D==null?void 0:D.shares)==null?void 0:Re.specificGroups)||((Oe=D==null?void 0:D.shares)==null?void 0:Oe.groups)||[];return!de||de.length===0?[]:de.filter(mt=>{const be=j.find(re=>re.id===mt.groupId);return(be==null?void 0:be.type)==="TENANT_GROUP"})},[D,j]),he=I||B||k==="groups"&&_,ye=F||V,Te=()=>(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:[ye&&c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsxs("div",{className:"text-center",children:[c.jsx(md,{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"})]})}),!ye&&n&&c.jsxs("div",{className:"max-h-[500px] space-y-4 overflow-y-auto",children:[c.jsx(wD,{shareType:k,onShareTypeChange:T,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(os,{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(wc,{className:"mb-3 h-6 w-6 text-orange-500"})},{value:"groups",label:"Groups",description:"Share with tenant groups",icon:c.jsx(os,{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(DA,{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(R_,{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(wc,{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(le,{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:(_e=S==null?void 0:S.tenants)==null?void 0:_e.map(de=>c.jsx(pe,{value:de.id,children:de.name},de.id))})]})]}),Te()?c.jsx(c.Fragment,{children:k==="specific_tenant_users"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(fv,{value:a,onChange:u}),c.jsx(B7,{selectedUsers:d,selectedUserObjects:G,onRemove:de=>$(de),onRoleChange:P,getRoleOptions:mi}),c.jsx(V7,{usersToRemove:f,allUsers:O,onRemove:L}),c.jsx(H7,{usersToUpdate:h,allUsers:O,onRemove:A,getRoleOptions:mi}),c.jsx(FH,{existingShares:D,isInitialLoading:!!he,isSearching:!1,resource:e,onShare:()=>{},getRoleOptions:mi,allUsers:O,currentUser:n,handleUserToggle:$,handleUserRoleChange:P,handleRemoveAccess:H,handleUpdateAccess:W})]}):k==="groups"?c.jsxs("div",{className:"space-y-4",children:[c.jsx(fv,{value:a,onChange:u,placeholder:"Search groups..."}),c.jsx(iU,{selectedGroups:p,groupObjects:se,onRemove:Z,onRoleChange:te,getRoleOptions:mi}),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(oU,{groups:ce,existingGroupShares:ae,isLoading:_,resource:e,getRoleOptions:mi,currentUser:n,handleGroupToggle:Z,handleGroupRoleChange:te,handleRemoveAccess:X,handleUpdateAccess:ne})]}):k==="all_tenant_users"||k==="all_tenants"?c.jsx("div",{className:"mt-6",children:c.jsx(sU,{currentUser:n,currentShare:z,isSharing:s,isUpdating:o,isRemoving:i,onUpdateAccess:q,onRemoveAccess:Y,allUsersToUpdate:b==="allTenantUsers"&&((z==null?void 0:z.role)===void 0||x!==z.role)||b==="allTenants"&&((z==null?void 0:z.role)===void 0||y!==z.role)?{currentRole:(z==null?void 0:z.role)||"VIEWER",newRole:b==="allTenantUsers"?x:y}:null,allUsersToRemove:b==="allTenantUsers"&&(z==null?void 0:z.role)===void 0||b==="allTenants"&&(z==null?void 0:z.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(DA,{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 ZSe({resource:e,resourceType:t,currentUser:n,onShareTabTypeChange:r,isSharing:s=!1,isUpdating:o=!1,isRemoving:i=!1}){var F,B;const{searchQuery:a,setSearchQuery:l}=xD(),u=Sp(),d=Cp(),f=Np(),h=Yc(),[p,m]=N.useState("org_groups"),[g,b]=N.useState(""),{data:x,isLoading:y}=r9({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}=aU(w(),p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"?g:n==null?void 0:n.tenantId),{existingShares:j}=Oh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t}),_=S.filter(V=>p==="org_groups"&&V.type!=="ORG_GROUP"||p==="tenant_groups"&&V.type!=="TENANT_GROUP"||p==="tenant_groups"&&(n==null?void 0:n.type)==="organization"&&(!g||V.tenantId&&V.tenantId!==g)?!1:V.name.toLowerCase().includes(a.toLowerCase())||V.description&&V.description.toLowerCase().includes(a.toLowerCase())),k=((F=j==null?void 0:j.shares)==null?void 0:F.specificGroups)||((B=j==null?void 0:j.shares)==null?void 0:B.groups)||[];N.useEffect(()=>{h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},[h]);const E=V=>{const $=V;m($),$==="org_groups"&&b(""),r==null||r($==="org_groups"?"specific_groups":"all_groups"),h.setCurrentContext("group-share"),h.setCurrentMode("specificGroups")},T=S.filter(V=>u.some($=>$.id===V.id)),R=V=>{const $=u.some(L=>L.id===V),P=d.includes(V),H=k==null?void 0:k.some(L=>L.groupId===V);$?h.removeSelectedGroup(V):P?h.removeGroupFromRemove(V):H||h.addSelectedGroup({id:V,role:"VIEWER"})},O=(V,$)=>{h.updateSelectedGroupRole(V,$)},D=V=>{h.addGroupToRemove(V),h.removeSelectedGroup(V)},I=(V,$,P)=>{h.addGroupToUpdate({id:V,currentRole:$,newRole:P})};return n?c.jsxs(c.Fragment,{children:[c.jsx(wD,{shareType:p,onShareTypeChange:E,currentUser:n,options:[{value:"org_groups",label:"Organization Groups",description:"Share with organization-level groups",icon:c.jsx(pd,{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(os,{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(le,{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(V=>c.jsx(pe,{className:"hover:bg-muted",value:V.id,children:V.name},V.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(fv,{value:a,onChange:l,placeholder:"Search groups..."}),c.jsx(iU,{selectedGroups:u,groupObjects:T,onRemove:R,onRoleChange:O,getRoleOptions:mi}),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(oU,{groups:_,existingGroupShares:k,isLoading:C,resource:e,getRoleOptions:mi,currentUser:n,handleGroupToggle:R,handleGroupRoleChange:O,handleRemoveAccess:D,handleUpdateAccess:I})]})})]}):null}const GU=()=>{const e=AH(),t=qc(),n=vp(),r=Yd(),s=wp(),o=Sp(),i=Cp(),a=Np(),l=Yb(),u=gD(),d=bD(),f=T1(),h=PH(),p=N.useMemo(()=>()=>xhe({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=>cB(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 $5({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllUsersShare:l,onRemoveAccess:u}){const d=vp(),f=Yd(),h=wp(),p=Yb(),m=gD(),g=bD(),b=T1(),{buildShareData:x,validateShareData:y,isCurrentStateValid:v}=GU(),w=n||r||s,S=()=>{var E,T,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 D=d.length+f.length+h.length;return D===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${D} user${D!==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 ${D} user${D!==1?"s":""}`}else if(a==="all_users"){if(!l||l.role===void 0)return"Share with All Users";const D=l.role;return m===D?"Remove Access":"Update Access"}else if(a==="all_tenants"){const D=(T=(E=t==null?void 0:t.shares)==null?void 0:E.allTenantsOnly)==null?void 0:T[0];if(!D||D.role===void 0)return"Share with All Tenants";const I=D.role;return g===I?"Remove Access":"Update Access"}else if(a==="all_tenant_users"){const D=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!D||D.role===void 0)return"Share with All Tenant Users";const I=D.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 D=d.length+f.length+h.length;return D===0?"Select users to share with":d.length>0&&f.length>0?`Update access for ${D} user${D!==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 ${D} user${D!==1?"s":""}`}return"Share"},C=()=>w||!e||a==="all_tenant_users"&&!p||a==="specific_tenant_users"&&!p?!0:!v,j=()=>{const E=x();E&&y(E)&&o(E)},_=()=>{var E,T,R,O;if(a==="all_users")if(!l||l.role===void 0){const D=x();D&&y(D)&&o(D)}else{const D=l.role;if(m===D)u==null||u();else{const F=x();if(F&&y(F)){const B={...F,updateAccess:!0};o(B)}}}else if(a==="all_tenants"){const D=(T=(E=t==null?void 0:t.shares)==null?void 0:E.allTenantsOnly)==null?void 0:T[0];if(!D||D.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=D.role;if(g===I)u==null||u();else{const B=x();if(B&&y(B)){const V={...B,updateAccess:!0};o(V)}}}}else if(a==="all_tenant_users"){const D=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!D||D.role===void 0){const I=x();I&&y(I)&&o(I)}else{const I=D.role;if(b===I)u==null||u();else{const B=x();if(B&&y(B)){const V={...B,updateAccess:!0};o(V)}}}}},k=()=>{var E,T,R,O;if(a==="all_users"){if(!l||l.role===void 0)return"default";const D=l.role;return m===D?"destructive":"default"}else if(a==="all_tenants"){const D=(T=(E=t==null?void 0:t.shares)==null?void 0:E.allTenantsOnly)==null?void 0:T[0];if(!D||D.role===void 0)return"default";const I=D.role;return g===I?"destructive":"default"}else if(a==="all_tenant_users"){const D=(O=(R=t==null?void 0:t.shares)==null?void 0:R.tenantWide)==null?void 0:O[0];if(!D||D.role===void 0)return"default";const I=D.role;return b===I?"destructive":"default"}return"default"};return c.jsxs(Ms,{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(Zu,{className:"mr-2 h-4 w-4"}),!w&&S()]})}),(a==="all_users"||a==="all_tenants"||a==="all_tenant_users")&&c.jsxs(oe,{onClick:_,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(os,{className:"mr-2 h-4 w-4"}),!w&&S()]})]})}function KSe({resource:e,isSharing:t,isRemoving:n,isUpdating:r,onShare:s,onClose:o,shareTabType:i,currentAllUsersShare:a}){const l=vp(),u=Yd(),d=wp(),f=Sp(),h=Cp(),p=Np();qc(),AH();const m=T1();Yb();const{buildShareData:g,validateShareData:b,isCurrentStateValid:x}=GU(),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 T=g();if(T&&b(T)){const R={...T,removeAccess:!0};s(R)}}else{const T=g();if(T&&b(T)){const R={...T,updateAccess:!0};s(R)}}}},_=()=>!a||a.role==="NONE"?"default":"destructive";return c.jsxs(Ms,{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(Zu,{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(Zu,{className:"mr-2 h-4 w-4"}),!y&&v()]})}),i==="all_users"&&c.jsxs(oe,{onClick:j,disabled:w(),variant:_(),children:[y?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Updating..."]}):c.jsx(Zu,{className:"mr-2 h-4 w-4"}),!y&&v()]})]})}function XSe({resource:e,existingShares:t,isSharing:n,isRemoving:r,isUpdating:s,onShare:o,onClose:i,shareTabType:a,currentAllGroupsShare:l,onRemoveAccess:u}){const d=Sp(),f=Cp(),h=Np();PH(),qc();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 to(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function el(e,t,n){return{resourceType:e,resourceId:t,data:{shares:n}}}function QSe(e,t,n){const{resourceType:r,resourceId:s,shareMutation:o,removeMutation:i,existingShares:a,resetUserSelections:l}=t;if(s)switch(e.context){case"org-tab":if(e.mode==="allOrgUsers"){const u=to(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=to(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=el(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=to(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=to(r,s,[{scope:"all_tenants_only",role:e.allTenantsRole}]);o(u,{onSuccess:()=>{l()}})}else if(e.mode==="allTenantUsers"){const u=to(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=el(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=to(r,s,[{scope:"specific_tenant_user",tenantUserId:p.id,tenantId:h,role:p.newRole}]);o(m,{onSuccess:()=>{l()}})}),u&&u.length>0){const p=to(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=el(r,s,[{scope:"all_tenant_users",role:"VIEWER"}]);i(u,{onSuccess:()=>{l()}})}else if(e.updateAccess){const u=to(r,s,[{scope:"all_tenant_users",tenantId:n==null?void 0:n.tenantId,role:e.tenantWideRole}]);o(u,{onSuccess:()=>{l()}})}else{const u=to(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=to(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=el(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=to(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=to(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),ze.success(`Shared with ${u.length} group${u.length!==1?"s":""}`)}})}if(d&&d.length>0){const h=el(r,s,d.map(p=>({scope:"group",groupId:p,role:"VIEWER"})));i(h,{onSuccess:()=>{var p;l(),(p=t.resetGroupSelections)==null||p.call(t),ze.success(`Removed access from ${d.length} group${d.length!==1?"s":""}`)}})}f&&f.length>0&&f.forEach(h=>{const p=to(r,s,[{scope:"group",groupId:h.id,role:h.newRole}]);o(p,{onSuccess:()=>{var m;l(),(m=t.resetGroupSelections)==null||m.call(t),ze.success("Updated access for group")}})})}break}}function JSe(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=el(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=el(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=el(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=el(s,o,[{scope:"org_users_only",role:x.role}]);i(y,{onSuccess:()=>{l()},onError:v=>{console.error("Remove org-wide access failed:",v)}})}}}}function eCe(e,t,n){const r=Yc(),s=Yd(),o=mD(),i=qc(),{currentUser:a}=_s(),{existingShares:l}=Oh({debouncedSearchQuery:"",resourceId:e||"",resourceType:$t.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:$t.DASHBOARD,resourceId:e,shareMutation:t,removeMutation:n,existingShares:l,resetUserSelections:u,resetGroupSelections:d};QSe(p,m,a)},[e,t,n,l,u,d,a]),h=N.useCallback(()=>{if(!e)return;const p={resourceType:$t.DASHBOARD,resourceId:e,removeMutation:n,existingShares:l,resetUserSelections:u};JSe(s,o||"",i||"",p)},[e,t,n,l,u,d,s,o,i]);return{handleShareSubmit:f,handleRemoveAccess:h}}function ZU({resource:e,resourceType:t,onClose:n,onShareSuccess:r,onRemoveSuccess:s}){var O,D,I,F,B,V,$,P;const{currentUser:o}=_s(),[i,a]=N.useState("specific_users"),[l,u]=N.useState("specific_users"),[d,f]=N.useState("specific_groups"),h=Yc(),p=mD(),m=qc(),g=o9(),b=i9(),{handleShareSubmit:x,handleRemoveAccess:y}=eCe(e.id,(H,L)=>{g.mutate(H,{...L,onSuccess:()=>{var A;(A=L==null?void 0:L.onSuccess)==null||A.call(L),r==null||r()}})},(H,L)=>{b.mutate(H,{...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}=Oh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"tenant"}),{existingShares:j}=Oh({debouncedSearchQuery:"",resourceId:(e==null?void 0:e.id)||"",resourceType:t,userType:"organization"}),_=(D=(O=C==null?void 0:C.shares)==null?void 0:O.tenantWide)==null?void 0:D[0],k=(F=(I=j==null?void 0:j.shares)==null?void 0:I.orgUsersOnly)==null?void 0:F[0],E=()=>{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"}},T=N.useCallback(()=>{h.resetShareState(),n()},[h,n]),R=(o==null?void 0:o.type)==="organization";return c.jsx(as,{open:!0,onOpenChange:T,children:c.jsxs(Br,{className:"z-[51] flex max-h-[80vh] max-w-3xl flex-col",children:[c.jsxs(Vr,{children:[c.jsx(Hr,{children:c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(Zu,{className:"h-5 w-5"}),' Share "',e==null?void 0:e.title,'"']})}),c.jsx(Ds,{children:R?"Share this resource with org users or tenant users.":"Share this resource with other users in your tenant."})]}),R?c.jsxs(ls,{value:p,onValueChange:H=>{const L=H;h.setSelectedTab(L),h.resetUserSelections(),h.resetGroupSelections()},className:"mb-4 min-h-0 flex-1",children:[c.jsxs(Ur,{className:"mb-2 grid w-full grid-cols-3",children:[c.jsx(Ut,{value:"org",children:"Org Users"}),c.jsx(Ut,{value:"tenant",children:"Tenant Users"}),c.jsx(Ut,{value:"groups",children:"Groups"})]}),c.jsx(Yn,{value:"org",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(fSe,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:u,isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx(Yn,{value:"tenant",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(F5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:H=>a(H),isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx(Yn,{value:"groups",className:"min-h-0 flex-1 overflow-hidden",children:c.jsx("div",{className:"h-full overflow-y-auto",children:c.jsx(ZSe,{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(F5,{resource:e,resourceType:t,currentUser:o,onShareTabTypeChange:H=>a(H),isSharing:v,isUpdating:S,isRemoving:w})})}),c.jsx("div",{className:"mt-auto flex-shrink-0",children:R?p==="org"?c.jsx($5,{resource:e,existingShares:j,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:l,currentAllUsersShare:k,onRemoveAccess:y}):p==="tenant"?c.jsx($5,{resource:e,existingShares:C,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:E(),currentAllUsersShare:_,onRemoveAccess:y}):c.jsx(XSe,{resource:e,existingShares:j,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:d,currentAllGroupsShare:(o==null?void 0:o.type)==="organization"?(V=(B=j==null?void 0:j.shares)==null?void 0:B.allOrgGroups)==null?void 0:V[0]:(P=($=C==null?void 0:C.shares)==null?void 0:$.allTenantGroups)==null?void 0:P[0],onRemoveAccess:y}):c.jsx(KSe,{resource:e,isSharing:v,isRemoving:w,isUpdating:S,onShare:x,onClose:n,shareTabType:i,currentAllUsersShare:_,onRemoveAccess:y})})]})})}const Cn=M.forwardRef(({className:e,type:t,...n},r)=>c.jsx("input",{type:t,className:K("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}));Cn.displayName="Input";function KU({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(as,{open:e,onOpenChange:h=>h?null:s(),children:c.jsx(Br,{className:"sm:max-w-md",children:c.jsxs("form",{onSubmit:f,className:"space-y-4",children:[c.jsxs(Vr,{children:[c.jsxs(Hr,{children:["Edit ",t]}),c.jsxs(Ds,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(le,{htmlFor:"resource-title",children:"Title"}),c.jsx(Cn,{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(le,{htmlFor:"resource-description",children:"Description"}),c.jsx(Ud,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),c.jsxs(Ms,{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 tCe({onDashboardSelect:e}){var q;const{authToken:t}=Ge(),[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),b=Ys(Y=>Y.actions.selectDashboard),{userContext:x}=_s(),y=((q=x==null?void 0:x.permissions)==null?void 0:q.canCreateDashboard)??!1,{onCreateSuccess:v}=u9({onDashboardSelect:e}),{resources:w,isLoading:S,isError:C,createResource:j,updateResource:_,deleteResource:k,duplicateResource:E,isCreating:T,isDeleting:R,refetch:O}=c9(()=>{u(!1),f(null)},Y=>{r(!1),v(Y,O)}),{startUpdating:D,stopUpdating:I,isUpdating:F}=l9(),B=Y=>{const U=w.find(z=>z.id===Y);U&&(b(U),e==null||e(Y))},V=Y=>{j({title:Y.title,description:Y.description,isPrivate:!1})},$=Y=>{f(Y),u(!0)},P=()=>{d&&k(d.id)},H=Y=>{p(Y),E(Y,{onSettled:()=>p(null)})},L=(Y,U,z)=>{var X;const G=Object.fromEntries(Object.entries(U).filter(([,ne])=>ne!==void 0));if(Object.keys(G).length===0){(X=z==null?void 0:z.onSuccess)==null||X.call(z);return}const Z=Object.keys(G),te=Z.length===1?Z[0]:void 0;D(Y,te),_({resourceId:Y,data:G},{onSuccess:()=>{var ne;I(Y,te),(ne=z==null?void 0:z.onSuccess)==null||ne.call(z)},onError:()=>{var ne;I(Y,te),(ne=z==null?void 0:z.onError)==null||ne.call(z)}})},A=Y=>{a(Y),o(!0)},W=Y=>new Date(Y).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return t?S?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..."})]})}):C?c.jsx("div",{className:"flex h-full grow items-center justify-center",children:c.jsxs("div",{className:"text-center",children:[c.jsx(md,{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"}),w.length>0&&y&&c.jsx("div",{className:"mt-6 flex gap-3",children:c.jsxs(oe,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(jr,{className:"h-4 w-4"}),"Create New Dashboard"]})})]}),w.length>0&&c.jsxs("div",{className:"rounded-md bg-orange-500 px-3 py-1 text-sm font-medium text-white",children:[w.length," dashboard",w.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:w.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(I_,{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:y?"Create your first dashboard to get started with analytics":"No dashboards have been shared with you yet"}),y&&c.jsxs(oe,{onClick:()=>r(!0),className:"gap-2",children:[c.jsx(jr,{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:w.map(Y=>c.jsx(jue,{dashboard:Y,onView:B,isDeleting:R&&(d==null?void 0:d.id)===Y.id,isDuplicating:h===Y.id,onEditDetails:g,onDeleteClick:$,onDuplicateDashboard:H,onShareDashboard:A,formatDate:W},Y.id))})]})})}),c.jsx(z9,{open:n,onOpenChange:r,onSubmit:V,isCreating:T}),m&&c.jsx(KU,{open:!!m,resourceLabel:"Dashboard",initialTitle:m.title||"",initialDescription:m.description||"",onClose:()=>g(null),onSave:Y=>{L(m.id,Y,{onSuccess:()=>{g(null)}})},isSaving:F(m.id)}),c.jsx($b,{open:l,onOpenChange:u,children:c.jsxs(ap,{children:[c.jsxs(lp,{children:[c.jsx(up,{children:"Delete Dashboard?"}),c.jsxs(dp,{children:['Are you sure you want to delete "',d==null?void 0:d.title,'"? This action cannot be undone.']})]}),c.jsxs(cp,{children:[c.jsx(hp,{disabled:R,children:"Cancel"}),c.jsx(fp,{onClick:P,disabled:R,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:R?c.jsxs(c.Fragment,{children:[c.jsx(On,{className:"mr-2 h-4 w-4 animate-spin"}),"Deleting..."]}):"Delete"})]})]})}),i&&s&&c.jsx(ZU,{resource:i,resourceType:$t.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(md,{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 nd=Nl()(Sne(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})})),XU=e=>nd(t=>t.panels[e]),QU=()=>nd(e=>e.fullscreen),JU=e=>nd(t=>t.panels[e].container??null);function eW(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 nCe(e){const{selectedEntities:t}=e,n=t.map(r=>({...r,qualifiedEntityName:Af(r)}));return{...e,selectedEntities:n}}const L5={selectedEntities:[]},Bi=Nl()(Nb((e,t)=>({currentAIContext:L5,activeAssistantType:null,reasoningEffort:"low",showReasoning:!1,messageQueues:{dashboard:[],editor:[]},fileAttachments:{dashboard:[],editor:[]},uploadProgress:new Map,actions:{setCurrentAIContext:n=>{e(r=>{r.currentAIContext=nCe(n)})},setActiveAssistantType:n=>{e(r=>{r.activeAssistantType=n})},updateSelectedEntities:n=>{e(r=>{r.currentAIContext.selectedEntities=n})},clearAIContext:()=>{e(n=>{n.currentAIContext=L5})},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]}}))),_p=()=>Bi(e=>e.currentAIContext),_D=()=>Bi(e=>e.activeAssistantType),rCe=()=>Bi(e=>e.reasoningEffort),sCe=()=>Bi(e=>e.showReasoning),F1=()=>Bi(e=>e.actions),tW=e=>Bi(t=>t.messageQueues[e]),Mp=()=>Bi(e=>({queueMessage:e.actions.queueMessage,dequeueMessage:e.actions.dequeueMessage,removeFromQueue:e.actions.removeFromQueue,clearQueue:e.actions.clearQueue})),MD=e=>Bi(t=>t.fileAttachments[e]),DD=()=>Bi(e=>({addFileAttachment:e.actions.addFileAttachment,removeFileAttachment:e.actions.removeFileAttachment,clearFileAttachments:e.actions.clearFileAttachments,updateUploadProgress:e.actions.updateUploadProgress,getFileAttachments:e.actions.getFileAttachments}));function nW(){const{tokenProps:e,id:t}=Ge(),n=Ys(s=>s.selectedDashboard);return!!(n!=null&&n.id||t||e!=null&&e.dashboard_id)}function TD({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}=Ge();Ys(O=>O.selectedDashboard);const _=J(O=>O.themeStyle),k=J(O=>O.isSessionExpired),{isLoading:E,isError:T}=Yoe({customStyle:t,currentTheme:u,onSave:n,onEvent:r,defaultFilterValues:p,onFilterValuesChange:m,selectedSheetId:g}),R=nW();return l&&!R&&!E?c.jsx(tCe,{}):E||!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]"})})):T?(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(_i,{children:"Session Expired"}),c.jsx("p",{className:"text-muted-foreground",children:"Please refresh your page to continue"})]})})):c.jsx("div",{className:K("isolate flex grow flex-col",{"h-full":x==="visual"},_==null?void 0:_.dashboardPanel,e),style:{},"data-role":"semaphor-container",...w})}var rW={exports:{}},Zb={},Vk={exports:{}};(function(e,t){(function(n,r){r(t)})(nl,function(n){function r(z){return function(Z,te,X,ne,se,ce,ae){return z(Z,te,ae)}}function s(z){return function(Z,te,X,ne){if(!Z||!te||typeof Z!="object"||typeof te!="object")return z(Z,te,X,ne);var se=ne.get(Z),ce=ne.get(te);if(se&&ce)return se===te&&ce===Z;ne.set(Z,te),ne.set(te,Z);var ae=z(Z,te,X,ne);return ne.delete(Z),ne.delete(te),ae}}function o(z,G){var Z={};for(var te in z)Z[te]=z[te];for(var te in G)Z[te]=G[te];return Z}function i(z){return z.constructor===Object||z.constructor==null}function a(z){return typeof z.then=="function"}function l(z,G){return z===G||z!==z&&G!==G}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(z){var G=z.areArraysEqual,Z=z.areDatesEqual,te=z.areMapsEqual,X=z.areObjectsEqual,ne=z.areRegExpsEqual,se=z.areSetsEqual,ce=z.createIsNestedEqual,ae=ce(he);function he(ye,Te,_e){if(ye===Te)return!0;if(!ye||!Te||typeof ye!="object"||typeof Te!="object")return ye!==ye&&Te!==Te;if(i(ye)&&i(Te))return X(ye,Te,ae,_e);var de=Array.isArray(ye),Re=Array.isArray(Te);if(de||Re)return de===Re&&G(ye,Te,ae,_e);var Oe=y.call(ye);return Oe!==y.call(Te)?!1:Oe===f?Z(ye,Te,ae,_e):Oe===h?ne(ye,Te,ae,_e):Oe===p?te(ye,Te,ae,_e):Oe===b?se(ye,Te,ae,_e):Oe===g||Oe===u?a(ye)||a(Te)?!1:X(ye,Te,ae,_e):Oe===d||Oe===m||Oe===x?l(ye.valueOf(),Te.valueOf()):!1}return he}function w(z,G,Z,te){var X=z.length;if(G.length!==X)return!1;for(;X-- >0;)if(!Z(z[X],G[X],X,X,z,G,te))return!1;return!0}var S=s(w);function C(z,G){return l(z.valueOf(),G.valueOf())}function j(z,G,Z,te){var X=z.size===G.size;if(!X)return!1;if(!z.size)return!0;var ne={},se=0;return z.forEach(function(ce,ae){if(X){var he=!1,ye=0;G.forEach(function(Te,_e){!he&&!ne[ye]&&(he=Z(ae,_e,se,ye,z,G,te)&&Z(ce,Te,ae,_e,z,G,te))&&(ne[ye]=!0),ye++}),se++,X=he}}),X}var _=s(j),k="_owner",E=Object.prototype.hasOwnProperty;function T(z,G,Z,te){var X=Object.keys(z),ne=X.length;if(Object.keys(G).length!==ne)return!1;for(var se;ne-- >0;){if(se=X[ne],se===k){var ce=!!z.$$typeof,ae=!!G.$$typeof;if((ce||ae)&&ce!==ae)return!1}if(!E.call(G,se)||!Z(z[se],G[se],se,se,z,G,te))return!1}return!0}var R=s(T);function O(z,G){return z.source===G.source&&z.flags===G.flags}function D(z,G,Z,te){var X=z.size===G.size;if(!X)return!1;if(!z.size)return!0;var ne={};return z.forEach(function(se,ce){if(X){var ae=!1,he=0;G.forEach(function(ye,Te){!ae&&!ne[he]&&(ae=Z(se,ye,ce,Te,z,G,te))&&(ne[he]=!0),he++}),X=ae}}),X}var I=s(D),F=Object.freeze({areArraysEqual:w,areDatesEqual:C,areMapsEqual:j,areObjectsEqual:T,areRegExpsEqual:O,areSetsEqual:D,createIsNestedEqual:r}),B=Object.freeze({areArraysEqual:S,areDatesEqual:C,areMapsEqual:_,areObjectsEqual:R,areRegExpsEqual:O,areSetsEqual:I,createIsNestedEqual:r}),V=v(F);function $(z,G){return V(z,G,void 0)}var P=v(o(F,{createIsNestedEqual:function(){return l}}));function H(z,G){return P(z,G,void 0)}var L=v(B);function A(z,G){return L(z,G,new WeakMap)}var W=v(o(B,{createIsNestedEqual:function(){return l}}));function q(z,G){return W(z,G,new WeakMap)}function Y(z){return v(o(F,z(F)))}function U(z){var G=v(o(B,z(B)));return function(Z,te,X){return X===void 0&&(X=new WeakMap),G(Z,te,X)}}n.circularDeepEqual=A,n.circularShallowEqual=q,n.createCustomCircularEqual=U,n.createCustomEqual=Y,n.deepEqual=$,n.sameValueZeroEqual=l,n.shallowEqual=H,Object.defineProperty(n,"__esModule",{value:!0})})})(Vk,Vk.exports);var RD=Vk.exports;const ID=o_(ute);var At={},oCe=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(At,"__esModule",{value:!0});At.bottom=AD;At.childrenEqual=cCe;At.cloneLayout=sW;At.cloneLayoutItem=rd;At.collides=$1;At.compact=iW;At.compactItem=aW;At.compactType=SCe;At.correctBounds=lW;At.fastPositionEqual=uCe;At.fastRGLPropsEqual=void 0;At.getAllCollisions=cW;At.getFirstCollision=Ru;At.getLayoutItem=PD;At.getStatics=OD;At.modifyLayout=oW;At.moveElement=Tm;At.moveElementAwayFromCollision=Uk;At.noop=void 0;At.perc=fCe;At.resizeItemInDirection=xCe;At.setTopLeft=vCe;At.setTransform=yCe;At.sortLayoutItems=VD;At.sortLayoutItemsByColRow=pW;At.sortLayoutItemsByRowCol=hW;At.synchronizeLayoutWithChildren=wCe;At.validateLayout=mW;At.withLayoutItem=lCe;var z5=RD,Dm=iCe(N);function iCe(e){return e&&e.__esModule?e:{default:e}}const aCe=process.env.NODE_ENV==="production";function AD(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 sW(e){const t=Array(e.length);for(let n=0,r=e.length;n<r;n++)t[n]=rd(e[n]);return t}function oW(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 lCe(e,t,n){let r=PD(e,t);return r?(r=n(rd(r)),e=oW(e,r),[e,r]):[e,null]}function rd(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 cCe(e,t){return(0,z5.deepEqual)(Dm.default.Children.map(e,n=>n==null?void 0:n.key),Dm.default.Children.map(t,n=>n==null?void 0:n.key))&&(0,z5.deepEqual)(Dm.default.Children.map(e,n=>n==null?void 0:n.props["data-grid"]),Dm.default.Children.map(t,n=>n==null?void 0:n.props["data-grid"]))}At.fastRGLPropsEqual=oCe;function uCe(e,t){return e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height}function $1(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 iW(e,t,n,r){const s=OD(e),o=VD(e,t),i=Array(e.length);for(let a=0,l=o.length;a<l;a++){let u=rd(o[a]);u.static||(u=aW(s,u,t,n,o,r),s.push(u)),i[e.indexOf(o[a])]=u,u.moved=!1}return i}const dCe={x:"w",y:"h"};function Hk(e,t,n,r){const s=dCe[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;$1(t,a)&&Hk(e,a,n+t[s],r)}}t[r]=n}function aW(e,t,n,r,s,o){const i=n==="vertical",a=n==="horizontal";if(i)for(t.y=Math.min(AD(e),t.y);t.y>0&&!Ru(e,t);)t.y--;else if(a)for(;t.x>0&&!Ru(e,t);)t.x--;let l;for(;(l=Ru(e,t))&&!(n===null&&o);)if(a?Hk(s,t,l.x+l.w,"x"):Hk(s,t,l.y+l.h,"y"),a&&t.x+t.w>r)for(t.x=r-t.w,t.y++;t.x>0&&!Ru(e,t);)t.x--;return t.y=Math.max(t.y,0),t.x=Math.max(t.x,0),t}function lW(e,t){const n=OD(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(;Ru(n,o);)o.y++}return e}function PD(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n].i===t)return e[n]}function Ru(e,t){for(let n=0,r=e.length;n<r;n++)if($1(e[n],t))return e[n]}function cW(e,t){return e.filter(n=>$1(n,t))}function OD(e){return e.filter(t=>t.static)}function Tm(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=VD(e,i);(i==="vertical"&&typeof r=="number"?d>=r:i==="horizontal"&&typeof n=="number"?u>=n:!1)&&(f=f.reverse());const p=cW(f,t),m=p.length>0;if(m&&l)return sW(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=Uk(e,x,t,s,i):e=Uk(e,t,x,s,i))}return e}function Uk(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=Ru(e,f),p=h&&h.y+h.h>t.y,m=h&&t.x+t.w>h.x;if(h){if(p&&a)return Tm(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 Tm(e,t,n.x,void 0,r,l,s)}else return`${n.i}${f.x}${f.y}`,Tm(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:Tm(e,n,i?n.x+1:void 0,a?n.y+1:void 0,r,l,s)}function fCe(e){return e*100+"%"}const uW=(e,t,n,r)=>e+n>r?t:n,dW=(e,t,n)=>e<0?t:n,fW=e=>Math.max(0,e),FD=e=>Math.max(0,e),$D=(e,t,n)=>{let{left:r,height:s,width:o}=t;const i=e.top-(s-e.height);return{left:r,width:o,height:dW(i,e.height,s),top:FD(i)}},LD=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{top:r,height:o,width:uW(e.left,e.width,i,n),left:fW(s)}},zD=(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:uW(e.left,e.width,o,n),top:FD(r),left:fW(i)}},BD=(e,t,n)=>{let{top:r,left:s,height:o,width:i}=t;return{width:i,left:s,height:dW(r,e.height,o),top:FD(r)}},hCe=function(){return $D(arguments.length<=0?void 0:arguments[0],LD(...arguments))},pCe=function(){return $D(arguments.length<=0?void 0:arguments[0],zD(...arguments))},mCe=function(){return BD(arguments.length<=0?void 0:arguments[0],LD(...arguments))},gCe=function(){return BD(arguments.length<=0?void 0:arguments[0],zD(...arguments))},bCe={n:$D,ne:hCe,e:LD,se:mCe,s:BD,sw:gCe,w:zD,nw:pCe};function xCe(e,t,n,r){const s=bCe[e];return s?s(t,{...t,...n},r):n}function yCe(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 vCe(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 VD(e,t){return t==="horizontal"?pW(e):t==="vertical"?hW(e):e}function hW(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 pW(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 wCe(e,t,n,r,s){e=e||[];const o=[];Dm.default.Children.forEach(t,a=>{if((a==null?void 0:a.key)==null)return;const l=PD(e,String(a.key)),u=a.props["data-grid"];l&&u==null?o.push(rd(l)):u?(aCe||mW([u],"ReactGridLayout.children"),o.push(rd({...u,i:a.key}))):o.push(rd({w:1,h:1,x:0,y:AD(o),i:String(a.key)}))});const i=lW(o,{cols:n});return s?i:iW(i,r,n)}function mW(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 SCe(e){const{verticalCompact:t,compactType:n}=e||{};return t===!1?null:n}const CCe=()=>{};At.noop=CCe;var Ta={};Object.defineProperty(Ta,"__esModule",{value:!0});Ta.calcGridColWidth=L1;Ta.calcGridItemPosition=NCe;Ta.calcGridItemWHPx=Wk;Ta.calcWH=kCe;Ta.calcXY=jCe;Ta.clamp=Iu;function L1(e){const{margin:t,containerPadding:n,containerWidth:r,cols:s}=e;return(r-t[0]*(s-1)-n[0]*2)/s}function Wk(e,t,n){return Number.isFinite(e)?Math.round(t*e+Math.max(0,e-1)*n):e}function NCe(e,t,n,r,s,o){const{margin:i,containerPadding:a,rowHeight:l}=e,u=L1(e),d={};return o&&o.resizing?(d.width=Math.round(o.resizing.width),d.height=Math.round(o.resizing.height)):(d.width=Wk(r,u,i[0]),d.height=Wk(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 jCe(e,t,n,r,s){const{margin:o,containerPadding:i,cols:a,rowHeight:l,maxRows:u}=e,d=L1(e);let f=Math.round((n-i[0])/(d+o[0])),h=Math.round((t-i[1])/(l+o[1]));return f=Iu(f,0,a-r),h=Iu(h,0,u-s),{x:f,y:h}}function kCe(e,t,n,r,s,o){const{margin:i,maxRows:a,cols:l,rowHeight:u}=e,d=L1(e);let f=Math.round((t+i[0])/(d+i[0])),h=Math.round((n+i[1])/(u+i[1])),p=Iu(f,0,l-r),m=Iu(h,0,a-s);return["sw","w","nw"].indexOf(o)!==-1&&(p=Iu(f,0,l)),["nw","n","ne"].indexOf(o)!==-1&&(m=Iu(h,0,a)),{w:p,h:m}}function Iu(e,t,n){return Math.max(Math.min(e,n),t)}var z1={},qk={exports:{}},_0={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 XZe=UGe(()=>hJ(Ar([Un({type:ut("text-start"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("text-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Un({type:ut("text-end"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("error"),errorText:$e()}),Un({type:ut("tool-input-start"),toolCallId:$e(),toolName:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Un({type:ut("tool-input-delta"),toolCallId:$e(),inputTextDelta:$e()}),Un({type:ut("tool-input-available"),toolCallId:$e(),toolName:$e(),input:uo(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional()}),Un({type:ut("tool-input-error"),toolCallId:$e(),toolName:$e(),input:uo(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional(),errorText:$e()}),Un({type:ut("tool-output-available"),toolCallId:$e(),output:uo(),providerExecuted:wr().optional(),dynamic:wr().optional(),preliminary:wr().optional()}),Un({type:ut("tool-output-error"),toolCallId:$e(),errorText:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Un({type:ut("reasoning-start"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("reasoning-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Un({type:ut("reasoning-end"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("source-url"),sourceId:$e(),url:$e(),title:$e().optional(),providerMetadata:ir.optional()}),Un({type:ut("source-document"),sourceId:$e(),mediaType:$e(),title:$e(),filename:$e().optional(),providerMetadata:ir.optional()}),Un({type:ut("file"),url:$e(),mediaType:$e(),providerMetadata:ir.optional()}),Un({type:lJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:$e().optional(),data:uo(),transient:wr().optional()}),Un({type:ut("start-step")}),Un({type:ut("finish-step")}),Un({type:ut("start"),messageId:$e().optional(),messageMetadata:uo().optional()}),Un({type:ut("finish"),messageMetadata:uo().optional()}),Un({type:ut("abort")}),Un({type:ut("message-metadata"),messageMetadata:uo()})])));function QZe(e){return e.type.startsWith("data-")}function wJ(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]=wJ(o,s):n[r]=s}return n}function JZe(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 SJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await _w({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await _w({text:JZe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Fy(e){return e.type.startsWith("tool-")}function eKe(e){return e.type==="dynamic-tool"}function XE(e){return Fy(e)||eKe(e)}function K$(e){return e.type.split("-").slice(1).join("-")}function tKe({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 nKe({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(Fy).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=>Fy(k)&&k.toolCallId===w.toolCallId),j=w,_=C;C!=null?(C.state=w.state,_.input=j.input,_.output=j.output,_.errorText=j.errorText,_.rawInput=j.rawInput,_.preliminary=j.preliminary,_.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,_=C;C!=null?(C.state=w.state,_.toolName=w.toolName,_.input=j.input,_.output=j.output,_.errorText=j.errorText,_.rawInput=(S=j.rawInput)!=null?S:_.rawInput,_.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?wJ(u.message.metadata,w):w;t!=null&&await W$({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(Fy);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 SJ(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:K$(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:K$(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(QZe(a)){(n==null?void 0:n[a.type])!=null&&await W$({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 rKe({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()}}Tx({prefix:"aitxt",size:24});Tx({prefix:"aiobj",size:24});var sKe=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()})}};Tx({prefix:"aiobj",size:24});var oKe={};BZe(oKe,{object:()=>aKe,text:()=>iKe});var iKe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),aKe=({schema:e})=>{const t=LZe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await SJ(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 _w({text:n});if(!s.success)throw new G$({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 lI({value:s.value,schema:t});if(!o.success)throw new G$({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}}},lKe=$f({name:$e(),version:$e()}),uI=$f({_meta:pr(qt({}).loose())}),mb=uI,cKe=qt({method:$e(),params:pr(uI)}),uKe=$f({experimental:pr(qt({}).loose()),logging:pr(qt({}).loose()),prompts:pr($f({listChanged:pr(wr())})),resources:pr($f({subscribe:pr(wr()),listChanged:pr(wr())})),tools:pr($f({listChanged:pr(wr())}))});mb.extend({protocolVersion:$e(),capabilities:uKe,serverInfo:lKe,instructions:pr($e())});var dKe=mb.extend({nextCursor:pr($e())}),fKe=qt({name:$e(),description:pr($e()),inputSchema:qt({type:ut("object"),properties:pr(qt({}).loose())}).loose()}).loose();dKe.extend({tools:ru(fKe)});var hKe=qt({type:ut("text"),text:$e()}).loose(),pKe=qt({type:ut("image"),data:nJ(),mimeType:$e()}).loose(),CJ=qt({uri:$e(),mimeType:pr($e())}).loose(),mKe=CJ.extend({text:$e()}),gKe=CJ.extend({blob:nJ()}),bKe=qt({type:ut("resource"),resource:Ar([mKe,gKe])}).loose();mb.extend({content:ru(Ar([hKe,pKe,bKe])),isError:wr().default(!1).optional()}).or(mb.extend({toolResult:uo()}));var GS="2.0",xKe=qt({jsonrpc:ut(GS),id:Ar([$e(),hb().int()])}).merge(cKe).strict(),yKe=qt({jsonrpc:ut(GS),id:Ar([$e(),hb().int()]),result:mb}).strict(),vKe=qt({jsonrpc:ut(GS),id:Ar([$e(),hb().int()]),error:qt({code:hb().int(),message:$e(),data:pr(uo())})}).strict(),wKe=qt({jsonrpc:ut(GS)}).merge(qt({method:$e(),params:pr(uI)})).strict();Ar([xKe,wKe,yKe,vKe]);async function SKe(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 CKe=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 wf(this.body),l=await wf(this.headers),u=await wf(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:U$({"Content-Type":"application/json",...h},`ai-sdk/${Z$}`,H$()),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 wf(this.body),a=await wf(this.headers),l=await wf(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:U$(f,`ai-sdk/${Z$}`,H$()),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)}},dI=class extends CKe{constructor(e={}){super(e)}processResponseStream(e){return YGe({stream:e,schema:XZe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},NKe=class{constructor({generateId:e=PGe,id:t=e(),transport:n=new dI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new sKe,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 SKe(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=>XE(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=>XE(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:tKe({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 rKe({stream:nKe({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 jKe({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(XE);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function kKe(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 EKe=kKe;const _Ke=zc(EKe);var NJ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(NJ(e,t,"read from private field"),n?n.call(e):t.get(e)),Yi=(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)},Wl=(e,t,n,r)=>(NJ(e,t,"write to private field"),t.set(e,n),n);function MKe(e,t){return t!=null?_Ke(e,t):e}var ko,$y,Ly,Fm,$m,Lm,Ef,QE,JE,DKe=class{constructor(e=[]){Yi(this,ko,void 0),Yi(this,$y,"ready"),Yi(this,Ly,void 0),Yi(this,Fm,new Set),Yi(this,$m,new Set),Yi(this,Lm,new Set),this.pushMessage=t=>{Wl(this,ko,Tn(this,ko).concat(t)),Tn(this,Ef).call(this)},this.popMessage=()=>{Wl(this,ko,Tn(this,ko).slice(0,-1)),Tn(this,Ef).call(this)},this.replaceMessage=(t,n)=>{Wl(this,ko,[...Tn(this,ko).slice(0,t),this.snapshot(n),...Tn(this,ko).slice(t+1)]),Tn(this,Ef).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?MKe(t,n):t;return Tn(this,Fm).add(r),()=>{Tn(this,Fm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,$m).add(t),()=>{Tn(this,$m).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Lm).add(t),()=>{Tn(this,Lm).delete(t)}),Yi(this,Ef,()=>{Tn(this,Fm).forEach(t=>t())}),Yi(this,QE,()=>{Tn(this,$m).forEach(t=>t())}),Yi(this,JE,()=>{Tn(this,Lm).forEach(t=>t())}),Wl(this,ko,e)}get status(){return Tn(this,$y)}set status(e){Wl(this,$y,e),Tn(this,QE).call(this)}get error(){return Tn(this,Ly)}set error(e){Wl(this,Ly,e),Tn(this,JE).call(this)}get messages(){return Tn(this,ko)}set messages(e){Wl(this,ko,[...e]),Tn(this,Ef).call(this)}};ko=new WeakMap;$y=new WeakMap;Ly=new WeakMap;Fm=new WeakMap;$m=new WeakMap;Lm=new WeakMap;Ef=new WeakMap;QE=new WeakMap;JE=new WeakMap;var _f,X$=class extends NKe{constructor({messages:e,...t}){const n=new DKe(e);super({...t,state:n}),Yi(this,_f,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,_f)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,_f)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,_f)["~registerErrorCallback"](r),Wl(this,_f,n)}};_f=new WeakMap;function jJ({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new X$(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new X$(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 TKe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function RKe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function IKe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function AKe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function kJ(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:AKe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function EJ(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 PKe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=J(x=>x.dashboard.aiScopeTables),r=(b=Uw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=jJ({transport:new dI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Bi.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:eW(x)}})}),onToolCall:p,sendAutomaticallyWhen:jKe,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:kJ(n||[])}}),x.toolName==="getDashboardContext"){const y=J.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=EJ(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function _J(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=Uw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=bn({queryKey:["assistant-profile",n],queryFn:()=>qn(`${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 MJ({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(W6,{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 Mw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(z_,{className:r});case"view":return c.jsx(vc,{className:r});case"materialized view":return c.jsx(oie,{className:r});case"model":return c.jsx(Xw,{className:r});case"file":return c.jsx(Ti,{className:r});case"dataset":return c.jsx(hl,{className:r});case"upload":return c.jsx(U_,{className:r});case"url":return c.jsx(t8,{className:r});default:return c.jsx(Kw,{className:r})}}const DJ=M.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Ea,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(us.Input,{ref:n,className:K("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})]}));DJ.displayName=us.Input.displayName;const ly=e=>e.label||(e==null?void 0:e.name),Q$=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function OKe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),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=ly(C).toLowerCase(),_=Q$(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||_.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(ly(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>ly(j)===m);C&&(o.some(_=>"id"in C&&"id"in _?C.id===_.id:C.name===_.name&&C.connectionId===_.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(ES,{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(DJ,{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(jr,{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(_S,{className:"min-h-60",children:[c.jsx(MS,{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(jr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(DS,{children:b.map((C,j)=>{const _=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,E=ly(C);return c.jsxs(TS,{value:E,onSelect:()=>{_?n==null||n(C):t(C)},onMouseDown:T=>{T.preventDefault(),T.stopPropagation()},className:K("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:Mw(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:Q$(C)})]}),_&&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 e_=e=>e.name||e.name,FKe=e=>{const t=e_(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 $Ke({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(er,{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(wn,{children:[c.jsx(Sn,{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:[Mw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:e_(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(En,{side:"top",className:"max-w-xs",children:FKe(d)})]},h)}),u&&c.jsxs(wn,{open:s,onOpenChange:o,children:[c.jsx(Sn,{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(T_,{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(En,{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:Mw(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:e_(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 TJ(e){return e.type==="dataset"&&e.label||e.name}function LKe(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 zKe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(le,{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,"]"]}),TJ(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 BKe(e){const{tokenProps:t}=Ge(),n=J(l=>l.authToken)||e;ke(l=>l.selectedConnectionId),ke(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}=bn({queryKey:["semantic-domains"],queryFn:()=>qn(`${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 VKe(e,t){const{tokenProps:n}=Ge(),r=J(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=bn({queryKey:["datasets",e],queryFn:()=>qn(`${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 HKe(e){var g,b;const{tokenProps:t}=Ge(),n=J(x=>x.authToken)||e,{connections:r}=zi(e),s=ke(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}=bn({queryKey:["databases",s],queryFn:()=>qn(`${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 UKe(e){var g;const{tokenProps:t}=Ge(),n=J(b=>b.authToken)||e,{connections:r}=zi(e),s=ke(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=ke(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}=bn({queryKey:["schemas",s,o],queryFn:()=>qn(`${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 RJ(e){const{tokenProps:t}=Ge(),n=J(h=>h.authToken)||e,{connections:r}=zi(e),s=ke(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}=bn({queryKey:["dataModels",s],queryFn:()=>qn(`${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 WKe(){var S,C,j;const e=ke(_=>_.card.dataSource);ke(_=>_.actions.updateDirectSource);const t=ke(_=>_.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=zi(),{databases:i,isPending:a,error:l,label:u}=HKe(),{schemas:d,isPending:f,error:h,label:p}=UKe(),{error:m}=RJ(),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=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:_},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(le,{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(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(le,{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(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function qKe(){const e=ke(l=>l.card.dataSource),t=ke(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(le,{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(U_,{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(le,{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(Ti,{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 YKe(){const e=ke(f=>f.card.dataSource),t=ke(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(le,{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(le,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Cn,{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(le,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Cn,{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(le,{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(jr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(le,{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(Kw,{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 GKe(e,t){var y,v;const{tokenProps:n}=Ge(),r=J(w=>w.authToken)||t,{connections:s}=zi(t),o=ke(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=ke(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=ke(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}=bn({queryKey:[e,o,i,a],queryFn:()=>qn(`${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 Dw({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(md,{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 ZKe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=zi(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=cr(),{entities:m,isLoading:g,error:b}=GKe("table"),{dataModels:x,isPending:y,error:v}=RJ(),w=E=>{const T=s.find(O=>O.id===E);if(!T)return;const R=T.type==="upload"?"upload":T.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:T.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(E)},S=E=>{var D,I;const T=n||[],R=T.some(F=>F.name===E.name&&F.type===E.type);let O;if(R)O=T.filter(F=>!(F.name===E.name&&F.type===E.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((D=e.dbSelection)==null?void 0:D.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:E.name,dialect:E.dialect};O=[...T,F]}t==null||t(O)},C=E=>{const T=n||[],R=T.some(D=>D.type==="model"&&D.name===E.name);let O;R?O=T.filter(D=>!(D.type==="model"&&D.name===E.name)):O=[...T,E],t==null||t(O)},j=m.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),_=x.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const E=n||[];let T=[...E];if(d==="tables"){const O=j.filter(D=>!E.some(I=>I.name===D.name&&I.type==="table")).map(D=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:D.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:D.name,dialect:D.dialect}});T=[...E,...O]}else if(d==="datamodels"){const R=_.filter(O=>!E.some(D=>D.name===O.name&&D.type==="model"));T=[...E,...R]}t(T)},[d,j,_,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(le,{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(E=>c.jsx(pe,{className:"hover:bg-muted",value:E.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(hl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:E.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(qKe,{}),e.connectionType==="url"&&c.jsx(YKe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(WKe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(ls,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ut,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ut,{value:"datamodels",children:["Data Models (",_.length,")"]})]}),c.jsxs(Yn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.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(Dw,{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(E=>{const T=n.some(R=>R.name===E.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(E),children:[c.jsx(un,{id:`table-${E.name}`,checked:T,onCheckedChange:()=>S(E),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(le,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),c.jsxs(Yn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:E=>u(E.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(Dw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(E=>{const T=n.some(R=>R.name===E.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(E),children:[c.jsx(un,{id:`dataModel-${E.name}`,checked:T,onCheckedChange:()=>C(E),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(le,{className:"cursor-pointer",children:E.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function KKe({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}=BKe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=VKe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],_=j.some(E=>E.id===C.id&&E.type==="dataset");let k;if(_)k=j.filter(E=>!(E.id===C.id&&E.type==="dataset"));else{const E={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,E]}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||[],_=v.filter(E=>!C.some(T=>T.id===E.id&&T.type==="dataset")).map(E=>({id:E.id,datasetType:E.type,name:E.name||E.table,label:E.label,domainId:E.domainId,description:E.description,database:E.database,schema:E.schema,type:"dataset",connectionId:E.connectionId,connectionType:E.connectionType,dialect:E.dialect,datamodelId:E.datamodelId,sql:E.sql})),k=[...C,..._];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(le,{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(Dw,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(le,{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(Dw,{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(_=>_.id===C.id&&_.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(un,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:_=>_.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(le,{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 fI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=cr(),d=J(T=>T.isVisualEditing),f=J(T=>T.dashboard.aiContext),{setAiContext:h}=Gt(),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(T=>{const R=T;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(T=>{u({...n,...T})},[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=T=>{const R=a.filter(O=>!(O.name===T.name&&O.type===T.type));l(R)},C=()=>{l([])},j=N.useCallback(T=>{l(T)},[]),_=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(T=>{p.current=T,g(!0)},[]);function E(){var T,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(T=a==null?void 0:a[0])==null?void 0:T.connectionId,D=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:D,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(as,{open:e,onOpenChange:t,children:c.jsx(Br,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Vr,{className:"flex-shrink-0",children:[c.jsx(Hr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Ds,{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(ls,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsx(Ut,{value:"database",children:"Direct Source"}),c.jsx(Ut,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(KKe,{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(ZKe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(zKe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ms,{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:_,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:E,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function XKe({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=Ya-n;if(l.length>u){ze.error(`You can only attach ${Ya} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=pQ(l);if(f.forEach(({file:h,error:p})=>{ze.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>JR(p)));e(h)}catch(h){console.error("Failed to process files:",h),ze.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ya}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ya,title:n>=Ya?`Maximum ${Ya} files allowed`:"Attach files",children:c.jsx(O_,{className:"h-4 w-4 text-muted-foreground"})})]})}function QKe({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=Ya-r;if(h.length>p){ze.error(`You can only attach ${Ya} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=pQ(h);if(g.forEach(({file:b,error:x})=>{ze.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>JR(x)));t(b),ze.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),ze.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:K("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(U_,{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:[Ya-r," slot(s) available"]})]})})]})}const hI=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=_p();sCe(),rCe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=F1(),{queueMessage:C}=Mp(),{addFileAttachment:j,removeFileAttachment:_,clearFileAttachments:k,getFileAttachments:E}=DD(),T=MD(l),R=ke(z=>z.card.dataSource),O=J(z=>z.dashboard.aiContext),D=J(z=>{var G;return(G=z.dashboard.aiContext)==null?void 0:G.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const z=b.current;if(z){if(!e||e.length===0){z.style.height="10px";return}z.style.height="auto";const G=Math.min(Math.max(z.scrollHeight,10),200);z.style.height=`${G}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const z=setTimeout(()=>{I()},0);return()=>clearTimeout(z)},[I]);const F=()=>{const z=e.trim();!z&&T.length===0||(a!=="ready"?(C(l,z,T),t(""),k(l)):r({preventDefault:()=>{}}))},B=z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),F()),z.key==="@"&&(U(),f(!0))},V=N.useCallback(z=>{const G=fUe(z.nativeEvent);G.length>0&&(z.preventDefault(),G.forEach(async Z=>{const te=await JR(Z);j(l,te)}))},[j,l]),$=N.useCallback(z=>{z.forEach(G=>{j(l,G)})},[j,l]),P=N.useCallback(z=>{z.forEach(G=>{j(l,G)})},[j,l]),H=N.useCallback(z=>{_(l,z)},[_,l]),L=z=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===z.id||Z.name===z.name)){const Z=x.selectedEntities.filter(te=>!(te.id&&te.id===z.id||te.name===z.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,z];y({selectedEntities:Z})}},A=z=>{L(z)},W=z=>{var te;if(!x.selectedEntities.some(X=>X.id&&X.id===z.id||X.name===z.name)){const X=[...x.selectedEntities,z];y({selectedEntities:X})}const Z="label"in z?z.label:z.name;t(e+`@${Z} `),f(!1),(te=b.current)==null||te.focus()},q=z=>{const G=x.selectedEntities.filter(X=>!(X.id&&X.id===z.id||X.name===z.name));y({selectedEntities:G});const te=`@${"label"in z?z.label:z.name}`;e.includes(te)&&t(e.replace(te,"").trim())},Y=z=>{const G=new Set(z.map(X=>X.id||X.name)),Z=x.selectedEntities.filter(X=>!G.has(X.id||X.name));y({selectedEntities:Z});let te=e;z.forEach(X=>{const se=`@${"label"in X?X.label:X.name}`;te=te.replace(se,"").trim()}),t(te)},U=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(QKe,{onFilesDropped:$,currentFileCount:T.length,disabled:s,className:"space-y-4",children:[c.jsx($Ke,{entities:x.selectedEntities,availableEntities:D||[],onRemoveEntity:q,onRemoveEntities:Y}),T.length>0&&c.jsx(hUe,{files:T,onRemove:H,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:B,onPaste:V,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(Ss,{open:d,onOpenChange:z=>{z&&U(),f(z)},children:[c.jsx(Cs,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Xoe,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(Ns,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:z=>z.preventDefault(),children:c.jsx(OKe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var z;f(!1),(z=b.current)==null||z.focus()},availableEntities:D||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{D&&y({selectedEntities:D})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(XKe,{onFilesSelected:P,disabled:s,currentFileCount:T.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(mie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&T.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(fI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||WS,dialogMode:"aiContext"})]})});hI.displayName="ChatInputWithContext";function IJ({assistantType:e,className:t}){const n=tW(e),{removeFromQueue:r}=Mp();return n.length===0?null:c.jsxs("div",{className:K("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(vl,{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 AJ({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=tW(e),{dequeueMessage:o}=Mp();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 PJ(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:T=!1,instant:R=!1}=k;if(!T&&!y.current||!a&&!T)return;const O=R||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!T&&!y.current){b.current=!1,v.current=void 0;return}const D=i.current;if(!D){b.current=!1,v.current=void 0;return}const I=D.scrollHeight;O==="smooth"&&"scrollTo"in D?D.scrollTo({top:I,behavior:O}):D.scrollTop=I,g.current=D.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 E=g.current,T=k.scrollTop,R=T-E;if(g.current=T,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]),_=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 E=w.current,T=e[e.length-1],R=(T==null?void 0:T.id)??(T==null?void 0:T.messageId)??(T==null?void 0:T.createdAt)??(T==null?void 0:T.timestamp)??e.length,O=Array.isArray(T==null?void 0:T.parts)?T.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(T==null?void 0:T.content)=="string"?T.content.length:typeof(T==null?void 0:T.text)=="string"?T.text.length:0,D=e.length>E.count,I=R!==E.key,F=O>E.length,B=s&&(T==null?void 0:T.role)==="assistant"&&!D&&(I||F),V=o||B;if(w.current={key:R,count:e.length,length:O},a&&(D||I||F||V)){C({force:!1,instant:V});return}if(!a&&D){const $=e.length-E.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 E=new ResizeObserver(()=>{const T=i.current;if(!T)return;const R=x.current,O=T.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return E.observe(k),()=>{E.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:_}}function OJ(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 FJ(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:mQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const JKe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function eXe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Lw),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=ip(),y=N.useRef(null);J(Ve=>Ve.dashboard.aiScopeTables),J(Ve=>Ve.isDashboardEditing);const v=J(Ve=>Ve.selectedSheetId),{setDataSource:w}=cr(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Gt(),_=_p(),{setCurrentAIContext:k,updateSelectedEntities:E,setReasoningEffort:T,setShowReasoning:R}=F1(),{clearQueue:O}=Mp(),{clearFileAttachments:D,getFileAttachments:I}=DD(),F=MD("dashboard"),B=J(Ve=>Ve.dashboard.aiContext),V=ke(Ve=>Ve.card.dataSource),{assistantProfile:$}=_J(),P=J(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:H,isLoading:L,messages:A,setMessages:W,status:q,stop:Y,errorMessage:U,clearError:z}=PKe(),G=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),Z=N.useCallback(()=>{G(!g)},[g,G]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,G]);const[te,X]=N.useState(""),ne=Ve=>{X(Ve.target.value)};function se({sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:Ne,dataSource:De}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:Ne,dataSource:De}),!v)return;const Le={id:Dr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ke==="horizontalBar"?"y":"x"}},type:Ke,sql:Ve,python:ve,dataSource:De,config:Ne,connectionId:He},nt={id:Dr(),cards:[Le],activeCardId:Le.id};j(!0),S(v,nt,"end"),C(nt.id)}const ce=Ve=>{Ve.preventDefault();const Ue=te.trim();if(!Ue&&F.length===0)return;const ht=[];Ue&&ht.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&ht.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),H({role:"user",parts:ht}),X(""),D("dashboard"),re({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),AJ({assistantType:"dashboard",status:q,isLoading:L,sendMessage:H});const{hasActiveTools:ae}=FJ(A),{visibleMessages:he,hasMoreMessages:ye,totalMessageCount:Te,loadMoreMessages:_e,resetMessageWindow:de}=OJ(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:Oe,hasNewMessages:mt,newMessageCount:be,scrollToBottom:re,handleScroll:ue,resetNewMessageCount:we}=PJ(he,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ze();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};H(Ue)}function Pe(Ve){Ze(),H({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ze(),H({role:"user",parts:[{type:"text",text:Ve}]}),re({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),ze.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),ze.error("Unable to copy conversation")}},[A]);function Ze(){_.selectedEntities.length===0&&k({selectedEntities:(B==null?void 0:B.selectedEntities)||[]})}const Lt=(te==null?void 0:te.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ce(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Mt(){return c.jsxs(sp,{children:[c.jsx(op,{asChild:!0,children:c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Mb,{className:"size-3.5"})})}),c.jsxs(Vd,{align:"end",children:[c.jsx(Wf,{children:"Options"}),c.jsx(bd,{}),c.jsx(Hm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Hm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Hm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const fn=c.jsxs("div",{"data-role":"dashboard-assistant",className:K("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:[Ce(),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&&Mt(),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(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(P_,{className:"size-4"}):c.jsx(Qw,{className:"size-4"})}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),z(),de()},children:c.jsx(Jw,{className:"size-4"})}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(_l,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ue,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[ye&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:_e,className:"text-xs",children:["Load ",Math.min(5,Te-he.length)," ","more messages (",Te-he.length," ","hidden)"]})}),c.jsx(bQ,{showTools:a,showSystemMessage:u,messages:he,onAddToDashboard:se,onQuickReply:Qe,disableQuickReplies:L}),!ae&&c.jsx(gQ,{status:q,errorMessage:U})]}),c.jsx(Ko,{orientation:"horizontal"})]}),e&&!Oe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{re({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Gs,{className:"h-4 w-4"}),mt&&be>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:be>9?"9+":be})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&Lt&&c.jsx(xQ,{onClick:Se,placeholders:JKe}),c.jsx("div",{children:Lt&&$&&c.jsx(MJ,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(IJ,{assistantType:"dashboard",className:"mb-3"}),c.jsx(hI,{ref:y,setInput:X,stop:Y,input:te,handleInputChange:ne,handleSubmit:Ve=>{Ze(),ce(Ve),re({force:!0})},isLoading:L,status:q,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(fI,{incomingSelectedEntities:(B==null?void 0:B.selectedEntities)||[],open:f,onOpenChange:h,dataSource:V||WS,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:fn})}),s):fn}function tXe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Gt(),o=J(d=>d.dashboard.sheets),a=J(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=J(d=>d.isDashboardEditing),u=J(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),ze.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=$T(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),ze.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 nXe(e,t){switch(e.interactionMode){case"drillToDetail":rXe(e,t);break;case"drillThrough":sXe(e,t);break;case"drillToURL":oXe(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 rXe(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 sXe(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 oXe(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 iXe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Br,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Vr,{children:[c.jsx(Hr,{children:i||"Insight Detail"}),c.jsx(Ds,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(DZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(RZ,{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 aXe(){const e=zt(w=>w.interactionStates),t=zt(w=>w.setInteractionState),n=zt(w=>w.clearLastInteractionEvent),r=zt(w=>w.replaceCardWithInsight),s=zt(w=>w.setPendingDrillThrough),o=zt(w=>w.pendingDrillThrough),i=zt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Gt(),{selectDashboard:u}=_b(),d=J(w=>w.dashboard),f=J(w=>w.filterValues),{data:h,isLoading:p}=fde((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=IZ(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:_})=>{const E={sourceCardId:da,interactionMode:"clickFilter",filterGroups:[{filters:w}]},T={...Po(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:_};t(da,T)}}),[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{nXe(C,y)}catch(_){console.error("Error executing interaction event:",_)}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(iXe,{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 lXe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=cXe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function cXe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function uXe(e){return e?`Back to ${e}`:"Back"}function dXe(){var x,y,v,w,S;const e=zt(C=>C.interactionStates[da]),t=J(C=>C.actions.goBackFromDrill),n=J(C=>C.actions.clearDrillContext),{selectDashboard:r}=_b(),[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=_=>{o({x:_.clientX-l.current.x,y:_.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})};lXe(f);const b=uXe(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 _=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[_," = ",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(I6,{className:"mr-2 h-4 w-4"}),b]})})]})})}function $J(){var U;const{showAssistant:e}=Ge(),{preferences:t}=ip(),n=((U=t==null?void 0:t.cardDisplay)==null?void 0:U.mode)==="print",r=N.useRef(null),s=N.useRef(null),[o,i]=N.useState(!1),a=nd(z=>z.setFullscreen),l=nd(z=>z.setPanelOpen),u=nd(z=>z.setContainer),d=XU("dashboard"),f=QU(),h=JU("dashboard"),p=d.isOpen,m=f==="dashboard",g=J(z=>z.isVisualEditing),b=J(z=>z.themeStyle),x=J(z=>{var G;return(G=z.dashboard)==null?void 0:G.sheets}),y=J(z=>z.isDashboardEditing),v=J(z=>z.selectedSheetId),w=J(z=>{var G;return(G=z.dashboard)==null?void 0:G.id}),{getDefaultSheetId:S,setDefaultSheetId:C,clearDefaultSheetId:j}=b6(w),[_,k]=N.useState(null),{setSelectedSheetId:E,setSheetTitle:T,addSheet:R,setSheets:O}=Gt();tXe(s);const{setActiveAssistantType:D}=F1();N.useEffect(()=>{if(w){const z=S();k(z)}},[w,S]),N.useEffect(()=>{p?D("dashboard"):f==="dashboard"&&a(null)},[p,D,f,a]);function I(z){var G,Z;z?((G=r.current)==null||G.resize(40),l("dashboard",!0),D("dashboard")):(l("dashboard",!1),a(null),(Z=r.current)==null||Z.resize(0),D(null))}function F(){const z={id:Dr(),title:"New Sheet"};R(z),E(z.id)}function B(z,G){if(!w)return;_===z?(j(),k(null),ze.success("Default sheet cleared")):(C(z),k(z),ze.success(`"${G}" set as default sheet`))}function V(z){z<1?(l("dashboard",!1),a(null),D(null)):(p||l("dashboard",!0),D("dashboard"))}function $(){return(b==null?void 0:b.canvasTheme)==="muted"||!(b!=null&&b.canvasTheme)?"hsl(var(--semaphor-muted))":(b==null?void 0:b.canvasTheme)==="clear"?"":b==null?void 0:b.canvasTheme}const P=(z,G)=>{z.dataTransfer.setData("tabIndex",G.toString())},H=z=>{z.preventDefault()},L=(z,G)=>{const Z=z.dataTransfer.getData("tabIndex");if(Z===G.toString())return;const te=Array.from(x||[]),[X]=te.splice(parseInt(Z),1);te.splice(G,0,X),O(te)};function A(){var z,G;if(x&&x.length>1||y)return c.jsxs(Ur,{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:[x==null?void 0:x.map((Z,te)=>{const X=v===Z.id,ne=_===Z.id;return c.jsxs(Ut,{draggable:!0,onDragStart:se=>P(se,te),onDragOver:H,onDrop:se=>L(se,te),style:{borderRadius:b==null?void 0:b.controlInputRadius},onClick:()=>E(Z.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:Z.id,children:[c.jsx(Gg,{enabled:y&&X,text:Z.title,onSave:se=>T(Z.id,se),children:Z.title},Z.id),!y&&X&&c.jsx("div",{title:ne?"Clear default sheet":"Set as default sheet",children:c.jsx(xie,{className:K("ml-1 size-3 cursor-pointer transition-all",ne?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:se=>{se.stopPropagation(),B(Z.id,Z.title||"Sheet")}})}),y&&X&&x.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>i(!0)})]},Z.id)}),y&&c.jsx("div",{style:{borderRadius:(G=(z=b==null?void 0:b.chart)==null?void 0:z.options)==null?void 0:G.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:F,children:c.jsx(jr,{className:"size-3"})})]})}function W(){return c.jsx("div",{ref:s,style:{},className:"grow",children:x==null?void 0:x.map(z=>c.jsx(Yn,{style:{backgroundColor:$()},className:K("mt-0",{}),value:z.id,children:c.jsx(_Le,{sheet:z})},z.id))})}function q(){var z;return c.jsxs(ls,{"data-role":"dashboard-tabs-container",className:K("relative flex h-full flex-col",b==null?void 0:b.dashboardTabsContainer),onValueChange:G=>{E(G)},value:v||((z=x==null?void 0:x[0])==null?void 0:z.id),children:[A(),c.jsx(_l,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:W()}),c.jsx(i6e,{open:o,setOpen:i})]})}const Y=N.useCallback(z=>{u("dashboard",z)},[u]);return x?c.jsxs(c.Fragment,{children:[c.jsx(aXe,{}),c.jsx(dXe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(TR,{className:K("flex-1 basis-0 overflow-y-auto transition-opacity",m&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(ib,{children:q()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(o6e,{open:p,onTabClick:I,withHandle:!0}),c.jsx(ib,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:V,defaultSize:p?40:0,ref:r,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(eXe,{open:p,setOpen:I,isFullscreen:m,onFullscreenChange:z=>a(z?"dashboard":null),fullscreenContainer:h})})})]})]}),c.jsx("div",{ref:Y,className:K("absolute inset-0",!m&&"pointer-events-none")}),e===!0&&!n&&!p&&!g&&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:()=>I(!0),title:"Open Assistant",children:c.jsx(L_,{className:"h-5 w-5"})})})]})]}):null}function pI({children:e}){return c.jsx(Da,{style:{height:"100%",width:"100%"},children:c.jsx(fre,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(er,{delayDuration:0,children:e})})})}function LJ({children:e,preferences:t}){const{currentUser:n}=_s(),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(t9.Provider,{value:r,children:c.jsx(oR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function zJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Dl,{FallbackComponent:oS,children:c.jsx(k_,{dashboardProps:e,children:c.jsx(pI,{children:c.jsx(LJ,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(TD,{...e,type:"dashboard",children:c.jsx($J,{})})})})})})})}function mI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return bn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return qn(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 BJ(e,t,n){if(t==="source")return{isValid:!0};const r=Xs(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 VJ(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 HJ=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=mI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=cr(),h=ke(D=>D.card.type),p=e==null?void 0:e.id,m=N.useCallback(D=>{if(!(e!=null&&e.config))return[];switch(D){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((D,I)=>{if(p)switch(D){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((D,I,F)=>{if(!p)return;const V=m(D)[I];if(V)switch(D){case"groupBy":s(p,V.id,{label:F});break;case"metrics":o(p,V.id,{label:F});break;case"pivotBy":i(p,V.id,{label:F});break;case"sortBy":a(p,V.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((D,I)=>{if(!p)return;const B=m("metrics")[D];B&&o(p,B.id,{aggregate:I,label:MH(B.name,I)})},[p,m,o]),y=N.useCallback((D,I,F)=>{if(!p)return;const V=m("groupBy")[D];if(!V)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,V.id,$)},[p,m,s]),v=N.useCallback((D,I)=>{if(!p)return;const B=m("groupBy")[D];B&&s(p,B.id,{granularity:I})},[p,m,s]),w=N.useCallback((D,I)=>{if(!p)return;const B=m("metrics")[D];B&&o(p,B.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((D,I)=>{if(console.log("handleValueAliasesChange",D,I),!p)return;console.log("handleValueAliasesChange",D,I);const B=m("metrics")[D];B&&(console.log("handleValueAliasesChange",I),o(p,B.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(D=>{if(!p)return;if(m("metrics").length===0){ze.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:D})},[p,r,m]),j=N.useCallback(D=>{p&&r(p,{showTrendline:D})},[p,r]),_=N.useCallback(D=>{p&&r(p,{trendlineWindow:D})},[p,r]),k=N.useCallback(D=>{p&&r(p,{trendlineGranularity:D})},[p,r]),E=N.useCallback(D=>{p&&r(p,{targetValue:D})},[p,r]),T=N.useCallback(D=>{var H;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=_1e(D,I,{joinPlan:(H=e==null?void 0:e.config)==null?void 0:H.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&kH();return}const B=T1e(D,I,h);if(!B){ze.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const V=BJ(D,B,h);if(!V.isValid){ze.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3});return}const $=m(B);if(EH(D,$))return;const P=DH(D,B,$);if(P){const L=[...$,P];g(B,L),B==="metrics"&&VJ(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((D,I)=>{if(!p)return;const B=m(D)[I];if(B){if(D!=="sortBy"){const V=m("sortBy"),$=V.filter(P=>!(P.name===B.name&&P.qualifiedEntityName===B.qualifiedEntityName));$.length!==V.length&&r(p,{sortByColumns:$})}switch(D){case"groupBy":l(p,B.id);break;case"metrics":u(p,B.id);break;case"pivotBy":d(p,B.id);break;case"sortBy":f(p,B.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:T,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:E,cardType:h}};function Rx(e,t){var Pe,Qe,Nt,Ze,Lt;const{tokenProps:n}=Ge(),r=Co(),s=Ge().authToken||e,o=ke(Ce=>Ce.selectedConnectionId),i=ke(Ce=>Ce.card),{queryKey:a}=Phe(i),l=ke(Ce=>Ce.selectedDatamodelId),u=ke(Ce=>Ce.isDevMode),d=ke(Ce=>Ce.selectedDatabaseName),f=ke(Ce=>Ce.selectedSchemaName),h=ke(Ce=>Ce.selectedTableName),p=ke(Ce=>Ce.actions.setSelectedConnectionId),m=ke(Ce=>Ce.actions.setSelectedDatamodelId),g=ke(Ce=>Ce.actions.setSelectedDatabaseName),b=ke(Ce=>Ce.actions.setSelectedSchemaName),x=ke(Ce=>Ce.actions.setSelectedTableName);ke(Ce=>Ce.actions.setCardSql);const{setQueryConfig:y}=cr();function v(Ce){var fn;return o&&Ce==="API"?!1:o&&Ce==="S3"?!0:!(!o||!d||d==="NA"||((fn=k==null?void 0:k.capabilities)==null?void 0:fn.path.includes("schema"))&&!f)}function w(Ce){return o&&Ce?!(Ce==="API"||Ce==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:_,selectedConnection:k}=zi(e),{refetch:E,data:T,isLoading:R,isError:O}=bn({queryKey:["models",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),D=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:B,isFetching:V,isError:$,refetch:P}=bn({queryKey:["databases",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(D)}),{data:H,isLoading:L,isFetching:A,isError:W,refetch:q}=bn({queryKey:["schemas",o,d],queryFn:()=>qn(`${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:U,isFetching:z,isError:G,refetch:Z}=bn({queryKey:["tables",o,d,f],queryFn:()=>qn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(D)}),{columns:te,isColumnsLoading:X,isColumnsFetching:ne,isColumnsError:se,refetchColumns:ce}=TH(e);N.useEffect(()=>{(D==="S3"||D==="API")&&(g(""),b(""),m(""),D==="API"&&x("api"))},[D,x,g,b,m]);const ae=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",he=I?"":f||"";function ye(Ce){x(Ce),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Te(Ce){b(Ce),x("")}function _e(Ce){g(Ce==="none"?"":Ce),b(""),x(""),Ce!=="none"&&Ce!==""&&m("")}function de(Ce){p(Ce)}function Re(Ce){m(Ce==="none"?"":Ce),Ce!=="none"&&Ce!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,H&&((Nt=H==null?void 0:H.schemas)==null?void 0:Nt.length)>0;const Oe=C==null?void 0:C.connections.map(Ce=>({id:Ce.id,name:Ce.name,type:Ce.type})),mt=(Ze=T==null?void 0:T.datamodels)==null?void 0:Ze.map(Ce=>({id:Ce.id,name:Ce.name})),be=F==null?void 0:F.databases.map(Ce=>({id:Ce.database_name,name:Ce.database_name})),re=H==null?void 0:H.schemas.map(Ce=>({id:Ce.schema_name,name:Ce.schema_name})),ue=Y==null?void 0:Y.tables.map(Ce=>({id:Ce.table_name,name:Ce.table_name})),we=(Lt=T==null?void 0:T.datamodels.find(Ce=>Ce.id===l))==null?void 0:Lt.name,Se=Uy({schemaName:he,tableName:ae,modelName:we,connectionType:D,databaseName:d||""});return{connectionItems:Oe,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:_,modelItems:mt,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:be,isDatabasesLoadingOrFetching:B||V,isDatabaseError:$,schemaItems:re,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:ue,selectedTableName:h,isTableLoadingOrFetching:U||z,isTableError:G,columns:te,isColumnsLoadingOrFetching:X||ne,isColumnsError:se,isNonDbConnection:I,connectionType:D,tableName:ae,formattedTableName:Se,schemaName:he,refetchConnections:S,refetchModels:E,refetchDatabases:P,refetchSchemas:q,refetchTables:Z,refetchColumns:ce,handleConnectionChange:de,handleDatamodelChange:Re,handleDatabaseChange:_e,handleSchemaChange:Te,handleTableChange:ye}}function cy(e){return`${e}-${Dr()}`}function J$(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 fXe(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 gI(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 UJ(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function WJ(){const e=ke(C=>C.sqlGen),t=ke(C=>C.isDevMode),n=ke(C=>C.card.dataSource),r=ke(C=>{var j,_;return(_=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=gI(n),a=UJ(n),l=ke(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=cr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Rx(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var _;if(!t)return;const j=y(C);if(t&&a&&s){const k=b_(j,e);p(k);const E=(_=b==null?void 0:b.find(R=>R.id===l))==null?void 0:_.name,T=g_(k,bi(o||""),bi(s),E||"",g,i||"");T&&(f(T),h(!0))}else if(!t){if(kb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:cy(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:cy(j.column_name),name:j.column_name,label:J$(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Bc(j.data_type)){const k={...j,role:"groupby",id:cy(j.column_name),name:j.column_name,type:j.data_type,label:fXe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:cy(j.column_name),name:j.column_name,label:J$(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=Uy({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=Uy({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 qJ(){const e=ke(m=>m.selectedConnectionId),t=ke(m=>m.selectedDatamodelId),n=ke(m=>m.selectedDatabaseName),r=ke(m=>m.selectedSchemaName),s=ke(m=>m.selectedTableName),o=J(m=>m.dashboard.filters)||[],i=J(m=>m.selectedSheetId),a=J(m=>m.actions.addFilter),l=J(m=>m.actions.removeFilter),{removeFilterValues:u}=Gt(),{modelItems:d,tableName:f,connectionType:h}=Rx();function p(m,g="sheet",b){var k;const x=bi(m.column_name),y=bi(n||""),v=bi(r||""),w=bi(f);let S=zw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(E=>E.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${xg}.${j}.${x}`,S=`${xg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let _;if(g==="sheet"&&i?_=ije(o,C,w,n||"",y,i):_=o==null?void 0:o.find(E=>E.column===C&&E.table===w&&(E.database===y||E.database===n)),_)u(_.id),l(_.id);else{const E=Dr(),T=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:T,sql:w4(m.data_type,S,x)}),E):(a({id:E,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:T,sql:w4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),E)}}return{assignFilter:p}}function hXe({column:e}){const[t,n]=N.useState(!1),r=ke(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=gI(r),a=ke(x=>x.selectedDatamodelId),l=ke(x=>x.sqlGen),{modelItems:u,connectionType:d}=Rx(),f=ke(x=>x.actions.setSqlGen),h=ke(x=>x.actions.setCardSql),p=ke(x=>x.actions.setRunSql),m=UJ(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=b_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=g_(v,bi(o||""),bi(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(jp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(kp,{asChild:!0,children:c.jsx(Mb,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Gd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function pXe({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 mXe({field:e,context:t="editor",fieldState:n}){const r=ke(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=J(L=>L.dashboard.filters),a=J(L=>L.selectedSheetId),l=J(L=>L.actions.removeFilter),{removeFilterValues:u}=Gt(),{assignFilter:d}=qJ(),f=s?Xc(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:_,isDragging:k}=jS({id:e.id,disabled:o}),[E,T]=N.useState(!1),R=ke(L=>L.card),{handleFieldClick:O}=HJ(R),{handleDevModeFieldClick:D,isNumberField:I}=WJ(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},B=()=>{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?D(e):O(e)},V={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:Pi.Transform.toString(j),transition:_},H=(()=>{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:K("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",H.borderColor||"border-transparent",H.bgColor||"",H.hoverBorderColor,H.hoverBgColor||"hover:bg-muted",H.opacity,H.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:B,children:[Jg(e.dataType),c.jsx(er,{children:c.jsxs(wn,{children:[c.jsx(Sn,{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 ${E?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(En,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(pXe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(hXe,{column:V})})]}),E&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Mi,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(c8,{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(vie,{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($b,{open:b,onOpenChange:x,children:c.jsxs(ap,{children:[c.jsxs(lp,{children:[c.jsx(up,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(dp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(cp,{children:[c.jsx(hp,{children:"Cancel"}),c.jsx(fp,{onClick:F,children:"Remove Filter"})]})]})})]})}const gXe="SEMAPHOR_CALCULATED_FIELD",bXe=["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 YJ(e){return!!e.expression}function xXe(e){return!!e.expression}function yXe(e){return!!e.expression}var GJ=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(GJ||{}),Al="Accordion",vXe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[bI,wXe,SXe]=t1(Al),[ZS]=Er(Al,[SXe,FZ]),xI=FZ(),ZJ=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(bI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(kXe,{...o,ref:t}):c.jsx(jXe,{...s,ref:t})})});ZJ.displayName=Al;var[KJ,CXe]=ZS(Al),[XJ,NXe]=ZS(Al,{collapsible:!1}),jXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=Fr({prop:n,defaultProp:r,onChange:s});return c.jsx(KJ,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(XJ,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(QJ,{...i,ref:t})})})}),kXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=Fr({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(KJ,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(XJ,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(QJ,{...o,ref:t})})})}),[EXe,KS]=ZS(Al),QJ=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=wXe(n),f=$d(s)==="ltr",h=je(e.onKeyDown,p=>{var _;if(!vXe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var E;return!((E=k.ref.current)!=null&&E.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;(_=g[j].ref.current)==null||_.focus()});return c.jsx(EXe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(bI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Tw="AccordionItem",[_Xe,yI]=ZS(Tw),JJ=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=KS(Tw,n),i=CXe(Tw,n),a=xI(n),l=rr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(_Xe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(zZ,{"data-orientation":o.orientation,"data-state":oee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});JJ.displayName=Tw;var eee="AccordionHeader",tee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(Al,n),o=yI(eee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":oee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});tee.displayName=eee;var t_="AccordionTrigger",nee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(Al,n),o=yI(t_,n),i=NXe(t_,n),a=xI(n);return c.jsx(bI.ItemSlot,{scope:n,children:c.jsx(T4e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});nee.displayName=t_;var ree="AccordionContent",see=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(Al,n),o=yI(ree,n),i=xI(n);return c.jsx(R4e,{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}})});see.displayName=ree;function oee(e){return e?"open":"closed"}var MXe=ZJ,DXe=JJ,TXe=tee,iee=nee,aee=see;const lee=MXe,vI=M.forwardRef(({className:e,...t},n)=>c.jsx(DXe,{ref:n,className:K("border-b",e),...t}));vI.displayName="AccordionItem";const wI=M.forwardRef(({className:e,children:t,...n},r)=>c.jsx(TXe,{className:"flex",children:c.jsxs(iee,{ref:r,className:K("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(Gs,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));wI.displayName=iee.displayName;const SI=M.forwardRef(({className:e,children:t,...n},r)=>c.jsx(aee,{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:K("pb-4 pt-0",e),children:t})}));SI.displayName=aee.displayName;function RXe({context:e="editor"}={}){var E,T,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");ke(D=>D.isDevMode);const o=ke(D=>D.card.dataSource),i=ke(D=>D.card.config),a=ke(D=>D.card),{autoJoinMetadata:l}=wa(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=hD(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=mI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(T=(E=i==null?void 0:i.joinPlan)==null?void 0:E.baseEntity)==null||T.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,WJ();const b=u.filter(D=>D.name.toLowerCase().includes(t.toLowerCase())||D.dataType.toLowerCase().includes(t.toLowerCase())||D.label&&D.label.toLowerCase().includes(t.toLowerCase())||D.qualifiedEntityName&&D.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=D=>{if(D.role==="metric"&&YJ(D)||D.role==="groupby"&&D.expression)return"calculated";if(D.dataType==="number"||D.dataType==="integer"||D.dataType==="float"||D.dataType==="decimal"||D.dataType==="currency")return"metrics";const I=Xs(D.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(D=>x(D)===r)).reduce((D,I)=>{const F=I.qualifiedEntityName||"Other Fields";return D[F]||(D[F]={label:y_(I.entityName),fields:[]}),D[F].fields.push(I),D},{}),S=Object.keys(v),C=b.filter(D=>x(D)==="dimensions").length,j=b.filter(D=>x(D)==="metrics").length,_=b.filter(D=>x(D)==="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(Tc,{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(hl,{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(Es,{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(hl,{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(Ea,{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:D=>n(D.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(ls,{defaultValue:"all",value:r,onValueChange:D=>s(D),className:"mb-4",children:c.jsxs(Ur,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ut,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ut,{value:"dimensions",className:"text-xs",children:[c.jsx(Xw,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ut,{value:"metrics",className:"text-xs",children:[c.jsx(Zh,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ut,{value:"calculated",className:"text-xs",children:[c.jsx(M_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]})]})})]}),c.jsxs(_l,{className:"py-2",children:[c.jsx(lee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([D,I])=>{const F=d.find(B=>B.entityName===D)||{entityName:D,label:I.label};return c.jsxs(vI,{value:D,className:"border-none",children:[c.jsx(wI,{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(SI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(B=>{const V=pD(B,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(mXe,{field:B,context:e,fieldState:V},B.id)})})})]},D)})}),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(Ko,{orientation:"horizontal"}),c.jsx(Ko,{orientation:"vertical"})]})]})}function cee({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(RXe,{context:e})," "]})}function uee(){const e=ke(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=cr();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=gI(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 IXe(){uee();const e=J(l=>l.selectedSheetId),t=J(l=>l.selectedFrameId),n=J(l=>l.dashboard),r=J(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Gt(),{setCard:o}=cr(),i=ke(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 AXe(){const e=J(n=>n.actions.setShowFilters),{hasEntities:t}=IXe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(le,{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(PZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(hl,{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",children:c.jsx(CS,{collisionDetection:yS,children:c.jsx(NS,{items:[],strategy:vR,children:c.jsx(cee,{context:"filter"})})})})]})}function PXe(){const e=J(r=>r.dashboard.filters),t=J(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:K("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(aR,{filter:r}),c.jsx(mS,{filter:r})]},r.id))}):null}function OXe(){const e=J(r=>r.showFilters),t=J(r=>r.isVisualEditing),n=J(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:K("",{"max-h-0 overflow-hidden":t,"flex grow overflow-auto":!t}),children:[c.jsxs("section",{className:"flex grow flex-col",children:[n&&c.jsx(PXe,{}),c.jsx($J,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex",children:c.jsx(AXe,{})})]})}const FXe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-hsJsvBAe.js"))),$Xe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BDVEh9_m.js"))),LXe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BVoJAaE6.js"))),zXe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-CMdBNTA3.js")).then(e=>({default:e.ResourceManagementPanel})));function BXe({showControls:e=!1,showFooter:t=!0,...n}){const r=J(m=>m.isDashboardPanelOpen),s=J(m=>m.isVisualEditing),o=J(m=>m.showDashboardJSON),i=J(m=>m.actions.setIsDashboardPanelOpen),a=20,l=20,u=30,d=r,f=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{f.current&&h.current&&(r?(f.current.resize(a),h.current.resize(100-a)):(f.current.resize(0),h.current.resize(100)))},[r]);const{preferences:p}=n;return c.jsx(Dl,{FallbackComponent:oS,children:c.jsxs(k_,{dashboardProps:n,children:[c.jsx(Que,{}),c.jsx(pI,{children:c.jsxs(LJ,{preferences:p,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(LXe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(FXe,{})}),c.jsxs(TR,{direction:"horizontal",className:"flex grow overflow-hidden",children:[c.jsx(ib,{ref:f,className:K("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?a:0,minSize:d?l:0,maxSize:d?u:0,children:d&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(zXe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})})}),c.jsx(JK,{className:K("",{"w-0":!d})}),c.jsx(ib,{ref:h,className:"flex min-w-0 flex-1",defaultSize:d?100-a:100,minSize:d?40:100,children:c.jsxs(TD,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx($Xe,{})}),c.jsx(OXe,{})]})})]})]})]})})]})})}var VXe=Object.defineProperty,HXe=(e,t,n)=>t in e?VXe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,uy=(e,t,n)=>HXe(e,typeof t!="symbol"?t+"":t,n);const UXe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},WXe={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}},qXe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},YXe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},GXe={stringify:e=>e,parse:e=>e},U2={string:GXe,number:YXe,boolean:UXe,function:WXe,json:qXe};function ZXe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const dy=Symbol.for("r2wc.render"),fy=Symbol.for("r2wc.connected"),gu=Symbol.for("r2wc.context"),za=Symbol.for("r2wc.props");function KXe(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=ZXe(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(),uy(this,o,!0),uy(this,s),uy(this,r,{}),uy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[za].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?U2[x]:null;y!=null&&y.parse&&b&&(this[za][m]=y.parse(b,g,this))}for(const m of a)this[za][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[fy]=!0,this[dy]()}disconnectedCallback(){this[fy]=!1,this[gu]&&n.unmount(this[gu]),delete this[gu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?U2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[za][x]=v.parse(b,m,this),this[dy]())}[(o=fy,s=gu,r=za,dy)](){this[fy]&&(this[gu]?n.update(this[gu],this[za]):this[gu]=n.mount(this.container,e,this[za]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[za][p]},set(b){this[za][p]=b;const x=g?U2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[dy]()}})}return h}function XXe(e,t,n){const r=rj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function QXe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function JXe({root:e}){e.unmount()}function eQe(e,t={}){return KXe(e,t,{mount:XXe,update:QXe,unmount:JXe})}const tQe={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"},nQe=eQe(zJ,{props:tQe});function rQe(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 tL(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){rQe(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 sQe(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 oQe(e,t){if(e==null)return{};var n=sQe(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 iQe(e,t){return aQe(e)||lQe(e,t)||cQe(e,t)||uQe()}function aQe(e){if(Array.isArray(e))return e}function lQe(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 cQe(e,t){if(e){if(typeof e=="string")return nL(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 nL(e,t)}}function nL(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 uQe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
1066
|
+
`)}})}});var XZe=UGe(()=>hJ(Ar([Un({type:ut("text-start"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("text-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Un({type:ut("text-end"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("error"),errorText:$e()}),Un({type:ut("tool-input-start"),toolCallId:$e(),toolName:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Un({type:ut("tool-input-delta"),toolCallId:$e(),inputTextDelta:$e()}),Un({type:ut("tool-input-available"),toolCallId:$e(),toolName:$e(),input:uo(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional()}),Un({type:ut("tool-input-error"),toolCallId:$e(),toolName:$e(),input:uo(),providerExecuted:wr().optional(),providerMetadata:ir.optional(),dynamic:wr().optional(),errorText:$e()}),Un({type:ut("tool-output-available"),toolCallId:$e(),output:uo(),providerExecuted:wr().optional(),dynamic:wr().optional(),preliminary:wr().optional()}),Un({type:ut("tool-output-error"),toolCallId:$e(),errorText:$e(),providerExecuted:wr().optional(),dynamic:wr().optional()}),Un({type:ut("reasoning-start"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("reasoning-delta"),id:$e(),delta:$e(),providerMetadata:ir.optional()}),Un({type:ut("reasoning-end"),id:$e(),providerMetadata:ir.optional()}),Un({type:ut("source-url"),sourceId:$e(),url:$e(),title:$e().optional(),providerMetadata:ir.optional()}),Un({type:ut("source-document"),sourceId:$e(),mediaType:$e(),title:$e(),filename:$e().optional(),providerMetadata:ir.optional()}),Un({type:ut("file"),url:$e(),mediaType:$e(),providerMetadata:ir.optional()}),Un({type:lJ(e=>typeof e=="string"&&e.startsWith("data-"),{message:'Type must start with "data-"'}),id:$e().optional(),data:uo(),transient:wr().optional()}),Un({type:ut("start-step")}),Un({type:ut("finish-step")}),Un({type:ut("start"),messageId:$e().optional(),messageMetadata:uo().optional()}),Un({type:ut("finish"),messageMetadata:uo().optional()}),Un({type:ut("abort")}),Un({type:ut("message-metadata"),messageMetadata:uo()})])));function QZe(e){return e.type.startsWith("data-")}function wJ(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]=wJ(o,s):n[r]=s}return n}function JZe(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 SJ(e){if(e===void 0)return{value:void 0,state:"undefined-input"};let t=await _w({text:e});return t.success?{value:t.value,state:"successful-parse"}:(t=await _w({text:JZe(e)}),t.success?{value:t.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}function Fy(e){return e.type.startsWith("tool-")}function eKe(e){return e.type==="dynamic-tool"}function XE(e){return Fy(e)||eKe(e)}function K$(e){return e.type.split("-").slice(1).join("-")}function tKe({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 nKe({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(Fy).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=>Fy(k)&&k.toolCallId===w.toolCallId),j=w,_=C;C!=null?(C.state=w.state,_.input=j.input,_.output=j.output,_.errorText=j.errorText,_.rawInput=j.rawInput,_.preliminary=j.preliminary,_.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,_=C;C!=null?(C.state=w.state,_.toolName=w.toolName,_.input=j.input,_.output=j.output,_.errorText=j.errorText,_.rawInput=(S=j.rawInput)!=null?S:_.rawInput,_.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?wJ(u.message.metadata,w):w;t!=null&&await W$({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(Fy);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 SJ(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:K$(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:K$(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(QZe(a)){(n==null?void 0:n[a.type])!=null&&await W$({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 rKe({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()}}Tx({prefix:"aitxt",size:24});Tx({prefix:"aiobj",size:24});var sKe=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()})}};Tx({prefix:"aiobj",size:24});var oKe={};BZe(oKe,{object:()=>aKe,text:()=>iKe});var iKe=()=>({type:"text",responseFormat:{type:"text"},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),aKe=({schema:e})=>{const t=LZe(e);return{type:"object",responseFormat:{type:"json",schema:t.jsonSchema},async parsePartial({text:n}){const r=await SJ(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 _w({text:n});if(!s.success)throw new G$({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 lI({value:s.value,schema:t});if(!o.success)throw new G$({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}}},lKe=$f({name:$e(),version:$e()}),uI=$f({_meta:pr(qt({}).loose())}),mb=uI,cKe=qt({method:$e(),params:pr(uI)}),uKe=$f({experimental:pr(qt({}).loose()),logging:pr(qt({}).loose()),prompts:pr($f({listChanged:pr(wr())})),resources:pr($f({subscribe:pr(wr()),listChanged:pr(wr())})),tools:pr($f({listChanged:pr(wr())}))});mb.extend({protocolVersion:$e(),capabilities:uKe,serverInfo:lKe,instructions:pr($e())});var dKe=mb.extend({nextCursor:pr($e())}),fKe=qt({name:$e(),description:pr($e()),inputSchema:qt({type:ut("object"),properties:pr(qt({}).loose())}).loose()}).loose();dKe.extend({tools:ru(fKe)});var hKe=qt({type:ut("text"),text:$e()}).loose(),pKe=qt({type:ut("image"),data:nJ(),mimeType:$e()}).loose(),CJ=qt({uri:$e(),mimeType:pr($e())}).loose(),mKe=CJ.extend({text:$e()}),gKe=CJ.extend({blob:nJ()}),bKe=qt({type:ut("resource"),resource:Ar([mKe,gKe])}).loose();mb.extend({content:ru(Ar([hKe,pKe,bKe])),isError:wr().default(!1).optional()}).or(mb.extend({toolResult:uo()}));var GS="2.0",xKe=qt({jsonrpc:ut(GS),id:Ar([$e(),hb().int()])}).merge(cKe).strict(),yKe=qt({jsonrpc:ut(GS),id:Ar([$e(),hb().int()]),result:mb}).strict(),vKe=qt({jsonrpc:ut(GS),id:Ar([$e(),hb().int()]),error:qt({code:hb().int(),message:$e(),data:pr(uo())})}).strict(),wKe=qt({jsonrpc:ut(GS)}).merge(qt({method:$e(),params:pr(uI)})).strict();Ar([xKe,wKe,yKe,vKe]);async function SKe(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 CKe=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 wf(this.body),l=await wf(this.headers),u=await wf(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:U$({"Content-Type":"application/json",...h},`ai-sdk/${Z$}`,H$()),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 wf(this.body),a=await wf(this.headers),l=await wf(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:U$(f,`ai-sdk/${Z$}`,H$()),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)}},dI=class extends CKe{constructor(e={}){super(e)}processResponseStream(e){return YGe({stream:e,schema:XZe}).pipeThrough(new TransformStream({async transform(t,n){if(!t.success)throw t.error;n.enqueue(t.value)}}))}},NKe=class{constructor({generateId:e=PGe,id:t=e(),transport:n=new dI,messageMetadataSchema:r,dataPartSchemas:s,state:o,onError:i,onToolCall:a,onFinish:l,onData:u,sendAutomaticallyWhen:d}){this.activeResponse=void 0,this.jobExecutor=new sKe,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 SKe(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=>XE(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=>XE(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:tKe({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 rKe({stream:nKe({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 jKe({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(XE);return r.length>0&&r.every(s=>s.state==="output-available"||s.state==="output-error")}function kKe(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 EKe=kKe;const _Ke=zc(EKe);var NJ=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},Tn=(e,t,n)=>(NJ(e,t,"read from private field"),n?n.call(e):t.get(e)),Yi=(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)},Wl=(e,t,n,r)=>(NJ(e,t,"write to private field"),t.set(e,n),n);function MKe(e,t){return t!=null?_Ke(e,t):e}var ko,$y,Ly,Fm,$m,Lm,Ef,QE,JE,DKe=class{constructor(e=[]){Yi(this,ko,void 0),Yi(this,$y,"ready"),Yi(this,Ly,void 0),Yi(this,Fm,new Set),Yi(this,$m,new Set),Yi(this,Lm,new Set),this.pushMessage=t=>{Wl(this,ko,Tn(this,ko).concat(t)),Tn(this,Ef).call(this)},this.popMessage=()=>{Wl(this,ko,Tn(this,ko).slice(0,-1)),Tn(this,Ef).call(this)},this.replaceMessage=(t,n)=>{Wl(this,ko,[...Tn(this,ko).slice(0,t),this.snapshot(n),...Tn(this,ko).slice(t+1)]),Tn(this,Ef).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?MKe(t,n):t;return Tn(this,Fm).add(r),()=>{Tn(this,Fm).delete(r)}},this["~registerStatusCallback"]=t=>(Tn(this,$m).add(t),()=>{Tn(this,$m).delete(t)}),this["~registerErrorCallback"]=t=>(Tn(this,Lm).add(t),()=>{Tn(this,Lm).delete(t)}),Yi(this,Ef,()=>{Tn(this,Fm).forEach(t=>t())}),Yi(this,QE,()=>{Tn(this,$m).forEach(t=>t())}),Yi(this,JE,()=>{Tn(this,Lm).forEach(t=>t())}),Wl(this,ko,e)}get status(){return Tn(this,$y)}set status(e){Wl(this,$y,e),Tn(this,QE).call(this)}get error(){return Tn(this,Ly)}set error(e){Wl(this,Ly,e),Tn(this,JE).call(this)}get messages(){return Tn(this,ko)}set messages(e){Wl(this,ko,[...e]),Tn(this,Ef).call(this)}};ko=new WeakMap;$y=new WeakMap;Ly=new WeakMap;Fm=new WeakMap;$m=new WeakMap;Lm=new WeakMap;Ef=new WeakMap;QE=new WeakMap;JE=new WeakMap;var _f,X$=class extends NKe{constructor({messages:e,...t}){const n=new DKe(e);super({...t,state:n}),Yi(this,_f,void 0),this["~registerMessagesCallback"]=(r,s)=>Tn(this,_f)["~registerMessagesCallback"](r,s),this["~registerStatusCallback"]=r=>Tn(this,_f)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>Tn(this,_f)["~registerErrorCallback"](r),Wl(this,_f,n)}};_f=new WeakMap;function jJ({experimental_throttle:e,resume:t=!1,...n}={}){const r=N.useRef("chat"in n?n.chat:new X$(n));("chat"in n&&n.chat!==r.current||"id"in n&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new X$(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 TKe(e,t){return e.some(n=>n.tableName&&n.tableName===t.tableName||n.datamodelName&&n.datamodelName===t.datamodelName)}function RKe(e){return e.filter((n,r,s)=>r===s.findIndex(o=>o.tableName===n.tableName&&o.datamodelName===n.datamodelName))}function IKe(e,t){return e.filter(n=>!(n.connectionId===t.connectionId&&n.tableName===t.tableName&&n.datamodelName===t.datamodelName))}function AKe(e){return e.toLowerCase()==="clickhouse"?"{database_name}.{table_name}":e.toLowerCase()==="postgres"?"{schema_name}.{table_name}":"{table_name}"}function kJ(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:AKe(s)}}).filter(r=>r.datamodelName?r.connectionId&&r.datamodelName&&r.connectionType:r.connectionId&&r.tableName&&r.connectionType)}function EJ(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 PKe(){var b;const{authToken:e,tokenProps:t}=Ge(),n=J(x=>x.dashboard.aiScopeTables),r=(b=Uw().data)==null?void 0:b.assistantProfileId,{sendMessage:s,messages:o,setMessages:i,regenerate:a,status:l,addToolResult:u,error:d,stop:f,clearError:h}=jJ({transport:new dI({api:`${t.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${e==null?void 0:e.accessToken}`}),body:()=>{const x=Bi.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:eW(x)}})}),onToolCall:p,sendAutomaticallyWhen:jKe,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:kJ(n||[])}}),x.toolName==="getDashboardContext"){const y=J.getState().dashboard;u({tool:x.toolName,toolCallId:x.toolCallId,output:{dashboardContext:y}})}}const m=!["ready","error"].includes(l),g=EJ(d);return{sendMessage:s,regenerate:a,isLoading:m,messages:o,setMessages:i,status:l,stop:f,errorMessage:g,clearError:h}}function _J(){var u;const{authToken:e,tokenProps:t}=Ge(),n=(u=Uw().data)==null?void 0:u.assistantProfileId;function r(){return!(!n||!(e!=null&&e.accessToken))}const{data:s,isLoading:o,isFetching:i,isError:a}=bn({queryKey:["assistant-profile",n],queryFn:()=>qn(`${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 MJ({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(W6,{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 Mw(e,t={}){const{size:n="h-4 w-4"}=t,r=n;switch(e){case"table":return c.jsx(z_,{className:r});case"view":return c.jsx(vc,{className:r});case"materialized view":return c.jsx(oie,{className:r});case"model":return c.jsx(Xw,{className:r});case"file":return c.jsx(Ti,{className:r});case"dataset":return c.jsx(hl,{className:r});case"upload":return c.jsx(U_,{className:r});case"url":return c.jsx(t8,{className:r});default:return c.jsx(Kw,{className:r})}}const DJ=M.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center px-3","cmdk-input-wrapper":"",children:[c.jsx(Ea,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(us.Input,{ref:n,className:K("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})]}));DJ.displayName=us.Input.displayName;const ly=e=>e.label||(e==null?void 0:e.name),Q$=e=>"description"in e?e.description:`${e.type} from ${e.database||"database"}`;function OKe({isOpen:e,onSelect:t,onDeselect:n,onClose:r,availableEntities:s,selectedEntities:o,onTabComplete:i,onSelectAll:a,onRemoveAll:l,onAddContext:u}){const{tokenProps:d}=Ge(),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=ly(C).toLowerCase(),_=Q$(C).toLowerCase(),k=h.toLowerCase();return j.includes(k)||_.includes(k)});N.useEffect(()=>{e||(p(""),g(""))},[e]),N.useEffect(()=>{b.length>0&&!m&&g(ly(b[0]))},[b,m]);const x=()=>{if(!m)return;const C=b.find(j=>ly(j)===m);C&&(o.some(_=>"id"in C&&"id"in _?C.id===_.id:C.name===_.name&&C.connectionId===_.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(ES,{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(DJ,{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(jr,{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(_S,{className:"min-h-60",children:[c.jsx(MS,{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(jr,{className:"h-4 w-4"}),"Add Datasets"]})]})}),c.jsx(DS,{children:b.map((C,j)=>{const _=v(C),k="id"in C?C.id:`${C.connectionId}-${C.name}`,E=ly(C);return c.jsxs(TS,{value:E,onSelect:()=>{_?n==null||n(C):t(C)},onMouseDown:T=>{T.preventDefault(),T.stopPropagation()},className:K("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:Mw(C.type)}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate font-medium",children:E}),c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:Q$(C)})]}),_&&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 e_=e=>e.name||e.name,FKe=e=>{const t=e_(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 $Ke({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(er,{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(wn,{children:[c.jsx(Sn,{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:[Mw(d.type,{size:"h-3 w-3"}),c.jsx("span",{className:"max-w-24 truncate text-xs",children:e_(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(En,{side:"top",className:"max-w-xs",children:FKe(d)})]},h)}),u&&c.jsxs(wn,{open:s,onOpenChange:o,children:[c.jsx(Sn,{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(T_,{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(En,{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:Mw(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:e_(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 TJ(e){return e.type==="dataset"&&e.label||e.name}function LKe(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 zKe({selectedEntities:e,onDeselectEntity:t}){return e.length===0?null:c.jsxs("div",{className:"mb-4 space-y-2",children:[c.jsxs(le,{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,"]"]}),TJ(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 BKe(e){const{tokenProps:t}=Ge(),n=J(l=>l.authToken)||e;ke(l=>l.selectedConnectionId),ke(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}=bn({queryKey:["semantic-domains"],queryFn:()=>qn(`${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 VKe(e,t){const{tokenProps:n}=Ge(),r=J(u=>u.authToken)||t,{refetch:s,isPending:o,data:i,isLoading:a,isError:l}=bn({queryKey:["datasets",e],queryFn:()=>qn(`${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 HKe(e){var g,b;const{tokenProps:t}=Ge(),n=J(x=>x.authToken)||e,{connections:r}=zi(e),s=ke(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}=bn({queryKey:["databases",s],queryFn:()=>qn(`${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 UKe(e){var g;const{tokenProps:t}=Ge(),n=J(b=>b.authToken)||e,{connections:r}=zi(e),s=ke(b=>{var x,y;return(y=(x=b==null?void 0:b.card)==null?void 0:x.dataSource)==null?void 0:y.connectionId}),o=ke(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}=bn({queryKey:["schemas",s,o],queryFn:()=>qn(`${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 RJ(e){const{tokenProps:t}=Ge(),n=J(h=>h.authToken)||e,{connections:r}=zi(e),s=ke(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}=bn({queryKey:["dataModels",s],queryFn:()=>qn(`${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 WKe(){var S,C,j;const e=ke(_=>_.card.dataSource);ke(_=>_.actions.updateDirectSource);const t=ke(_=>_.actions.updateDataSource),[n,r]=N.useState(""),{selectedConnection:s,error:o}=zi(),{databases:i,isPending:a,error:l,label:u}=HKe(),{schemas:d,isPending:f,error:h,label:p}=UKe(),{error:m}=RJ(),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=_=>{e&&t({...e,dbSelection:{database:_,schema:"",entityType:"table"},selectedEntities:(e==null?void 0:e.selectedEntities)||[]})},w=_=>{var E;if(!((E=e==null?void 0:e.dbSelection)!=null&&E.database))return;const k=e.dbSelection||{database:"",schema:"",entityType:"table"};t({...e,dbSelection:{...k,schema:_},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(le,{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(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]}),((C=e==null?void 0:e.dbSelection)==null?void 0:C.database)&&g&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(le,{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(_=>c.jsx(pe,{className:"hover:bg-muted",value:_.id,children:_.name},_.id))})]})]})]})]})}function qKe(){const e=ke(l=>l.card.dataSource),t=ke(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(le,{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(U_,{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(le,{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(Ti,{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 YKe(){const e=ke(f=>f.card.dataSource),t=ke(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(le,{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(le,{className:"text-xs text-gray-600",children:"Source Name"}),c.jsx(Cn,{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(le,{className:"text-xs text-gray-600",children:"URL"}),c.jsx(Cn,{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(le,{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(jr,{className:"mr-1 h-3 w-3"}),"Add Source"]})]})]}),d.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsxs(le,{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(Kw,{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 GKe(e,t){var y,v;const{tokenProps:n}=Ge(),r=J(w=>w.authToken)||t,{connections:s}=zi(t),o=ke(w=>{var S,C;return(C=(S=w==null?void 0:w.card)==null?void 0:S.dataSource)==null?void 0:C.connectionId}),i=ke(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=ke(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}=bn({queryKey:[e,o,i,a],queryFn:()=>qn(`${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 Dw({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(md,{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 ZKe({dataSource:e,onSelectionChange:t,selectedEntities:n,onRegisterSelectAll:r}){const{connections:s,isPending:o}=zi(),[i,a]=N.useState(""),[l,u]=N.useState(""),[d,f]=N.useState("tables"),{updateDataSource:h,setSelectedConnectionId:p}=cr(),{entities:m,isLoading:g,error:b}=GKe("table"),{dataModels:x,isPending:y,error:v}=RJ(),w=E=>{const T=s.find(O=>O.id===E);if(!T)return;const R=T.type==="upload"?"upload":T.type==="url"?"url":"database";h({...e,connectionId:E,connectionType:T.type,mode:R,dbSelection:{database:"",schema:"",entityType:"table"}}),p(E)},S=E=>{var D,I;const T=n||[],R=T.some(F=>F.name===E.name&&F.type===E.type);let O;if(R)O=T.filter(F=>!(F.name===E.name&&F.type===E.type));else{const F={connectionId:e.connectionId,connectionType:e.connectionType,type:E.type,dbObjectType:E.dbObjectType,database:((D=e.dbSelection)==null?void 0:D.database)||"",schema:((I=e.dbSelection)==null?void 0:I.schema)||"",name:E.name,dialect:E.dialect};O=[...T,F]}t==null||t(O)},C=E=>{const T=n||[],R=T.some(D=>D.type==="model"&&D.name===E.name);let O;R?O=T.filter(D=>!(D.type==="model"&&D.name===E.name)):O=[...T,E],t==null||t(O)},j=m.filter(E=>E.name.toLowerCase().includes(i.toLowerCase())),_=x.filter(E=>E.name.toLowerCase().includes(l.toLowerCase())),k=N.useCallback(()=>{if(!t)return;const E=n||[];let T=[...E];if(d==="tables"){const O=j.filter(D=>!E.some(I=>I.name===D.name&&I.type==="table")).map(D=>{var I,F;return{connectionId:e.connectionId,connectionType:e.connectionType,type:"table",dbObjectType:D.dbObjectType,database:((I=e.dbSelection)==null?void 0:I.database)||"",schema:((F=e.dbSelection)==null?void 0:F.schema)||"",name:D.name,dialect:D.dialect}});T=[...E,...O]}else if(d==="datamodels"){const R=_.filter(O=>!E.some(D=>D.name===O.name&&D.type==="model"));T=[...E,...R]}t(T)},[d,j,_,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(le,{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(E=>c.jsx(pe,{className:"hover:bg-muted",value:E.id,children:c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(hl,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"truncate",children:E.name}),c.jsx(Fe,{variant:"secondary",className:"flex-shrink-0 text-xs",children:E.type})]})},E.id))})]})]}),(e==null?void 0:e.connectionId)&&c.jsxs(c.Fragment,{children:[e.connectionType==="upload"&&c.jsx(qKe,{}),e.connectionType==="url"&&c.jsx(YKe,{}),e.connectionType!=="upload"&&e.connectionType!=="url"&&c.jsxs(c.Fragment,{children:[c.jsx(WKe,{}),c.jsx("div",{className:"space-y-4",children:c.jsx("div",{className:"space-y-2",children:c.jsxs(ls,{defaultValue:"tables",value:d,onValueChange:E=>f(E),className:"w-full",children:[c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsxs(Ut,{value:"tables",children:["Tables & Views (",j.length,")"]}),c.jsxs(Ut,{value:"datamodels",children:["Data Models (",_.length,")"]})]}),c.jsxs(Yn,{value:"tables",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search tables and views...",value:i,onChange:E=>a(E.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(Dw,{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(E=>{const T=n.some(R=>R.name===E.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(E),children:[c.jsx(un,{id:`table-${E.name}`,checked:T,onCheckedChange:()=>S(E),onClick:R=>R.stopPropagation(),disabled:g}),c.jsxs(le,{className:"flex flex-1 cursor-pointer items-center gap-2",children:[E.name,E.dbObjectType==="view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"View"}),E.dbObjectType==="materialized view"&&c.jsx(Fe,{variant:"secondary",className:"text-xs group-hover:border-border",children:"Materialized View"})]})]},E.name)})})]}),c.jsxs(Yn,{value:"datamodels",className:"space-y-2",children:[c.jsx(Bn,{placeholder:"Search data models...",value:l,onChange:E=>u(E.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(Dw,{title:"Error loading data models",message:v.message||"Failed to load data models. Please try again.",onRetry:()=>window.location.reload()}):_.length===0?c.jsx("div",{className:"py-4 text-center text-sm",children:"No data models found"}):_.map(E=>{const T=n.some(R=>R.name===E.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(E),children:[c.jsx(un,{id:`dataModel-${E.name}`,checked:T,onCheckedChange:()=>C(E),onClick:R=>R.stopPropagation(),disabled:y}),c.jsxs("div",{className:"flex flex-1 cursor-pointer flex-col gap-1",children:[c.jsx(le,{className:"cursor-pointer",children:E.name}),c.jsx("span",{className:"text-xs text-muted-foreground",children:E.description})]})]},E.name)})})]})]})})})]})]})]})}function KKe({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}=BKe(),m=o?f.filter(C=>s.includes(C.id)):f,{datasets:g,isPending:b,error:x}=VKe(e==null?void 0:e.semanticDomainId),y=C=>{const j=r||[],_=j.some(E=>E.id===C.id&&E.type==="dataset");let k;if(_)k=j.filter(E=>!(E.id===C.id&&E.type==="dataset"));else{const E={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,E]}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||[],_=v.filter(E=>!C.some(T=>T.id===E.id&&T.type==="dataset")).map(E=>({id:E.id,datasetType:E.type,name:E.name||E.table,label:E.label,domainId:E.domainId,description:E.description,database:E.database,schema:E.schema,type:"dataset",connectionId:E.connectionId,connectionType:E.connectionType,dialect:E.dialect,datamodelId:E.datamodelId,sql:E.sql})),k=[...C,..._];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(le,{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(Dw,{title:"Error loading semantic models",message:p.message})]}),(e==null?void 0:e.semanticDomainId)&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(le,{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(Dw,{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(_=>_.id===C.id&&_.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(un,{id:`dataset-${C.id}`,checked:j,onCheckedChange:()=>y(C),onClick:_=>_.stopPropagation(),disabled:b}),c.jsxs("div",{className:"flex flex-1 flex-col gap-1",children:[c.jsx(le,{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 fI({open:e,onOpenChange:t,dataSource:n,dialogMode:r,incomingSelectedEntities:s}){const{tokenProps:o}=Ge(),{allowedSemanticDomains:i}=o,[a,l]=N.useState([]),{updateDataSource:u}=cr(),d=J(T=>T.isVisualEditing),f=J(T=>T.dashboard.aiContext),{setAiContext:h}=Gt(),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(T=>{const R=T;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(T=>{u({...n,...T})},[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=T=>{const R=a.filter(O=>!(O.name===T.name&&O.type===T.type));l(R)},C=()=>{l([])},j=N.useCallback(T=>{l(T)},[]),_=N.useCallback(()=>{p.current&&p.current()},[]),k=N.useCallback(T=>{p.current=T,g(!0)},[]);function E(){var T,R;if(r==="aiContext")d&&u(n),h({...f,selectedEntities:a}),t(!1);else if(r==="dataSource"){if(n.mode==="semanticDomain"){const O=(T=a==null?void 0:a[0])==null?void 0:T.connectionId,D=(R=a==null?void 0:a[0])==null?void 0:R.connectionType;u({...n,connectionId:O,connectionType:D,selectedEntities:a})}else u({...n,selectedEntities:a});t(!1)}}return c.jsx(as,{open:e,onOpenChange:t,children:c.jsx(Br,{className:"flex max-w-2xl flex-col",children:c.jsxs("div",{children:[c.jsxs(Vr,{className:"flex-shrink-0",children:[c.jsx(Hr,{children:r==="aiContext"?"Data Context":"Select Data Source"}),c.jsx(Ds,{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(ls,{defaultValue:(n==null?void 0:n.mode)||"database",value:(n==null?void 0:n.mode)||"database",onValueChange:v,className:"w-full",children:c.jsxs(Ur,{className:"grid w-full grid-cols-2",children:[c.jsx(Ut,{value:"database",children:"Direct Source"}),c.jsx(Ut,{value:"semanticDomain",children:"Semantic Domain"})]})})}),(n==null?void 0:n.mode)==="semanticDomain"&&c.jsx(KKe,{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(ZKe,{dataSource:n,onDataSourceUpdate:w,selectedEntities:a,onSelectionChange:j,onRegisterSelectAll:k})]})}),c.jsx(zKe,{selectedEntities:a,onDeselectEntity:S}),c.jsx(Ms,{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:_,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:E,children:[c.jsx(Rr,{className:"mr-2 h-4 w-4"}),"Accept"]})]})})})]})})})}function XKe({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=Ya-n;if(l.length>u){ze.error(`You can only attach ${Ya} files per message. You have ${u} slot(s) remaining.`);return}const{valid:d,errors:f}=pQ(l);if(f.forEach(({file:h,error:p})=>{ze.error(`${h.name}: ${p}`)}),d.length>0)try{const h=await Promise.all(d.map(p=>JR(p)));e(h)}catch(h){console.error("Failed to process files:",h),ze.error("Failed to process one or more files")}s.current&&(s.current.value="")},i=()=>{var a;(a=s.current)==null||a.click()};return c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",multiple:!0,accept:".png,.jpg,.jpeg,.gif,.webp,.pdf,.txt,.md,.csv,.json,.xml,.js,.jsx,.ts,.tsx,.py,.sql",onChange:o,className:"hidden",disabled:t||n>=Ya}),c.jsx(oe,{variant:"secondary",size:"sm",className:`h-7 px-2 ${r}`,onClick:i,disabled:t||n>=Ya,title:n>=Ya?`Maximum ${Ya} files allowed`:"Attach files",children:c.jsx(O_,{className:"h-4 w-4 text-muted-foreground"})})]})}function QKe({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=Ya-r;if(h.length>p){ze.error(`You can only attach ${Ya} files per message. You have ${p} slot(s) remaining.`);return}const{valid:m,errors:g}=pQ(h);if(g.forEach(({file:b,error:x})=>{ze.error(`${b.name}: ${x}`)}),m.length>0)try{const b=await Promise.all(m.map(x=>JR(x)));t(b),ze.success(`${b.length} file(s) attached successfully`)}catch(b){console.error("Failed to process files:",b),ze.error("Failed to process one or more files")}},[n,r,t]);return c.jsxs("div",{className:K("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(U_,{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:[Ya-r," slot(s) available"]})]})})]})}const hI=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=_p();sCe(),rCe();const{setCurrentAIContext:y,updateSelectedEntities:v,setReasoningEffort:w,setShowReasoning:S}=F1(),{queueMessage:C}=Mp(),{addFileAttachment:j,removeFileAttachment:_,clearFileAttachments:k,getFileAttachments:E}=DD(),T=MD(l),R=ke(z=>z.card.dataSource),O=J(z=>z.dashboard.aiContext),D=J(z=>{var G;return(G=z.dashboard.aiContext)==null?void 0:G.selectedEntities});N.useEffect(()=>{u&&"current"in u&&(u.current=b.current)},[u]);const I=N.useCallback(()=>{const z=b.current;if(z){if(!e||e.length===0){z.style.height="10px";return}z.style.height="auto";const G=Math.min(Math.max(z.scrollHeight,10),200);z.style.height=`${G}px`}},[e]);N.useEffect(()=>{I()},[I]),N.useEffect(()=>{const z=setTimeout(()=>{I()},0);return()=>clearTimeout(z)},[I]);const F=()=>{const z=e.trim();!z&&T.length===0||(a!=="ready"?(C(l,z,T),t(""),k(l)):r({preventDefault:()=>{}}))},B=z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),F()),z.key==="@"&&(U(),f(!0))},V=N.useCallback(z=>{const G=fUe(z.nativeEvent);G.length>0&&(z.preventDefault(),G.forEach(async Z=>{const te=await JR(Z);j(l,te)}))},[j,l]),$=N.useCallback(z=>{z.forEach(G=>{j(l,G)})},[j,l]),P=N.useCallback(z=>{z.forEach(G=>{j(l,G)})},[j,l]),H=N.useCallback(z=>{_(l,z)},[_,l]),L=z=>{if(x.selectedEntities.some(Z=>Z.id&&Z.id===z.id||Z.name===z.name)){const Z=x.selectedEntities.filter(te=>!(te.id&&te.id===z.id||te.name===z.name));y({selectedEntities:Z})}else{const Z=[...x.selectedEntities,z];y({selectedEntities:Z})}},A=z=>{L(z)},W=z=>{var te;if(!x.selectedEntities.some(X=>X.id&&X.id===z.id||X.name===z.name)){const X=[...x.selectedEntities,z];y({selectedEntities:X})}const Z="label"in z?z.label:z.name;t(e+`@${Z} `),f(!1),(te=b.current)==null||te.focus()},q=z=>{const G=x.selectedEntities.filter(X=>!(X.id&&X.id===z.id||X.name===z.name));y({selectedEntities:G});const te=`@${"label"in z?z.label:z.name}`;e.includes(te)&&t(e.replace(te,"").trim())},Y=z=>{const G=new Set(z.map(X=>X.id||X.name)),Z=x.selectedEntities.filter(X=>!G.has(X.id||X.name));y({selectedEntities:Z});let te=e;z.forEach(X=>{const se=`@${"label"in X?X.label:X.name}`;te=te.replace(se,"").trim()}),t(te)},U=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(QKe,{onFilesDropped:$,currentFileCount:T.length,disabled:s,className:"space-y-4",children:[c.jsx($Ke,{entities:x.selectedEntities,availableEntities:D||[],onRemoveEntity:q,onRemoveEntities:Y}),T.length>0&&c.jsx(hUe,{files:T,onRemove:H,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:B,onPaste:V,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(Ss,{open:d,onOpenChange:z=>{z&&U(),f(z)},children:[c.jsx(Cs,{asChild:!0,children:c.jsx(oe,{variant:"secondary",size:"sm",className:"h-7 px-2",title:"Add entity",children:c.jsx(Xoe,{className:"h-4 w-4 text-muted-foreground"})})}),c.jsx(Ns,{className:"w-80 p-0",align:"start",side:"top",sideOffset:8,onOpenAutoFocus:z=>z.preventDefault(),children:c.jsx(OKe,{isOpen:!0,onSelect:L,onDeselect:A,onClose:()=>{var z;f(!1),(z=b.current)==null||z.focus()},availableEntities:D||[],selectedEntities:x.selectedEntities,onTabComplete:W,onSelectAll:()=>{D&&y({selectedEntities:D})},onRemoveAll:()=>{y({selectedEntities:[]})},onAddContext:()=>{f(!1),p(!0)}})})]}),c.jsx(XKe,{onFilesSelected:P,disabled:s,currentFileCount:T.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(mie,{className:"size-3.5 bg-background"})}),!s&&c.jsx(oe,{disabled:!e.trim()&&T.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(fI,{incomingSelectedEntities:x.selectedEntities,open:h,onOpenChange:p,dataSource:R||WS,dialogMode:"aiContext"})]})});hI.displayName="ChatInputWithContext";function IJ({assistantType:e,className:t}){const n=tW(e),{removeFromQueue:r}=Mp();return n.length===0?null:c.jsxs("div",{className:K("space-y-2",t),children:[c.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[c.jsx(vl,{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 AJ({assistantType:e,status:t,isLoading:n,sendMessage:r}){const s=tW(e),{dequeueMessage:o}=Mp();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 PJ(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:T=!1,instant:R=!1}=k;if(!T&&!y.current||!a&&!T)return;const O=R||r==="auto"||r==="instant"?"auto":r;v.current&&cancelAnimationFrame(v.current),b.current=!0,v.current=requestAnimationFrame(()=>{if(!T&&!y.current){b.current=!1,v.current=void 0;return}const D=i.current;if(!D){b.current=!1,v.current=void 0;return}const I=D.scrollHeight;O==="smooth"&&"scrollTo"in D?D.scrollTo({top:I,behavior:O}):D.scrollTop=I,g.current=D.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 E=g.current,T=k.scrollTop,R=T-E;if(g.current=T,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]),_=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 E=w.current,T=e[e.length-1],R=(T==null?void 0:T.id)??(T==null?void 0:T.messageId)??(T==null?void 0:T.createdAt)??(T==null?void 0:T.timestamp)??e.length,O=Array.isArray(T==null?void 0:T.parts)?T.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(T==null?void 0:T.content)=="string"?T.content.length:typeof(T==null?void 0:T.text)=="string"?T.text.length:0,D=e.length>E.count,I=R!==E.key,F=O>E.length,B=s&&(T==null?void 0:T.role)==="assistant"&&!D&&(I||F),V=o||B;if(w.current={key:R,count:e.length,length:O},a&&(D||I||F||V)){C({force:!1,instant:V});return}if(!a&&D){const $=e.length-E.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 E=new ResizeObserver(()=>{const T=i.current;if(!T)return;const R=x.current,O=T.scrollHeight;x.current=O,!b.current&&y.current&&O>R&&C({force:!1,instant:!0})});return E.observe(k),()=>{E.disconnect()}},[C]),N.useEffect(()=>()=>{v.current&&cancelAnimationFrame(v.current)},[]),{scrollRef:i,isAutoScrollEnabled:a,isAtBottom:u,hasNewMessages:f,newMessageCount:p,scrollToBottom:C,handleScroll:j,resetNewMessageCount:_}}function OJ(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 FJ(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:mQ(s.type,o),toolType:s.type}}}return{hasActiveTools:!1}}const JKe=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function eXe({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=N.useState(!1),[a,l]=N.useState(Lw),[u,d]=N.useState(!1),[f,h]=N.useState(!1),[p,m]=N.useState(!1),g=n??p,{isLocalDev:b,isConsoleMode:x}=ip(),y=N.useRef(null);J(Ve=>Ve.dashboard.aiScopeTables),J(Ve=>Ve.isDashboardEditing);const v=J(Ve=>Ve.selectedSheetId),{setDataSource:w}=cr(),{addFrame:S,setSelectedFrameId:C,setIsDashboardEditing:j}=Gt(),_=_p(),{setCurrentAIContext:k,updateSelectedEntities:E,setReasoningEffort:T,setShowReasoning:R}=F1(),{clearQueue:O}=Mp(),{clearFileAttachments:D,getFileAttachments:I}=DD(),F=MD("dashboard"),B=J(Ve=>Ve.dashboard.aiContext),V=ke(Ve=>Ve.card.dataSource),{assistantProfile:$}=_J(),P=J(Ve=>Ve.handleOpenAssistantProfile),{sendMessage:H,isLoading:L,messages:A,setMessages:W,status:q,stop:Y,errorMessage:U,clearError:z}=PKe(),G=N.useCallback(Ve=>{r==null||r(Ve),n===void 0&&m(Ve)},[n,r]),Z=N.useCallback(()=>{G(!g)},[g,G]);N.useEffect(()=>{if(!g)return;function Ve(Ue){Ue.key==="Escape"&&G(!1)}return window.addEventListener("keydown",Ve),()=>{window.removeEventListener("keydown",Ve)}},[g,G]);const[te,X]=N.useState(""),ne=Ve=>{X(Ve.target.value)};function se({sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:Ne,dataSource:De}){if(console.log("handleAddNewFrame",{sql:Ve,data:Ue,cardTitle:ht,connectionId:He,cardType:Ke,python:ve,cardConfig:Ne,dataSource:De}),!v)return;const Le={id:Dr(),title:ht||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Ke==="horizontalBar"?"y":"x"}},type:Ke,sql:Ve,python:ve,dataSource:De,config:Ne,connectionId:He},nt={id:Dr(),cards:[Le],activeCardId:Le.id};j(!0),S(v,nt,"end"),C(nt.id)}const ce=Ve=>{Ve.preventDefault();const Ue=te.trim();if(!Ue&&F.length===0)return;const ht=[];Ue&&ht.push({type:"text",text:Ue}),F.forEach(He=>{He.data&&ht.push({type:"file",mediaType:He.type,filename:He.name,url:`data:${He.type};base64,${He.data}`})}),H({role:"user",parts:ht}),X(""),D("dashboard"),re({force:!0})};N.useEffect(()=>{var Ve;e&&((Ve=y.current)==null||Ve.focus())},[e]),AJ({assistantType:"dashboard",status:q,isLoading:L,sendMessage:H});const{hasActiveTools:ae}=FJ(A),{visibleMessages:he,hasMoreMessages:ye,totalMessageCount:Te,loadMoreMessages:_e,resetMessageWindow:de}=OJ(A,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:Re,isAtBottom:Oe,hasNewMessages:mt,newMessageCount:be,scrollToBottom:re,handleScroll:ue,resetNewMessageCount:we}=PJ(he,{threshold:50,behavior:"smooth",isStreaming:L});function Se(Ve){Ze();const Ue={role:"user",parts:[{type:"text",text:Ve.title+" "+Ve.subtitle}]};H(Ue)}function Pe(Ve){Ze(),H({role:"user",parts:[{type:"text",text:Ve}]})}function Qe(Ve){Ze(),H({role:"user",parts:[{type:"text",text:Ve}]}),re({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),ze.success("Conversation copied")}catch(Ue){console.error("Failed to copy conversation",Ue),ze.error("Unable to copy conversation")}},[A]);function Ze(){_.selectedEntities.length===0&&k({selectedEntities:(B==null?void 0:B.selectedEntities)||[]})}const Lt=(te==null?void 0:te.length)===0&&(A==null?void 0:A.filter(Ve=>Ve.role==="user").length)===0;function Ce(){return c.jsx("div",{"data-role":"header",children:c.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}function Mt(){return c.jsxs(sp,{children:[c.jsx(op,{asChild:!0,children:c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(Mb,{className:"size-3.5"})})}),c.jsxs(Vd,{align:"end",children:[c.jsx(Wf,{children:"Options"}),c.jsx(bd,{}),c.jsx(Hm,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Hm,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Hm,{checked:u,onCheckedChange:d,children:"System Message"})]})]})}const fn=c.jsxs("div",{"data-role":"dashboard-assistant",className:K("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:[Ce(),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&&Mt(),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(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:g?"Exit Fullscreen":"Expand",onClick:Z,children:g?c.jsx(P_,{className:"size-4"}):c.jsx(Qw,{className:"size-4"})}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{W([]),O("dashboard"),z(),de()},children:c.jsx(Jw,{className:"size-4"})}),c.jsx(cc,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:()=>{t(!1)},children:c.jsx(vt,{className:"size-4"})})]})]}),c.jsxs(_l,{"data-role":"dashboard-assistant-scroll-area",ref:Re,className:"mt-4 flex flex-1 basis-0 flex-col flex-wrap justify-end pr-2",onScroll:ue,children:[c.jsxs("div",{className:"space-y-3 pb-4",children:[ye&&c.jsx("div",{className:"flex justify-center py-2",children:c.jsxs(oe,{variant:"outline",size:"sm",onClick:_e,className:"text-xs",children:["Load ",Math.min(5,Te-he.length)," ","more messages (",Te-he.length," ","hidden)"]})}),c.jsx(bQ,{showTools:a,showSystemMessage:u,messages:he,onAddToDashboard:se,onQuickReply:Qe,disableQuickReplies:L}),!ae&&c.jsx(gQ,{status:q,errorMessage:U})]}),c.jsx(Ko,{orientation:"horizontal"})]}),e&&!Oe&&c.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:c.jsxs(oe,{onClick:()=>{re({force:!0}),we()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[c.jsx(Gs,{className:"h-4 w-4"}),mt&&be>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:be>9?"9+":be})]})}),c.jsxs("div",{className:"space-y-3",children:[!$&&Lt&&c.jsx(xQ,{onClick:Se,placeholders:JKe}),c.jsx("div",{children:Lt&&$&&c.jsx(MJ,{seedQuestions:$.seedQuestions||[],handleSeedQuestionClick:Pe})}),c.jsx(IJ,{assistantType:"dashboard",className:"mb-3"}),c.jsx(hI,{ref:y,setInput:X,stop:Y,input:te,handleInputChange:ne,handleSubmit:Ve=>{Ze(),ce(Ve),re({force:!0})},isLoading:L,status:q,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(fI,{incomingSelectedEntities:(B==null?void 0:B.selectedEntities)||[],open:f,onOpenChange:h,dataSource:V||WS,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:fn})}),s):fn}function tXe(e){const t=e.current,{getSelectedFrame:n,addFrame:r,setSelectedFrameId:s}=Gt(),o=J(d=>d.dashboard.sheets),a=J(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=J(d=>d.isDashboardEditing),u=J(d=>d.isVisualEditing);N.useEffect(()=>{if(!l||u)return;async function d(p){const m=p.ctrlKey||p.metaKey;m&&p.key==="c"?(await f(),ze.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=$T(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),ze.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 nXe(e,t){switch(e.interactionMode){case"drillToDetail":rXe(e,t);break;case"drillThrough":sXe(e,t);break;case"drillToURL":oXe(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 rXe(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 sXe(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 oXe(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 iXe({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(as,{open:e,onOpenChange:t,children:c.jsxs(Br,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Vr,{children:[c.jsx(Hr,{children:i||"Insight Detail"}),c.jsx(Ds,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(DZ,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(RZ,{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 aXe(){const e=zt(w=>w.interactionStates),t=zt(w=>w.setInteractionState),n=zt(w=>w.clearLastInteractionEvent),r=zt(w=>w.replaceCardWithInsight),s=zt(w=>w.setPendingDrillThrough),o=zt(w=>w.pendingDrillThrough),i=zt(w=>w.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=Gt(),{selectDashboard:u}=_b(),d=J(w=>w.dashboard),f=J(w=>w.filterValues),{data:h,isLoading:p}=fde((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[m,g]=N.useState({open:!1,insightId:""}),b=IZ(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:_})=>{const E={sourceCardId:da,interactionMode:"clickFilter",filterGroups:[{filters:w}]},T={...Po(),appliedClickFilters:[E],contextMode:S,sourceDashboardId:C,sourceDashboardTitle:j,targetDashboardId:_};t(da,T)}}),[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{nXe(C,y)}catch(_){console.error("Error executing interaction event:",_)}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(iXe,{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 lXe(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=cXe(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function cXe(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function uXe(e){return e?`Back to ${e}`:"Back"}function dXe(){var x,y,v,w,S;const e=zt(C=>C.interactionStates[da]),t=J(C=>C.actions.goBackFromDrill),n=J(C=>C.actions.clearDrillContext),{selectDashboard:r}=_b(),[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=_=>{o({x:_.clientX-l.current.x,y:_.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})};lXe(f);const b=uXe(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 _=C.field.label||C.field.name,k=String(C.value);return c.jsxs(Fe,{variant:"secondary",className:"pointer-events-none text-xs",children:[_," = ",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(I6,{className:"mr-2 h-4 w-4"}),b]})})]})})}function $J(){var U;const{showAssistant:e}=Ge(),{preferences:t}=ip(),n=((U=t==null?void 0:t.cardDisplay)==null?void 0:U.mode)==="print",r=N.useRef(null),s=N.useRef(null),[o,i]=N.useState(!1),a=nd(z=>z.setFullscreen),l=nd(z=>z.setPanelOpen),u=nd(z=>z.setContainer),d=XU("dashboard"),f=QU(),h=JU("dashboard"),p=d.isOpen,m=f==="dashboard",g=J(z=>z.isVisualEditing),b=J(z=>z.themeStyle),x=J(z=>{var G;return(G=z.dashboard)==null?void 0:G.sheets}),y=J(z=>z.isDashboardEditing),v=J(z=>z.selectedSheetId),w=J(z=>{var G;return(G=z.dashboard)==null?void 0:G.id}),{getDefaultSheetId:S,setDefaultSheetId:C,clearDefaultSheetId:j}=b6(w),[_,k]=N.useState(null),{setSelectedSheetId:E,setSheetTitle:T,addSheet:R,setSheets:O}=Gt();tXe(s);const{setActiveAssistantType:D}=F1();N.useEffect(()=>{if(w){const z=S();k(z)}},[w,S]),N.useEffect(()=>{p?D("dashboard"):f==="dashboard"&&a(null)},[p,D,f,a]);function I(z){var G,Z;z?((G=r.current)==null||G.resize(40),l("dashboard",!0),D("dashboard")):(l("dashboard",!1),a(null),(Z=r.current)==null||Z.resize(0),D(null))}function F(){const z={id:Dr(),title:"New Sheet"};R(z),E(z.id)}function B(z,G){if(!w)return;_===z?(j(),k(null),ze.success("Default sheet cleared")):(C(z),k(z),ze.success(`"${G}" set as default sheet`))}function V(z){z<1?(l("dashboard",!1),a(null),D(null)):(p||l("dashboard",!0),D("dashboard"))}function $(){return(b==null?void 0:b.canvasTheme)==="muted"||!(b!=null&&b.canvasTheme)?"hsl(var(--semaphor-muted))":(b==null?void 0:b.canvasTheme)==="clear"?"":b==null?void 0:b.canvasTheme}const P=(z,G)=>{z.dataTransfer.setData("tabIndex",G.toString())},H=z=>{z.preventDefault()},L=(z,G)=>{const Z=z.dataTransfer.getData("tabIndex");if(Z===G.toString())return;const te=Array.from(x||[]),[X]=te.splice(parseInt(Z),1);te.splice(G,0,X),O(te)};function A(){var z,G;if(x&&x.length>1||y)return c.jsxs(Ur,{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:[x==null?void 0:x.map((Z,te)=>{const X=v===Z.id,ne=_===Z.id;return c.jsxs(Ut,{draggable:!0,onDragStart:se=>P(se,te),onDragOver:H,onDrop:se=>L(se,te),style:{borderRadius:b==null?void 0:b.controlInputRadius},onClick:()=>E(Z.id),className:"flex items-center gap-1 rounded-none border px-2 py-1",value:Z.id,children:[c.jsx(Gg,{enabled:y&&X,text:Z.title,onSave:se=>T(Z.id,se),children:Z.title},Z.id),!y&&X&&c.jsx("div",{title:ne?"Clear default sheet":"Set as default sheet",children:c.jsx(xie,{className:K("ml-1 size-3 cursor-pointer transition-all",ne?"fill-yellow-500 text-yellow-500":"text-muted-foreground hover:text-foreground"),onClick:se=>{se.stopPropagation(),B(Z.id,Z.title||"Sheet")}})}),y&&X&&x.length>1&&c.jsx(vt,{className:"ml-1 size-3",onClick:()=>i(!0)})]},Z.id)}),y&&c.jsx("div",{style:{borderRadius:(G=(z=b==null?void 0:b.chart)==null?void 0:z.options)==null?void 0:G.borderRadius},className:"flex h-7 items-center justify-center border-none bg-muted p-2 hover:cursor-pointer dark:border-l-background",onClick:F,children:c.jsx(jr,{className:"size-3"})})]})}function W(){return c.jsx("div",{ref:s,style:{},className:"grow",children:x==null?void 0:x.map(z=>c.jsx(Yn,{style:{backgroundColor:$()},className:K("mt-0",{}),value:z.id,children:c.jsx(_Le,{sheet:z})},z.id))})}function q(){var z;return c.jsxs(ls,{"data-role":"dashboard-tabs-container",className:K("relative flex h-full flex-col",b==null?void 0:b.dashboardTabsContainer),onValueChange:G=>{E(G)},value:v||((z=x==null?void 0:x[0])==null?void 0:z.id),children:[A(),c.jsx(_l,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:W()}),c.jsx(i6e,{open:o,setOpen:i})]})}const Y=N.useCallback(z=>{u("dashboard",z)},[u]);return x?c.jsxs(c.Fragment,{children:[c.jsx(aXe,{}),c.jsx(dXe,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(TR,{className:K("flex-1 basis-0 overflow-y-auto transition-opacity",m&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(ib,{children:q()}),e===!0&&c.jsxs(c.Fragment,{children:[c.jsx(o6e,{open:p,onTabClick:I,withHandle:!0}),c.jsx(ib,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:V,defaultSize:p?40:0,ref:r,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(eXe,{open:p,setOpen:I,isFullscreen:m,onFullscreenChange:z=>a(z?"dashboard":null),fullscreenContainer:h})})})]})]}),c.jsx("div",{ref:Y,className:K("absolute inset-0",!m&&"pointer-events-none")}),e===!0&&!n&&!p&&!g&&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:()=>I(!0),title:"Open Assistant",children:c.jsx(L_,{className:"h-5 w-5"})})})]})]}):null}function pI({children:e}){return c.jsx(Da,{style:{height:"100%",width:"100%"},children:c.jsx(fre,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(er,{delayDuration:0,children:e})})})}function LJ({children:e,preferences:t}){const{currentUser:n}=_s(),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(t9.Provider,{value:r,children:c.jsx(oR,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function zJ(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(Dl,{FallbackComponent:oS,children:c.jsx(k_,{dashboardProps:e,children:c.jsx(pI,{children:c.jsx(LJ,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(TD,{...e,type:"dashboard",children:c.jsx($J,{})})})})})})})}function mI(e){const{tokenProps:t,authToken:n}=Ge(),r=t==null?void 0:t.apiServiceUrl;return bn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return qn(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 BJ(e,t,n){if(t==="source")return{isValid:!0};const r=Xs(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 VJ(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 HJ=e=>{var O;const t=(O=e==null?void 0:e.dataSource)==null?void 0:O.semanticDomainId,{data:n}=mI(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f}=cr(),h=ke(D=>D.card.type),p=e==null?void 0:e.id,m=N.useCallback(D=>{if(!(e!=null&&e.config))return[];switch(D){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((D,I)=>{if(p)switch(D){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((D,I,F)=>{if(!p)return;const V=m(D)[I];if(V)switch(D){case"groupBy":s(p,V.id,{label:F});break;case"metrics":o(p,V.id,{label:F});break;case"pivotBy":i(p,V.id,{label:F});break;case"sortBy":a(p,V.id,{label:F});break}},[p,m,s,o,i,a]),x=N.useCallback((D,I)=>{if(!p)return;const B=m("metrics")[D];B&&o(p,B.id,{aggregate:I,label:MH(B.name,I)})},[p,m,o]),y=N.useCallback((D,I,F)=>{if(!p)return;const V=m("groupBy")[D];if(!V)return;const $={dateFormat:I};I==="custom"&&F?$.customFormat=F:$.customFormat=void 0,s(p,V.id,$)},[p,m,s]),v=N.useCallback((D,I)=>{if(!p)return;const B=m("groupBy")[D];B&&s(p,B.id,{granularity:I})},[p,m,s]),w=N.useCallback((D,I)=>{if(!p)return;const B=m("metrics")[D];B&&o(p,B.id,{aliasTemplate:I})},[p,m,o]),S=N.useCallback((D,I)=>{if(console.log("handleValueAliasesChange",D,I),!p)return;console.log("handleValueAliasesChange",D,I);const B=m("metrics")[D];B&&(console.log("handleValueAliasesChange",I),o(p,B.id,{valueAliases:I}))},[p,m,o]),C=N.useCallback(D=>{if(!p)return;if(m("metrics").length===0){ze.error("Add Metric First",{description:"Please add a metric field before selecting a comparison type",position:"top-center",duration:3e3});return}r(p,{comparisonType:D})},[p,r,m]),j=N.useCallback(D=>{p&&r(p,{showTrendline:D})},[p,r]),_=N.useCallback(D=>{p&&r(p,{trendlineWindow:D})},[p,r]),k=N.useCallback(D=>{p&&r(p,{trendlineGranularity:D})},[p,r]),E=N.useCallback(D=>{p&&r(p,{targetValue:D})},[p,r]),T=N.useCallback(D=>{var H;if(!p)return;const I=[...m("groupBy"),...m("pivotBy"),...m("metrics"),...m("sortBy")],F=_1e(D,I,{joinPlan:(H=e==null?void 0:e.config)==null?void 0:H.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t});if(!F.isValid){F.showError&&kH();return}const B=T1e(D,I,h);if(!B){ze.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const V=BJ(D,B,h);if(!V.isValid){ze.error("Invalid Field Type",{description:V.reason,position:"top-center",duration:3e3});return}const $=m(B);if(EH(D,$))return;const P=DH(D,B,$);if(P){const L=[...$,P];g(B,L),B==="metrics"&&VJ(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((D,I)=>{if(!p)return;const B=m(D)[I];if(B){if(D!=="sortBy"){const V=m("sortBy"),$=V.filter(P=>!(P.name===B.name&&P.qualifiedEntityName===B.qualifiedEntityName));$.length!==V.length&&r(p,{sortByColumns:$})}switch(D){case"groupBy":l(p,B.id);break;case"metrics":u(p,B.id);break;case"pivotBy":d(p,B.id);break;case"sortBy":f(p,B.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:T,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:j,handleKpiTrendlineWindowChange:_,handleKpiTrendlineGranularityChange:k,handleKpiTargetValueChange:E,cardType:h}};function Rx(e,t){var Pe,Qe,Nt,Ze,Lt;const{tokenProps:n}=Ge(),r=Co(),s=Ge().authToken||e,o=ke(Ce=>Ce.selectedConnectionId),i=ke(Ce=>Ce.card),{queryKey:a}=Phe(i),l=ke(Ce=>Ce.selectedDatamodelId),u=ke(Ce=>Ce.isDevMode),d=ke(Ce=>Ce.selectedDatabaseName),f=ke(Ce=>Ce.selectedSchemaName),h=ke(Ce=>Ce.selectedTableName),p=ke(Ce=>Ce.actions.setSelectedConnectionId),m=ke(Ce=>Ce.actions.setSelectedDatamodelId),g=ke(Ce=>Ce.actions.setSelectedDatabaseName),b=ke(Ce=>Ce.actions.setSelectedSchemaName),x=ke(Ce=>Ce.actions.setSelectedTableName);ke(Ce=>Ce.actions.setCardSql);const{setQueryConfig:y}=cr();function v(Ce){var fn;return o&&Ce==="API"?!1:o&&Ce==="S3"?!0:!(!o||!d||d==="NA"||((fn=k==null?void 0:k.capabilities)==null?void 0:fn.path.includes("schema"))&&!f)}function w(Ce){return o&&Ce?!(Ce==="API"||Ce==="S3"):!1}const{refetchConnections:S,connectionsData:C,isConnectionsLoading:j,isConnectionsError:_,selectedConnection:k}=zi(e),{refetch:E,data:T,isLoading:R,isError:O}=bn({queryKey:["models",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),D=k==null?void 0:k.type,I=(k==null?void 0:k.type)==="API"||(k==null?void 0:k.type)==="S3",{data:F,isLoading:B,isFetching:V,isError:$,refetch:P}=bn({queryKey:["databases",o],queryFn:()=>qn(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:w(D)}),{data:H,isLoading:L,isFetching:A,isError:W,refetch:q}=bn({queryKey:["schemas",o,d],queryFn:()=>qn(`${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:U,isFetching:z,isError:G,refetch:Z}=bn({queryKey:["tables",o,d,f],queryFn:()=>qn(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(D)}),{columns:te,isColumnsLoading:X,isColumnsFetching:ne,isColumnsError:se,refetchColumns:ce}=TH(e);N.useEffect(()=>{(D==="S3"||D==="API")&&(g(""),b(""),m(""),D==="API"&&x("api"))},[D,x,g,b,m]);const ae=(k==null?void 0:k.type)==="API"?(Pe=k==null?void 0:k.type)==null?void 0:Pe.toLowerCase():h||"",he=I?"":f||"";function ye(Ce){x(Ce),y(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Te(Ce){b(Ce),x("")}function _e(Ce){g(Ce==="none"?"":Ce),b(""),x(""),Ce!=="none"&&Ce!==""&&m("")}function de(Ce){p(Ce)}function Re(Ce){m(Ce==="none"?"":Ce),Ce!=="none"&&Ce!==""&&g("")}F&&((Qe=F==null?void 0:F.databases)==null?void 0:Qe.length)>0,H&&((Nt=H==null?void 0:H.schemas)==null?void 0:Nt.length)>0;const Oe=C==null?void 0:C.connections.map(Ce=>({id:Ce.id,name:Ce.name,type:Ce.type})),mt=(Ze=T==null?void 0:T.datamodels)==null?void 0:Ze.map(Ce=>({id:Ce.id,name:Ce.name})),be=F==null?void 0:F.databases.map(Ce=>({id:Ce.database_name,name:Ce.database_name})),re=H==null?void 0:H.schemas.map(Ce=>({id:Ce.schema_name,name:Ce.schema_name})),ue=Y==null?void 0:Y.tables.map(Ce=>({id:Ce.table_name,name:Ce.table_name})),we=(Lt=T==null?void 0:T.datamodels.find(Ce=>Ce.id===l))==null?void 0:Lt.name,Se=Uy({schemaName:he,tableName:ae,modelName:we,connectionType:D,databaseName:d||""});return{connectionItems:Oe,selectedConnectionId:o,selectedConnection:k,isConnectionsLoading:j,isConnectionsError:_,modelItems:mt,selectedDatamodelId:l,selectedDatamodelName:we,isModelsLoading:R,isModelsError:O,selectedDatabaseName:d,databaseItems:be,isDatabasesLoadingOrFetching:B||V,isDatabaseError:$,schemaItems:re,selectedSchemaName:f,isSchemaLoadingOrFetching:L||A,isSchemaError:W,tableItems:ue,selectedTableName:h,isTableLoadingOrFetching:U||z,isTableError:G,columns:te,isColumnsLoadingOrFetching:X||ne,isColumnsError:se,isNonDbConnection:I,connectionType:D,tableName:ae,formattedTableName:Se,schemaName:he,refetchConnections:S,refetchModels:E,refetchDatabases:P,refetchSchemas:q,refetchTables:Z,refetchColumns:ce,handleConnectionChange:de,handleDatamodelChange:Re,handleDatabaseChange:_e,handleSchemaChange:Te,handleTableChange:ye}}function cy(e){return`${e}-${Dr()}`}function J$(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 fXe(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 gI(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 UJ(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function WJ(){const e=ke(C=>C.sqlGen),t=ke(C=>C.isDevMode),n=ke(C=>C.card.dataSource),r=ke(C=>{var j,_;return(_=(j=C.card)==null?void 0:j.queryConfig)==null?void 0:_.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=gI(n),a=UJ(n),l=ke(C=>C.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:p,setIsShowingVisual:m}=cr(),{connectionType:g,modelItems:b,selectedDatamodelName:x}=Rx(),y=C=>({column_name:C.name,data_type:C.dataType,label:C.label,description:C.description});return{handleDevModeFieldClick:C=>{var _;if(!t)return;const j=y(C);if(t&&a&&s){const k=b_(j,e);p(k);const E=(_=b==null?void 0:b.find(R=>R.id===l))==null?void 0:_.name,T=g_(k,bi(o||""),bi(s),E||"",g,i||"");T&&(f(T),h(!0))}else if(!t){if(kb(j.data_type))if(r&&r.length>0){const k={...j,role:"groupby",id:cy(j.column_name),name:j.column_name,type:j.data_type};d(k)}else{const k={...j,role:"metric",id:cy(j.column_name),name:j.column_name,label:J$(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(k)}if(Bc(j.data_type)){const k={...j,role:"groupby",id:cy(j.column_name),name:j.column_name,type:j.data_type,label:fXe(j.column_name,"month"),granularity:"month"};d(k)}if(Vo(j.data_type)){const k={...j,role:"metric",id:cy(j.column_name),name:j.column_name,label:J$(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=Uy({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=Uy({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 qJ(){const e=ke(m=>m.selectedConnectionId),t=ke(m=>m.selectedDatamodelId),n=ke(m=>m.selectedDatabaseName),r=ke(m=>m.selectedSchemaName),s=ke(m=>m.selectedTableName),o=J(m=>m.dashboard.filters)||[],i=J(m=>m.selectedSheetId),a=J(m=>m.actions.addFilter),l=J(m=>m.actions.removeFilter),{removeFilterValues:u}=Gt(),{modelItems:d,tableName:f,connectionType:h}=Rx();function p(m,g="sheet",b){var k;const x=bi(m.column_name),y=bi(n||""),v=bi(r||""),w=bi(f);let S=zw({schemaName:v,tableName:w,connectionType:h,databaseName:y}),C=`${S}.${x}`;const j=(k=d==null?void 0:d.find(E=>E.id===t))==null?void 0:k.name;t&&t!=="none"&&(C=`${xg}.${j}.${x}`,S=`${xg}.${j}`),b!=null&&b.qualifiedFieldName&&(C=b.qualifiedFieldName,S=b.qualifiedFieldName.split(".").slice(0,-1).join(".")),b!=null&&b.entityName;let _;if(g==="sheet"&&i?_=ije(o,C,w,n||"",y,i):_=o==null?void 0:o.find(E=>E.column===C&&E.table===w&&(E.database===y||E.database===n)),_)u(_.id),l(_.id);else{const E=Dr(),T=g==="sheet"&&i?[i]:void 0;return f==="api"&&e?(a({location:g,id:E,column:C,title:m.label||m.column_name,dataType:m.data_type,table:"api",database:"",connectionId:e,operation:"in",applyToSheetIds:T,sql:w4(m.data_type,S,x)}),E):(a({id:E,location:g,column:C,title:m.label||m.column_name,dataType:m.data_type,table:s||"",database:n||"",connectionId:e||"",operation:"in",applyToSheetIds:T,sql:w4(m.data_type,S,(b==null?void 0:b.qualifiedFieldName)||x)}),E)}}return{assignFilter:p}}function hXe({column:e}){const[t,n]=N.useState(!1),r=ke(x=>x.card.dataSource),{tableName:s,schemaName:o,databaseName:i}=gI(r),a=ke(x=>x.selectedDatamodelId),l=ke(x=>x.sqlGen),{modelItems:u,connectionType:d}=Rx(),f=ke(x=>x.actions.setSqlGen),h=ke(x=>x.actions.setCardSql),p=ke(x=>x.actions.setRunSql),m=UJ(r);function g(x,y){var C;if(!m||!s){console.warn("Cannot generate SQL: missing table metadata");return}const v=b_(x,l,y),w=(C=u==null?void 0:u.find(j=>j.id===a))==null?void 0:C.name;f(v);const S=g_(v,bi(o||""),bi(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(jp,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(kp,{asChild:!0,children:c.jsx(Mb,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Gd,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:b()})]}):null}function pXe({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 mXe({field:e,context:t="editor",fieldState:n}){const r=ke(L=>L.isDevMode),s=t==="filter",o=r||s||(n==null?void 0:n.state)==="unreachable"&&!s,i=J(L=>L.dashboard.filters),a=J(L=>L.selectedSheetId),l=J(L=>L.actions.removeFilter),{removeFilterValues:u}=Gt(),{assignFilter:d}=qJ(),f=s?Xc(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:_,isDragging:k}=jS({id:e.id,disabled:o}),[E,T]=N.useState(!1),R=ke(L=>L.card),{handleFieldClick:O}=HJ(R),{handleDevModeFieldClick:D,isNumberField:I}=WJ(),F=()=>{m&&(console.log("[SourceField] Removing multi-sheet filter:",m.id),u(m.id),l(m.id)),v(null),x(!1)},B=()=>{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?D(e):O(e)},V={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},$={transform:Pi.Transform.toString(j),transition:_},H=(()=>{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:K("group/container max-w-[265px] overflow-hidden rounded-lg transition-all",k&&"scale-95 opacity-50",!k&&"border",H.borderColor||"border-transparent",H.bgColor||"",H.hoverBorderColor,H.hoverBgColor||"hover:bg-muted",H.opacity,H.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:B,children:[Jg(e.dataType),c.jsx(er,{children:c.jsxs(wn,{children:[c.jsx(Sn,{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 ${E?"whitespace-normal break-words":"truncate"}`,children:e.label||e.name})})}),c.jsx(En,{side:"bottom",align:"start",className:"ml-5 max-w-xs px-4 pb-2 pt-4",children:c.jsx(pXe,{field:e,fieldState:n})})]})}),r&&!s&&I(e)&&c.jsx("div",{onClick:L=>L.stopPropagation(),children:c.jsx(hXe,{column:V})})]}),E&&c.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:c.jsx(xo,{className:"",children:c.jsxs(Mi,{className:"space-y-2 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(c8,{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(vie,{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($b,{open:b,onOpenChange:x,children:c.jsxs(ap,{children:[c.jsxs(lp,{children:[c.jsx(up,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(dp,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(cp,{children:[c.jsx(hp,{children:"Cancel"}),c.jsx(fp,{onClick:F,children:"Remove Filter"})]})]})})]})}const gXe="SEMAPHOR_CALCULATED_FIELD",bXe=["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 YJ(e){return!!e.expression}function xXe(e){return!!e.expression}function yXe(e){return!!e.expression}var GJ=(e=>(e.SUBTOTAL="__SUBTOTAL__",e.TOTAL="__TOTAL__",e.ALL="__ALL__",e))(GJ||{}),Al="Accordion",vXe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[bI,wXe,SXe]=t1(Al),[ZS]=Er(Al,[SXe,FZ]),xI=FZ(),ZJ=N.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(bI.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(kXe,{...o,ref:t}):c.jsx(jXe,{...s,ref:t})})});ZJ.displayName=Al;var[KJ,CXe]=ZS(Al),[XJ,NXe]=ZS(Al,{collapsible:!1}),jXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=Fr({prop:n,defaultProp:r,onChange:s});return c.jsx(KJ,{scope:e.__scopeAccordion,value:a?[a]:[],onItemOpen:l,onItemClose:N.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(XJ,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(QJ,{...i,ref:t})})})}),kXe=N.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i=[],a]=Fr({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(KJ,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(XJ,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(QJ,{...o,ref:t})})})}),[EXe,KS]=ZS(Al),QJ=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=wXe(n),f=$d(s)==="ltr",h=je(e.onKeyDown,p=>{var _;if(!vXe.includes(p.key))return;const m=p.target,g=u().filter(k=>{var E;return!((E=k.ref.current)!=null&&E.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;(_=g[j].ref.current)==null||_.focus()});return c.jsx(EXe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(bI.Slot,{scope:n,children:c.jsx(Be.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),Tw="AccordionItem",[_Xe,yI]=ZS(Tw),JJ=N.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=KS(Tw,n),i=CXe(Tw,n),a=xI(n),l=rr(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(_Xe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(zZ,{"data-orientation":o.orientation,"data-state":oee(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});JJ.displayName=Tw;var eee="AccordionHeader",tee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(Al,n),o=yI(eee,n);return c.jsx(Be.h3,{"data-orientation":s.orientation,"data-state":oee(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});tee.displayName=eee;var t_="AccordionTrigger",nee=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(Al,n),o=yI(t_,n),i=NXe(t_,n),a=xI(n);return c.jsx(bI.ItemSlot,{scope:n,children:c.jsx(T4e,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});nee.displayName=t_;var ree="AccordionContent",see=N.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=KS(Al,n),o=yI(ree,n),i=xI(n);return c.jsx(R4e,{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}})});see.displayName=ree;function oee(e){return e?"open":"closed"}var MXe=ZJ,DXe=JJ,TXe=tee,iee=nee,aee=see;const lee=MXe,vI=M.forwardRef(({className:e,...t},n)=>c.jsx(DXe,{ref:n,className:K("border-b",e),...t}));vI.displayName="AccordionItem";const wI=M.forwardRef(({className:e,children:t,...n},r)=>c.jsx(TXe,{className:"flex",children:c.jsxs(iee,{ref:r,className:K("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(Gs,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));wI.displayName=iee.displayName;const SI=M.forwardRef(({className:e,children:t,...n},r)=>c.jsx(aee,{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:K("pb-4 pt-0",e),children:t})}));SI.displayName=aee.displayName;function RXe({context:e="editor"}={}){var E,T,R,O;const[t,n]=N.useState(""),[r,s]=N.useState("all");ke(D=>D.isDevMode);const o=ke(D=>D.card.dataSource),i=ke(D=>D.card.config),a=ke(D=>D.card),{autoJoinMetadata:l}=wa(a),{columns:u=[],columnGroups:d=[],isLoading:f,error:h}=hD(),p=(o==null?void 0:o.mode)==="semanticDomain"?o.semanticDomainId:void 0,{data:m}=mI(p),g=[...(i==null?void 0:i.groupByColumns)||[],...(i==null?void 0:i.metricColumns)||[]];(T=(E=i==null?void 0:i.joinPlan)==null?void 0:E.baseEntity)==null||T.name,(O=(R=l==null?void 0:l.resolvedJoinPlan)==null?void 0:R.baseEntity)==null||O.name,WJ();const b=u.filter(D=>D.name.toLowerCase().includes(t.toLowerCase())||D.dataType.toLowerCase().includes(t.toLowerCase())||D.label&&D.label.toLowerCase().includes(t.toLowerCase())||D.qualifiedEntityName&&D.qualifiedEntityName.toLowerCase().includes(t.toLowerCase())),x=D=>{if(D.role==="metric"&&YJ(D)||D.role==="groupby"&&D.expression)return"calculated";if(D.dataType==="number"||D.dataType==="integer"||D.dataType==="float"||D.dataType==="decimal"||D.dataType==="currency")return"metrics";const I=Xs(D.dataType);return["date","string","boolean"].includes(I)?"dimensions":I==="number"?"metrics":"dimensions"},v=(r==="all"?b:b.filter(D=>x(D)===r)).reduce((D,I)=>{const F=I.qualifiedEntityName||"Other Fields";return D[F]||(D[F]={label:y_(I.entityName),fields:[]}),D[F].fields.push(I),D},{}),S=Object.keys(v),C=b.filter(D=>x(D)==="dimensions").length,j=b.filter(D=>x(D)==="metrics").length,_=b.filter(D=>x(D)==="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(Tc,{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(hl,{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(Es,{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(hl,{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(Ea,{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:D=>n(D.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(ls,{defaultValue:"all",value:r,onValueChange:D=>s(D),className:"mb-4",children:c.jsxs(Ur,{className:"grid h-9 w-full grid-cols-4",children:[c.jsxs(Ut,{value:"all",className:"text-xs",children:["All",c.jsx("span",{className:"ml-2 text-xs font-semibold",children:b.length})]}),c.jsxs(Ut,{value:"dimensions",className:"text-xs",children:[c.jsx(Xw,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:C})]}),c.jsxs(Ut,{value:"metrics",className:"text-xs",children:[c.jsx(Zh,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:j})]}),c.jsxs(Ut,{value:"calculated",className:"text-xs",children:[c.jsx(M_,{className:"size-4 shrink-0"}),c.jsx("span",{className:"ml-2 text-xs font-semibold",children:_})]})]})})]}),c.jsxs(_l,{className:"py-2",children:[c.jsx(lee,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(v).map(([D,I])=>{const F=d.find(B=>B.entityName===D)||{entityName:D,label:I.label};return c.jsxs(vI,{value:D,className:"border-none",children:[c.jsx(wI,{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(SI,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:I.fields.map(B=>{const V=pD(B,{joinabilityMap:(m==null?void 0:m.joinabilityMap)||null,selectedFields:g,cardConfig:i,autoJoinMetadata:l});return c.jsx(mXe,{field:B,context:e,fieldState:V},B.id)})})})]},D)})}),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(Ko,{orientation:"horizontal"}),c.jsx(Ko,{orientation:"vertical"})]})]})}function cee({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(RXe,{context:e})," "]})}function uee(){const e=ke(i=>i.card.dataSource),{setSelectedConnectionId:t,setSelectedDatabaseName:n,setSelectedSchemaName:r,setSelectedTableName:s,setSelectedDatamodelId:o}=cr();N.useEffect(()=>{var p;if(!e)return;const{tableName:i,schemaName:a,databaseName:l,connectionId:u}=gI(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 IXe(){uee();const e=J(l=>l.selectedSheetId),t=J(l=>l.selectedFrameId),n=J(l=>l.dashboard),r=J(l=>l.actions.getSelectedFrame),{setSelectedFrameId:s}=Gt(),{setCard:o}=cr(),i=ke(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 AXe(){const e=J(n=>n.actions.setShowFilters),{hasEntities:t}=IXe();return c.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l",children:[c.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-4",children:[c.jsx(le,{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(PZ,{})})]}),!t&&c.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-6 py-12 text-center",children:[c.jsx(hl,{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",children:c.jsx(CS,{collisionDetection:yS,children:c.jsx(NS,{items:[],strategy:vR,children:c.jsx(cee,{context:"filter"})})})})]})}function PXe(){const e=J(r=>r.dashboard.filters),t=J(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?c.jsx("div",{className:K("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(aR,{filter:r}),c.jsx(mS,{filter:r})]},r.id))}):null}function OXe(){const e=J(r=>r.showFilters),t=J(r=>r.isVisualEditing),n=J(r=>r.isDashboardEditing);return c.jsxs("div",{role:"dashboard-plus-main",className:K("",{"max-h-0 overflow-hidden":t,"flex grow overflow-auto":!t}),children:[c.jsxs("section",{className:"flex grow flex-col",children:[n&&c.jsx(PXe,{}),c.jsx($J,{})]}),e&&c.jsx("div",{role:"filter-aside-container",className:"flex",children:c.jsx(AXe,{})})]})}const FXe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-DKci3my0.js"))),$Xe=N.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BtV3RWgf.js"))),LXe=N.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-C0CKQW3d.js"))),zXe=N.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-BQVERuRi.js")).then(e=>({default:e.ResourceManagementPanel})));function BXe({showControls:e=!1,showFooter:t=!0,...n}){const r=J(m=>m.isDashboardPanelOpen),s=J(m=>m.isVisualEditing),o=J(m=>m.showDashboardJSON),i=J(m=>m.actions.setIsDashboardPanelOpen),a=20,l=20,u=30,d=r,f=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{f.current&&h.current&&(r?(f.current.resize(a),h.current.resize(100-a)):(f.current.resize(0),h.current.resize(100)))},[r]);const{preferences:p}=n;return c.jsx(Dl,{FallbackComponent:oS,children:c.jsxs(k_,{dashboardProps:n,children:[c.jsx(Que,{}),c.jsx(pI,{children:c.jsxs(LJ,{preferences:p,children:[o&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(LXe,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col",children:[e&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(FXe,{})}),c.jsxs(TR,{direction:"horizontal",className:"flex grow overflow-hidden",children:[c.jsx(ib,{ref:f,className:K("flex h-full max-w-[26rem] overflow-hidden",{"min-w-[20rem]":d}),defaultSize:d?a:0,minSize:d?l:0,maxSize:d?u:0,children:d&&c.jsx(N.Suspense,{fallback:null,children:c.jsx(zXe,{isOpen:r,onClose:()=>i(!1),variant:"inline"})})}),c.jsx(JK,{className:K("",{"w-0":!d})}),c.jsx(ib,{ref:h,className:"flex min-w-0 flex-1",defaultSize:d?100-a:100,minSize:d?40:100,children:c.jsxs(TD,{...n,type:"dashboard",children:[s&&c.jsx(N.Suspense,{fallback:null,children:c.jsx($Xe,{})}),c.jsx(OXe,{})]})})]})]})]})})]})})}var VXe=Object.defineProperty,HXe=(e,t,n)=>t in e?VXe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,uy=(e,t,n)=>HXe(e,typeof t!="symbol"?t+"":t,n);const UXe={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},WXe={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}},qXe={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)},YXe={stringify:e=>`${e}`,parse:e=>parseFloat(e)},GXe={stringify:e=>e,parse:e=>e},U2={string:GXe,number:YXe,boolean:UXe,function:WXe,json:qXe};function ZXe(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}const dy=Symbol.for("r2wc.render"),fy=Symbol.for("r2wc.connected"),gu=Symbol.for("r2wc.context"),za=Symbol.for("r2wc.props");function KXe(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=ZXe(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(),uy(this,o,!0),uy(this,s),uy(this,r,{}),uy(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[za].container=this.container;for(const m of i){const g=d[m],b=this.getAttribute(g),x=l[m],y=x?U2[x]:null;y!=null&&y.parse&&b&&(this[za][m]=y.parse(b,g,this))}for(const m of a)this[za][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[fy]=!0,this[dy]()}disconnectedCallback(){this[fy]=!1,this[gu]&&n.unmount(this[gu]),delete this[gu]}attributeChangedCallback(m,g,b){const x=f[m],y=l[x],v=y?U2[y]:null;x in l&&v!=null&&v.parse&&b&&(this[za][x]=v.parse(b,m,this),this[dy]())}[(o=fy,s=gu,r=za,dy)](){this[fy]&&(this[gu]?n.update(this[gu],this[za]):this[gu]=n.mount(this.container,e,this[za]))}}for(const p of i){const m=d[p],g=l[p];Object.defineProperty(h.prototype,p,{enumerable:!0,configurable:!0,get(){return this[za][p]},set(b){this[za][p]=b;const x=g?U2[g]:null;if(x!=null&&x.stringify){const y=x.stringify(b,m,this);this.getAttribute(m)!==y&&this.setAttribute(m,y)}else this[dy]()}})}return h}function XXe(e,t,n){const r=rj(e),s=N.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function QXe({root:e,ReactComponent:t},n){const r=N.createElement(t,n);e.render(r)}function JXe({root:e}){e.unmount()}function eQe(e,t={}){return KXe(e,t,{mount:XXe,update:QXe,unmount:JXe})}const tQe={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"},nQe=eQe(zJ,{props:tQe});function rQe(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 tL(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){rQe(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 sQe(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 oQe(e,t){if(e==null)return{};var n=sQe(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 iQe(e,t){return aQe(e)||lQe(e,t)||cQe(e,t)||uQe()}function aQe(e){if(Array.isArray(e))return e}function lQe(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 cQe(e,t){if(e){if(typeof e=="string")return nL(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 nL(e,t)}}function nL(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 uQe(){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 dQe(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rL(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 sL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?rL(Object(n),!0).forEach(function(r){dQe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):rL(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function fQe(){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 zm(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 Rw(e){return{}.toString.call(e).includes("Object")}function hQe(e){return!Object.keys(e).length}function gb(e){return typeof e=="function"}function pQe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function mQe(e,t){return Rw(t)||xc("changeType"),Object.keys(t).some(function(n){return!pQe(e,n)})&&xc("changeField"),t}function gQe(e){gb(e)||xc("selectorType")}function bQe(e){gb(e)||Rw(e)||xc("handlerType"),Rw(e)&&Object.values(e).some(function(t){return!gb(t)})&&xc("handlersType")}function xQe(e){e||xc("initialIsRequired"),Rw(e)||xc("initialType"),hQe(e)&&xc("initialContent")}function yQe(e,t){throw new Error(e[t]||e.default)}var vQe={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"},xc=zm(yQe)(vQe),hy={changes:mQe,selector:gQe,handler:bQe,initial:xQe};function wQe(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};hy.initial(e),hy.handler(t);var n={current:e},r=zm(NQe)(n,t),s=zm(CQe)(n),o=zm(hy.changes)(e),i=zm(SQe)(n);function a(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(d){return d};return hy.selector(u),u(n.current)}function l(u){fQe(r,s,o,i)(u)}return[a,l]}function SQe(e,t){return gb(t)?t(e.current):t}function CQe(e,t){return e.current=sL(sL({},e.current),t),t}function NQe(e,t,n){return gb(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 jQe={create:wQe},kQe={paths:{vs:"https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs"}};function EQe(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 _Qe(e){return{}.toString.call(e).includes("Object")}function MQe(e){return e||oL("configIsRequired"),_Qe(e)||oL("configType"),e.urls?(DQe(),{paths:{vs:e.urls.monacoBase}}):e}function DQe(){console.warn(dee.deprecation)}function TQe(e,t){throw new Error(e[t]||e.default)}var dee={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
|
|