react-semaphor 0.1.455 → 0.1.456
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/brand-studio/index.cjs +1 -1
- package/dist/brand-studio/index.js +1 -1
- package/dist/chunks/{dashboard-briefing-launcher-BmEHYblf.cjs → dashboard-briefing-launcher-B_ZDOOzA.cjs} +1 -1
- package/dist/chunks/{dashboard-briefing-launcher-BgBMjAVe.js → dashboard-briefing-launcher-DPbSnj9m.js} +3 -3
- package/dist/chunks/{dashboard-controls-BLNG_zHC.cjs → dashboard-controls-BBnq7SH-.cjs} +1 -1
- package/dist/chunks/{dashboard-controls-C-23EDdr.js → dashboard-controls-yOJOMobf.js} +4 -4
- package/dist/chunks/{dashboard-json-BJ_Z9EaL.cjs → dashboard-json-BEw43pFy.cjs} +1 -1
- package/dist/chunks/{dashboard-json-BTF-1Iwa.js → dashboard-json-ChYuh43q.js} +2 -2
- package/dist/chunks/{edit-dashboard-visual-CR832BJc.cjs → edit-dashboard-visual-DDVhyor8.cjs} +1 -1
- package/dist/chunks/{edit-dashboard-visual-Mw-ZE7P7.js → edit-dashboard-visual-DvAI9rwj.js} +3 -3
- package/dist/chunks/{editor-action-buttons-BVigIMg0.cjs → editor-action-buttons-BnMAJDMZ.cjs} +1 -1
- package/dist/chunks/{editor-action-buttons-BxbFCerU.js → editor-action-buttons-FCsvW-0C.js} +2 -2
- package/dist/chunks/{index-DIWJALWL.cjs → index-DEwVo0GH.cjs} +5 -5
- package/dist/chunks/{index-B5Oy1eLv.js → index-xki38iaF.js} +7 -7
- package/dist/chunks/{report-preferences-dialog-BgE3Gzsp.cjs → report-preferences-dialog-CdHVi8_W.cjs} +1 -1
- package/dist/chunks/{report-preferences-dialog-CFenWkcH.js → report-preferences-dialog-VRe-9gct.js} +2 -2
- package/dist/chunks/{switch-D-CCcfhc.cjs → switch-BHOdIXq3.cjs} +1 -1
- package/dist/chunks/{switch-BeZW-HnS.js → switch-BOBLNHUj.js} +2 -2
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/data-app-builder/index.cjs +1 -1
- package/dist/data-app-builder/index.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +6 -6
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Lxe=Object.defineProperty;var sB=e=>{throw TypeError(e)};var $xe=(e,t,n)=>t in e?Lxe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ne=(e,t,n)=>$xe(e,typeof t!="symbol"?t+"":t,n),$T=(e,t,n)=>t.has(e)||sB("Cannot "+n);var ve=(e,t,n)=>($T(e,t,"read from private field"),n?n.call(e):t.get(e)),At=(e,t,n)=>t.has(e)?sB("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),yt=(e,t,n,r)=>($T(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Qt=(e,t,n)=>($T(e,t,"access private method"),n);var hC=(e,t,n,r)=>({set _(o){yt(e,t,o,n)},get _(){return ve(e,t,r)}});const l=require("react/jsx-runtime"),v=require("react"),br=require("react-dom"),p=require("./switch-D-CCcfhc.cjs"),je=require("./x-B6ghREd2.cjs"),dt=require("./saved-temporal-bucket-format-CFfWXRl9.cjs"),va=require("./validators-BDYprKI9.cjs");require("./analyze-result-contract-LPDNldic.cjs");const Li=require("../value-format-preferences/index.cjs"),cf=require("./index-ByFbacH7.cjs"),zxe=require("react-dom/client"),qc=require("./temporal-bucket-authoring-o3Emn05L.cjs"),Ft=require("./search-BqqhaMx9.cjs"),Tk=require("./canonical-result-keys-BA0HCP4e.cjs"),Bxe=require("./color-CyB5o13F.cjs"),Vxe=require("./token-types-D7CaaI80.cjs"),it=require("./index-C99Ow35Y.cjs"),$r=require("./temporal-bucket-DHY1y9lq.cjs"),fn=require("./pivot-header-presentation-DhyQXxKq.cjs"),wa=require("./pivot-result-identity-Bb4EixVN.cjs"),$t=require("./pivot-result-lifecycle-DmcF1ris.cjs"),Kt=require("./format-types-PSZZ7hG8.cjs"),Oi=require("./matrix-result-contract-zamd9euI.cjs"),Ho=require("./normalize-dashboard-for-dirty-check-BXRUMVb2.cjs"),xr=require("./common-types-C57kJ59w.cjs"),nY=require("../dashboard-assistant/index.cjs"),rY=require("./report-runtime-context-DqxS4wbi.cjs"),Hxe=require("./contracts-CtB2VONT.cjs"),qxe=require("../layouts/index.cjs"),iB=require("./index-F25jnH0p.cjs");function rO(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const aB=rO(l),te=rO(v),V2=rO(br);function Uxe(e){return Kt.toDate(e).getMonth()}function Wxe(e){return Kt.toDate(e).getFullYear()}function Xx(e,t){const r=Zxe(e);let o;if(r.date){const c=Xxe(r.date,2);o=Qxe(c.restDateString,c.year)}if(!o||isNaN(o.getTime()))return new Date(NaN);const s=o.getTime();let i=0,a;if(r.time&&(i=Jxe(r.time),isNaN(i)))return new Date(NaN);if(r.timezone){if(a=eye(r.timezone),isNaN(a))return new Date(NaN)}else{const c=new Date(s+i),u=new Date(0);return u.setFullYear(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()),u.setHours(c.getUTCHours(),c.getUTCMinutes(),c.getUTCSeconds(),c.getUTCMilliseconds()),u}return new Date(s+i+a)}const mC={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},Kxe=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,Gxe=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,Yxe=/^([+-])(\d{2})(?::?(\d{2}))?$/;function Zxe(e){const t={},n=e.split(mC.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],mC.timeZoneDelimiter.test(t.date)&&(t.date=e.split(mC.timeZoneDelimiter)[0],r=e.substr(t.date.length,e.length))),r){const o=mC.timezone.exec(r);o?(t.time=r.replace(o[1],""),t.timezone=o[1]):t.time=r}return t}function Xxe(e,t){const n=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),r=e.match(n);if(!r)return{year:NaN,restDateString:""};const o=r[1]?parseInt(r[1]):null,s=r[2]?parseInt(r[2]):null;return{year:s===null?o:s*100,restDateString:e.slice((r[1]||r[2]).length)}}function Qxe(e,t){if(t===null)return new Date(NaN);const n=e.match(Kxe);if(!n)return new Date(NaN);const r=!!n[4],o=ux(n[1]),s=ux(n[2])-1,i=ux(n[3]),a=ux(n[4]),c=ux(n[5])-1;if(r)return sye(t,a,c)?tye(t,a,c):new Date(NaN);{const u=new Date(0);return!rye(t,s,i)||!oye(t,o)?new Date(NaN):(u.setUTCFullYear(t,s,Math.max(o,i)),u)}}function ux(e){return e?parseInt(e):1}function Jxe(e){const t=e.match(Gxe);if(!t)return NaN;const n=zT(t[1]),r=zT(t[2]),o=zT(t[3]);return iye(n,r,o)?n*Kt.millisecondsInHour+r*Kt.millisecondsInMinute+o*1e3:NaN}function zT(e){return e&&parseFloat(e.replace(",","."))||0}function eye(e){if(e==="Z")return 0;const t=e.match(Yxe);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),o=t[3]&&parseInt(t[3])||0;return aye(r,o)?n*(r*Kt.millisecondsInHour+o*Kt.millisecondsInMinute):NaN}function tye(e,t,n){const r=new Date(0);r.setUTCFullYear(e,0,4);const o=r.getUTCDay()||7,s=(t-1)*7+n+1-o;return r.setUTCDate(r.getUTCDate()+s),r}const nye=[31,null,31,30,31,30,31,31,30,31,30,31];function oY(e){return e%400===0||e%4===0&&e%100!==0}function rye(e,t,n){return t>=0&&t<=11&&n>=1&&n<=(nye[t]||(oY(e)?29:28))}function oye(e,t){return t>=1&&t<=(oY(e)?366:365)}function sye(e,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function iye(e,t,n){return e===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&e>=0&&e<25}function aye(e,t){return t>=0&&t<=59}var sN={exports:{}};sN.exports;(function(e,t){var n=200,r="__lodash_hash_undefined__",o=800,s=16,i=9007199254740991,a="[object Arguments]",c="[object Array]",u="[object AsyncFunction]",d="[object Boolean]",f="[object Date]",h="[object Error]",m="[object Function]",g="[object GeneratorFunction]",b="[object Map]",x="[object Number]",y="[object Null]",w="[object Object]",C="[object Proxy]",N="[object RegExp]",S="[object Set]",j="[object String]",_="[object Undefined]",k="[object WeakMap]",T="[object ArrayBuffer]",I="[object DataView]",E="[object Float32Array]",D="[object Float64Array]",R="[object Int8Array]",A="[object Int16Array]",F="[object Int32Array]",z="[object Uint8Array]",L="[object Uint8ClampedArray]",$="[object Uint16Array]",H="[object Uint32Array]",M=/[\\^$.*+?()[\]{}|]/g,B=/^\[object .+?Constructor\]$/,W=/^(?:0|[1-9]\d*)$/,P={};P[E]=P[D]=P[R]=P[A]=P[F]=P[z]=P[L]=P[$]=P[H]=!0,P[a]=P[c]=P[T]=P[d]=P[I]=P[f]=P[h]=P[m]=P[b]=P[x]=P[w]=P[N]=P[S]=P[j]=P[k]=!1;var G=typeof dt.commonjsGlobal=="object"&&dt.commonjsGlobal&&dt.commonjsGlobal.Object===Object&&dt.commonjsGlobal,Z=typeof self=="object"&&self&&self.Object===Object&&self,X=G||Z||Function("return this")(),Y=t&&!t.nodeType&&t,O=Y&&!0&&e&&!e.nodeType&&e,q=O&&O.exports===Y,U=q&&G.process,V=function(){try{var be=O&&O.require&&O.require("util").types;return be||U&&U.binding&&U.binding("util")}catch{}}(),K=V&&V.isTypedArray;function Q(be,_e,qe){switch(qe.length){case 0:return be.call(_e);case 1:return be.call(_e,qe[0]);case 2:return be.call(_e,qe[0],qe[1]);case 3:return be.call(_e,qe[0],qe[1],qe[2])}return be.apply(_e,qe)}function se(be,_e){for(var qe=-1,Ot=Array(be);++qe<be;)Ot[qe]=_e(qe);return Ot}function oe(be){return function(_e){return be(_e)}}function me(be,_e){return be==null?void 0:be[_e]}function le(be,_e){return function(qe){return be(_e(qe))}}var ue=Array.prototype,ne=Function.prototype,de=Object.prototype,Ce=X["__core-js_shared__"],ce=ne.toString,ie=de.hasOwnProperty,we=function(){var be=/[^.]+$/.exec(Ce&&Ce.keys&&Ce.keys.IE_PROTO||"");return be?"Symbol(src)_1."+be:""}(),fe=de.toString,ae=ce.call(Object),ee=RegExp("^"+ce.call(ie).replace(M,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),J=q?X.Buffer:void 0,re=X.Symbol,pe=X.Uint8Array;J&&J.allocUnsafe;var Ee=le(Object.getPrototypeOf,Object),Te=Object.create,ze=de.propertyIsEnumerable,Pe=ue.splice,He=re?re.toStringTag:void 0,ye=function(){try{var be=Co(Object,"defineProperty");return be({},"",{}),be}catch{}}(),Ke=J?J.isBuffer:void 0,We=Math.max,Qe=Date.now,xe=Co(X,"Map"),Ve=Co(Object,"create"),Ae=function(){function be(){}return function(_e){if(!Ht(_e))return{};if(Te)return Te(_e);be.prototype=_e;var qe=new be;return be.prototype=void 0,qe}}();function ke(be){var _e=-1,qe=be==null?0:be.length;for(this.clear();++_e<qe;){var Ot=be[_e];this.set(Ot[0],Ot[1])}}function Be(){this.__data__=Ve?Ve(null):{},this.size=0}function Ie(be){var _e=this.has(be)&&delete this.__data__[be];return this.size-=_e?1:0,_e}function $e(be){var _e=this.__data__;if(Ve){var qe=_e[be];return qe===r?void 0:qe}return ie.call(_e,be)?_e[be]:void 0}function st(be){var _e=this.__data__;return Ve?_e[be]!==void 0:ie.call(_e,be)}function ct(be,_e){var qe=this.__data__;return this.size+=this.has(be)?0:1,qe[be]=Ve&&_e===void 0?r:_e,this}ke.prototype.clear=Be,ke.prototype.delete=Ie,ke.prototype.get=$e,ke.prototype.has=st,ke.prototype.set=ct;function rt(be){var _e=-1,qe=be==null?0:be.length;for(this.clear();++_e<qe;){var Ot=be[_e];this.set(Ot[0],Ot[1])}}function Ct(){this.__data__=[],this.size=0}function Lt(be){var _e=this.__data__,qe=ot(_e,be);if(qe<0)return!1;var Ot=_e.length-1;return qe==Ot?_e.pop():Pe.call(_e,qe,1),--this.size,!0}function vt(be){var _e=this.__data__,qe=ot(_e,be);return qe<0?void 0:_e[qe][1]}function Tt(be){return ot(this.__data__,be)>-1}function Me(be,_e){var qe=this.__data__,Ot=ot(qe,be);return Ot<0?(++this.size,qe.push([be,_e])):qe[Ot][1]=_e,this}rt.prototype.clear=Ct,rt.prototype.delete=Lt,rt.prototype.get=vt,rt.prototype.has=Tt,rt.prototype.set=Me;function Je(be){var _e=-1,qe=be==null?0:be.length;for(this.clear();++_e<qe;){var Ot=be[_e];this.set(Ot[0],Ot[1])}}function kt(){this.size=0,this.__data__={hash:new ke,map:new(xe||rt),string:new ke}}function mt(be){var _e=Lr(this,be).delete(be);return this.size-=_e?1:0,_e}function _t(be){return Lr(this,be).get(be)}function Rt(be){return Lr(this,be).has(be)}function Pt(be,_e){var qe=Lr(this,be),Ot=qe.size;return qe.set(be,_e),this.size+=qe.size==Ot?0:1,this}Je.prototype.clear=kt,Je.prototype.delete=mt,Je.prototype.get=_t,Je.prototype.has=Rt,Je.prototype.set=Pt;function wt(be){var _e=this.__data__=new rt(be);this.size=_e.size}function Et(){this.__data__=new rt,this.size=0}function Bt(be){var _e=this.__data__,qe=_e.delete(be);return this.size=_e.size,qe}function un(be){return this.__data__.get(be)}function Ge(be){return this.__data__.has(be)}function Re(be,_e){var qe=this.__data__;if(qe instanceof rt){var Ot=qe.__data__;if(!xe||Ot.length<n-1)return Ot.push([be,_e]),this.size=++qe.size,this;qe=this.__data__=new Je(Ot)}return qe.set(be,_e),this.size=qe.size,this}wt.prototype.clear=Et,wt.prototype.delete=Bt,wt.prototype.get=un,wt.prototype.has=Ge,wt.prototype.set=Re;function De(be,_e){var qe=vc(be),Ot=!qe&&yc(be),gn=!qe&&!Ot&&us(be),Vn=!qe&&!Ot&&!gn&&Gt(be),mr=qe||Ot||gn||Vn,Hn=mr?se(be.length,String):[],cr=Hn.length;for(var _i in be)mr&&(_i=="length"||gn&&(_i=="offset"||_i=="parent")||Vn&&(_i=="buffer"||_i=="byteLength"||_i=="byteOffset")||xl(_i,cr))||Hn.push(_i);return Hn}function he(be,_e,qe){(qe!==void 0&&!yl(be[_e],qe)||qe===void 0&&!(_e in be))&&Dt(be,_e,qe)}function Fe(be,_e,qe){var Ot=be[_e];(!(ie.call(be,_e)&&yl(Ot,qe))||qe===void 0&&!(_e in be))&&Dt(be,_e,qe)}function ot(be,_e){for(var qe=be.length;qe--;)if(yl(be[qe][0],_e))return qe;return-1}function Dt(be,_e,qe){_e=="__proto__"&&ye?ye(be,_e,{configurable:!0,enumerable:!0,value:qe,writable:!0}):be[_e]=qe}var nt=Rs();function ge(be){return be==null?be===void 0?_:y:He&&He in Object(be)?Qi(be):oi(be)}function Se(be){return wn(be)&&ge(be)==a}function Oe(be){if(!Ht(be)||Ps(be))return!1;var _e=Wu(be)?ee:B;return _e.test(Uu(be))}function Ye(be){return wn(be)&&Xe(be.length)&&!!P[ge(be)]}function bt(be){if(!Ht(be))return qu(be);var _e=If(be),qe=[];for(var Ot in be)Ot=="constructor"&&(_e||!ie.call(be,Ot))||qe.push(Ot);return qe}function St(be,_e,qe,Ot,gn){be!==_e&&nt(_e,function(Vn,mr){if(gn||(gn=new wt),Ht(Vn))on(be,_e,mr,qe,St,Ot,gn);else{var Hn=Ot?Ot($n(be,mr),Vn,mr+"",be,_e,gn):void 0;Hn===void 0&&(Hn=Vn),he(be,mr,Hn)}},An)}function on(be,_e,qe,Ot,gn,Vn,mr){var Hn=$n(be,qe),cr=$n(_e,qe),_i=mr.get(cr);if(_i){he(be,qe,_i);return}var Fs=Vn?Vn(Hn,cr,qe+"",be,_e,mr):void 0,Gu=Fs===void 0;if(Gu){var lx=vc(cr),cx=!lx&&us(cr),fC=!lx&&!cx&&Gt(cr);Fs=cr,lx||cx||fC?vc(Hn)?Fs=Hn:So(Hn)?Fs=Vt(Hn):cx?(Gu=!1,Fs=et(cr)):fC?(Gu=!1,Fs=ht(cr)):Fs=[]:nn(cr)||yc(cr)?(Fs=Hn,yc(Hn)?Fs=or(Hn):(!Ht(Hn)||Wu(Hn))&&(Fs=Hu(cr))):Gu=!1}Gu&&(mr.set(cr,Fs),gn(Fs,cr,Ot,Vn,mr),mr.delete(cr)),he(be,qe,Fs)}function sn(be,_e){return Tf(xc(be,_e,co),be+"")}var Le=ye?function(be,_e){return ye(be,"toString",{configurable:!0,enumerable:!1,value:Nr(_e),writable:!0})}:co;function et(be,_e){return be.slice()}function at(be){var _e=new be.constructor(be.byteLength);return new pe(_e).set(new pe(be)),_e}function ht(be,_e){var qe=at(be.buffer);return new be.constructor(qe,be.byteOffset,be.length)}function Vt(be,_e){var qe=-1,Ot=be.length;for(_e||(_e=Array(Ot));++qe<Ot;)_e[qe]=be[qe];return _e}function Xn(be,_e,qe,Ot){var gn=!qe;qe||(qe={});for(var Vn=-1,mr=_e.length;++Vn<mr;){var Hn=_e[Vn],cr=void 0;cr===void 0&&(cr=be[Hn]),gn?Dt(qe,Hn,cr):Fe(qe,Hn,cr)}return qe}function Go(be){return sn(function(_e,qe){var Ot=-1,gn=qe.length,Vn=gn>1?qe[gn-1]:void 0,mr=gn>2?qe[2]:void 0;for(Vn=be.length>3&&typeof Vn=="function"?(gn--,Vn):void 0,mr&&ki(qe[0],qe[1],mr)&&(Vn=gn<3?void 0:Vn,gn=1),_e=Object(_e);++Ot<gn;){var Hn=qe[Ot];Hn&&be(_e,Hn,Ot,Vn)}return _e})}function Rs(be){return function(_e,qe,Ot){for(var gn=-1,Vn=Object(_e),mr=Ot(_e),Hn=mr.length;Hn--;){var cr=mr[++gn];if(qe(Vn[cr],cr,Vn)===!1)break}return _e}}function Lr(be,_e){var qe=be.__data__;return As(_e)?qe[typeof _e=="string"?"string":"hash"]:qe.map}function Co(be,_e){var qe=me(be,_e);return Oe(qe)?qe:void 0}function Qi(be){var _e=ie.call(be,He),qe=be[He];try{be[He]=void 0;var Ot=!0}catch{}var gn=fe.call(be);return Ot&&(_e?be[He]=qe:delete be[He]),gn}function Hu(be){return typeof be.constructor=="function"&&!If(be)?Ae(Ee(be)):{}}function xl(be,_e){var qe=typeof be;return _e=_e??i,!!_e&&(qe=="number"||qe!="symbol"&&W.test(be))&&be>-1&&be%1==0&&be<_e}function ki(be,_e,qe){if(!Ht(qe))return!1;var Ot=typeof _e;return(Ot=="number"?vl(qe)&&xl(_e,qe.length):Ot=="string"&&_e in qe)?yl(qe[_e],be):!1}function As(be){var _e=typeof be;return _e=="string"||_e=="number"||_e=="symbol"||_e=="boolean"?be!=="__proto__":be===null}function Ps(be){return!!we&&we in be}function If(be){var _e=be&&be.constructor,qe=typeof _e=="function"&&_e.prototype||de;return be===qe}function qu(be){var _e=[];if(be!=null)for(var qe in Object(be))_e.push(qe);return _e}function oi(be){return fe.call(be)}function xc(be,_e,qe){return _e=We(_e===void 0?be.length-1:_e,0),function(){for(var Ot=arguments,gn=-1,Vn=We(Ot.length-_e,0),mr=Array(Vn);++gn<Vn;)mr[gn]=Ot[_e+gn];gn=-1;for(var Hn=Array(_e+1);++gn<_e;)Hn[gn]=Ot[gn];return Hn[_e]=qe(mr),Q(be,this,Hn)}}function $n(be,_e){if(!(_e==="constructor"&&typeof be[_e]=="function")&&_e!="__proto__")return be[_e]}var Tf=Ma(Le);function Ma(be){var _e=0,qe=0;return function(){var Ot=Qe(),gn=s-(Ot-qe);if(qe=Ot,gn>0){if(++_e>=o)return arguments[0]}else _e=0;return be.apply(void 0,arguments)}}function Uu(be){if(be!=null){try{return ce.call(be)}catch{}try{return be+""}catch{}}return""}function yl(be,_e){return be===_e||be!==be&&_e!==_e}var yc=Se(function(){return arguments}())?Se:function(be){return wn(be)&&ie.call(be,"callee")&&!ze.call(be,"callee")},vc=Array.isArray;function vl(be){return be!=null&&Xe(be.length)&&!Wu(be)}function So(be){return wn(be)&&vl(be)}var us=Ke||Ku;function Wu(be){if(!Ht(be))return!1;var _e=ge(be);return _e==m||_e==g||_e==u||_e==C}function Xe(be){return typeof be=="number"&&be>-1&&be%1==0&&be<=i}function Ht(be){var _e=typeof be;return be!=null&&(_e=="object"||_e=="function")}function wn(be){return be!=null&&typeof be=="object"}function nn(be){if(!wn(be)||ge(be)!=w)return!1;var _e=Ee(be);if(_e===null)return!0;var qe=ie.call(_e,"constructor")&&_e.constructor;return typeof qe=="function"&&qe instanceof qe&&ce.call(qe)==ae}var Gt=K?oe(K):Ye;function or(be){return Xn(be,An(be))}function An(be){return vl(be)?De(be):bt(be)}var Dr=Go(function(be,_e,qe){St(be,_e,qe)});function Nr(be){return function(){return be}}function co(be){return be}function Ku(){return!1}e.exports=Dr})(sN,sN.exports);var lye=sN.exports;const Jl=dt.getDefaultExportFromCjs(lye),cye={theme:"system",setTheme:()=>null},sY=v.createContext(cye);function iN(e,t="system"){return uye(e)?e:t}function uye(e){return e==="light"||e==="dark"||e==="system"}const oO=()=>{const e=v.useContext(sY);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e},iY=(e,t)=>{const n={};if(e===null||t===null)return t;const r=new Set([...Object.keys(e),...Object.keys(t)]);for(const o of r){if(!(o in e)&&o in t){n[o]=t[o];continue}if(o in e&&!(o in t)){n[o]=void 0;continue}const s=e[o],i=t[o];if(!H2(s,i))if(Array.isArray(s)&&Array.isArray(i))n[o]=i;else if(lB(s)&&lB(i)){const a=iY(s,i);Object.keys(a).length>0&&(n[o]=a)}else n[o]=i}return n},H2=(e,t)=>{if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((o,s)=>H2(o,t[s]));const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(o=>H2(e[o],t[o]))}return!1},lB=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ks=e=>{if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(e);if(e instanceof RegExp)return new RegExp(e);if(Array.isArray(e))return e.map(n=>Ks(n));const t={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=Ks(e[n]));return t},aY="__semaphorAuthoredFontFamily";var VG,HG;const dye=(HG=(VG=dt.DEFAULT_STYLE.default.chart)==null?void 0:VG.font)==null?void 0:HG.family,fye=new Set([dye,"Open Sans, Arial, sans-serif",'"Open Sans", Arial, sans-serif'].filter(Boolean));function hye(e,t){if(!e)return t?{family:t}:void 0;const{[aY]:n,...r}=e,o=mye(r.family,t,!!n);return{...r,...o?{family:o}:void 0}}function mye(e,t,n=!1){return n&&e||e&&!pye(e)?e:t||e}function pye(e){return fye.has(e.trim())}function gye(e,t){if(!t)return e;const n={...e,font:sa(e.font,t)},r=yye(e.plugins,t);r&&(n.plugins=r);const o=vye(e.scales,t);return o&&(n.scales=o),n}function bye(e,t){return!e||!t?e:e.map(n=>{if(!n||typeof n!="object")return n;const r=n,o=r.datalabels;return!o||typeof o!="object"?n:{...r,datalabels:{...o,font:sa(o.font,t)}}})}function xye(e,t){if(!e||typeof e!="object"||!t)return e;const n=e.datasets;return Array.isArray(n)?{...e,datasets:bye(n,t)}:e}function yye(e,t){var n;return e&&{...e,title:e.title?{...e.title,font:sa(e.title.font,t)}:e.title,subtitle:e.subtitle?{...e.subtitle,font:sa(e.subtitle.font,t)}:e.subtitle,legend:e.legend?{...e.legend,labels:e.legend.labels?{...e.legend.labels,font:sa(e.legend.labels.font,t)}:e.legend.labels}:e.legend,tooltip:e.tooltip?{...e.tooltip,titleFont:sa(e.tooltip.titleFont,t),bodyFont:sa(e.tooltip.bodyFont,t),footerFont:sa(e.tooltip.footerFont,t)}:e.tooltip,datalabels:e.datalabels?{...e.datalabels,font:sa((n=e.datalabels)==null?void 0:n.font,t)}:e.datalabels}}function vye(e,t){return e&&Object.entries(e).reduce((n,[r,o])=>{if(!o||typeof o!="object")return n[r]=o,n;const s=o;return n[r]={...s,ticks:s.ticks?{...s.ticks,font:sa(s.ticks.font,t)}:s.ticks,title:s.title?{...s.title,font:sa(s.title.font,t)}:s.title,pointLabels:s.pointLabels?{...s.pointLabels,font:sa(s.pointLabels.font,t)}:s.pointLabels},n},{})}function sa(e,t){return typeof e=="function"?e:{...t,...e&&typeof e=="object"?e:{}}}function wye(e,t){const n=Ks(e??{}),r=Cye(t);if(!r)return n;const o=Jl(n,r);return jye(o,r),o}function Cye(e){var h,m,g,b;const t=(h=e.scheme.components)==null?void 0:h.chart,n=cf.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes[e.mode],r=(m=n.components)==null?void 0:m.chart,o=(g=n.tokens)==null?void 0:g.typography,s={};Nye(t==null?void 0:t.palette,r==null?void 0:r.palette)&&(s.dataset={backgroundColor:[...t.palette],borderColor:[...t.palette]});const i=(b=e.scheme.tokens)==null?void 0:b.typography,a=ap(i==null?void 0:i.fontFamily,o==null?void 0:o.fontFamily),c=ap(i==null?void 0:i.baseFontSize,o==null?void 0:o.baseFontSize);if(a||c!==void 0){const x={...a?{family:a}:void 0,...c!==void 0?{size:c}:void 0};a&&(x[aY]=!0),s.font=x}const u=ap(t==null?void 0:t.gridColor,r==null?void 0:r.gridColor),d=ap(t==null?void 0:t.axisColor,r==null?void 0:r.axisColor)??ap(t==null?void 0:t.foreground,r==null?void 0:r.foreground);(u||d)&&(s.options={scales:{x:BT({gridColor:u,axisColor:d}),y:BT({gridColor:u,axisColor:d}),y2:BT({gridColor:u,axisColor:d}),r:Sye({gridColor:u,axisColor:d})}});const f=ap(t==null?void 0:t.foreground,r==null?void 0:r.foreground);return f&&(s.options=Jl(s.options??{},{plugins:{legend:{labels:{color:f}}}})),Object.keys(s).length>0?{chart:s}:void 0}function BT({gridColor:e,axisColor:t}){return{...e?{grid:{color:e}}:void 0,...t?{ticks:{color:t},title:{color:t}}:void 0}}function Sye({gridColor:e,axisColor:t}){return{...e?{grid:{color:e},angleLines:{color:e}}:void 0,...t?{ticks:{color:t},title:{color:t},pointLabels:{color:t}}:void 0}}function Nye(e,t){return e!=null&&e.length?!(t!=null&&t.length)||e.length!==t.length?!0:e.some((n,r)=>n!==t[r]):!1}function ap(e,t){return e!==void 0&&e!==t?e:void 0}function jye(e,t){var r;const n=(r=t.chart)==null?void 0:r.dataset;n&&(e.chart=e.chart??{},e.chart.dataset=e.chart.dataset??{},Array.isArray(n.backgroundColor)&&(e.chart.dataset.backgroundColor=[...n.backgroundColor]),Array.isArray(n.borderColor)&&(e.chart.dataset.borderColor=[...n.borderColor]))}var Em=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},kye={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Rl,wh,qG,_ye=(qG=class{constructor(){At(this,Rl,kye);At(this,wh,!1)}setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&ve(this,wh)&&e!==ve(this,Rl)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:ve(this,Rl),provider:e}),yt(this,Rl,e),process.env.NODE_ENV!=="production"&&yt(this,wh,!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&yt(this,wh,!0),ve(this,Rl).setTimeout(e,t)}clearTimeout(e){ve(this,Rl).clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&yt(this,wh,!0),ve(this,Rl).setInterval(e,t)}clearInterval(e){ve(this,Rl).clearInterval(e)}},Rl=new WeakMap,wh=new WeakMap,qG),lh=new _ye;function Iye(e){setTimeout(e,0)}var Zh=typeof window>"u"||"Deno"in globalThis;function gs(){}function Tye(e,t){return typeof e=="function"?e(t):e}function q2(e){return typeof e=="number"&&e>=0&&e!==1/0}function lY(e,t){return Math.max(e+(t||0)-Date.now(),0)}function _d(e,t){return typeof e=="function"?e(t):e}function ia(e,t){return typeof e=="function"?e(t):e}function cB(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:i,stale:a}=e;if(i){if(r){if(t.queryHash!==sO(i,t.options))return!1}else if(!f0(t.queryKey,i))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||o&&o!==t.state.fetchStatus||s&&!s(t))}function uB(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(Xh(t.options.mutationKey)!==Xh(s))return!1}else if(!f0(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function sO(e,t){return((t==null?void 0:t.queryKeyHashFn)||Xh)(e)}function Xh(e){return JSON.stringify(e,(t,n)=>U2(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function f0(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>f0(e[n],t[n])):!1}var Eye=Object.prototype.hasOwnProperty;function aN(e,t){if(e===t)return e;const n=dB(e)&&dB(t);if(!n&&!(U2(e)&&U2(t)))return t;const o=(n?e:Object.keys(e)).length,s=n?t:Object.keys(t),i=s.length,a=n?new Array(i):{};let c=0;for(let u=0;u<i;u++){const d=n?u:s[u],f=e[d],h=t[d];if(f===h){a[d]=f,(n?u<o:Eye.call(e,d))&&c++;continue}if(f===null||h===null||typeof f!="object"||typeof h!="object"){a[d]=h;continue}const m=aN(f,h);a[d]=m,m===f&&c++}return o===i&&c===o?e:a}function h0(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function dB(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function U2(e){if(!fB(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!fB(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function fB(e){return Object.prototype.toString.call(e)==="[object Object]"}function Dye(e){return new Promise(t=>{lh.setTimeout(t,e)})}function W2(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return aN(e,t)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${r}`),r}return aN(e,t)}return t}function Mye(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Rye(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var lN=Symbol();function cY(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===lN&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===lN?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function uY(e,t){return typeof e=="function"?e(...t):!!e}var Ch,id,hg,UG,Aye=(UG=class extends Em{constructor(){super();At(this,Ch);At(this,id);At(this,hg);yt(this,hg,t=>{if(!Zh&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ve(this,id)||this.setEventListener(ve(this,hg))}onUnsubscribe(){var t;this.hasListeners()||((t=ve(this,id))==null||t.call(this),yt(this,id,void 0))}setEventListener(t){var n;yt(this,hg,t),(n=ve(this,id))==null||n.call(this),yt(this,id,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){ve(this,Ch)!==t&&(yt(this,Ch,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof ve(this,Ch)=="boolean"?ve(this,Ch):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Ch=new WeakMap,id=new WeakMap,hg=new WeakMap,UG),iO=new Aye;function K2(){let e,t;const n=new Promise((o,s)=>{e=o,t=s});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}var Pye=Iye;function Fye(){let e=[],t=0,n=a=>{a()},r=a=>{a()},o=Pye;const s=a=>{t?e.push(a):o(()=>{n(a)})},i=()=>{const a=e;e=[],a.length&&o(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||i()}return c},batchCalls:a=>(...c)=>{s(()=>{a(...c)})},schedule:s,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{o=a}}}var Ur=Fye(),mg,ad,pg,WG,Oye=(WG=class extends Em{constructor(){super();At(this,mg,!0);At(this,ad);At(this,pg);yt(this,pg,t=>{if(!Zh&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){ve(this,ad)||this.setEventListener(ve(this,pg))}onUnsubscribe(){var t;this.hasListeners()||((t=ve(this,ad))==null||t.call(this),yt(this,ad,void 0))}setEventListener(t){var n;yt(this,pg,t),(n=ve(this,ad))==null||n.call(this),yt(this,ad,t(this.setOnline.bind(this)))}setOnline(t){ve(this,mg)!==t&&(yt(this,mg,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return ve(this,mg)}},mg=new WeakMap,ad=new WeakMap,pg=new WeakMap,WG),cN=new Oye;function Lye(e){return Math.min(1e3*2**e,3e4)}function dY(e){return(e??"online")==="online"?cN.isOnline():!0}var G2=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function fY(e){let t=!1,n=0,r;const o=K2(),s=()=>o.status!=="pending",i=b=>{var x;if(!s()){const y=new G2(b);h(y),(x=e.onCancel)==null||x.call(e,y)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>iO.isFocused()&&(e.networkMode==="always"||cN.isOnline())&&e.canRun(),d=()=>dY(e.networkMode)&&e.canRun(),f=b=>{s()||(r==null||r(),o.resolve(b))},h=b=>{s()||(r==null||r(),o.reject(b))},m=()=>new Promise(b=>{var x;r=y=>{(s()||u())&&b(y)},(x=e.onPause)==null||x.call(e)}).then(()=>{var b;r=void 0,s()||(b=e.onContinue)==null||b.call(e)}),g=()=>{if(s())return;let b;const x=n===0?e.initialPromise:void 0;try{b=x??e.fn()}catch(y){b=Promise.reject(y)}Promise.resolve(b).then(f).catch(y=>{var j;if(s())return;const w=e.retry??(Zh?0:3),C=e.retryDelay??Lye,N=typeof C=="function"?C(n,y):C,S=w===!0||typeof w=="number"&&n<w||typeof w=="function"&&w(n,y);if(t||!S){h(y);return}n++,(j=e.onFail)==null||j.call(e,n,y),Dye(N).then(()=>u()?void 0:m()).then(()=>{t?h(y):g()})})};return{promise:o,status:()=>o.status,cancel:i,continue:()=>(r==null||r(),o),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?g():m().then(g),o)}}var Sh,KG,hY=(KG=class{constructor(){At(this,Sh)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),q2(this.gcTime)&&yt(this,Sh,lh.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Zh?1/0:5*60*1e3))}clearGcTimeout(){ve(this,Sh)&&(lh.clearTimeout(ve(this,Sh)),yt(this,Sh,void 0))}},Sh=new WeakMap,KG),Nh,gg,ra,jh,Ao,kv,kh,Oa,kc,GG,$ye=(GG=class extends hY{constructor(t){super();At(this,Oa);At(this,Nh);At(this,gg);At(this,ra);At(this,jh);At(this,Ao);At(this,kv);At(this,kh);yt(this,kh,!1),yt(this,kv,t.defaultOptions),this.setOptions(t.options),this.observers=[],yt(this,jh,t.client),yt(this,ra,ve(this,jh).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,yt(this,Nh,mB(this.options)),this.state=t.state??ve(this,Nh),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=ve(this,Ao))==null?void 0:t.promise}setOptions(t){if(this.options={...ve(this,kv),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=mB(this.options);n.data!==void 0&&(this.setState(hB(n.data,n.dataUpdatedAt)),yt(this,Nh,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ve(this,ra).remove(this)}setData(t,n){const r=W2(this.state.data,t,this.options);return Qt(this,Oa,kc).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Qt(this,Oa,kc).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,o;const n=(r=ve(this,Ao))==null?void 0:r.promise;return(o=ve(this,Ao))==null||o.cancel(t),n?n.then(gs).catch(gs):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(ve(this,Nh))}isActive(){return this.observers.some(t=>ia(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===lN||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>_d(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!lY(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=ve(this,Ao))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=ve(this,Ao))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),ve(this,ra).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(ve(this,Ao)&&(ve(this,kh)?ve(this,Ao).cancel({revert:!0}):ve(this,Ao).cancelRetry()),this.scheduleGc()),ve(this,ra).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Qt(this,Oa,kc).call(this,{type:"invalidate"})}async fetch(t,n){var c,u,d,f,h,m,g,b,x,y,w,C;if(this.state.fetchStatus!=="idle"&&((c=ve(this,Ao))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(ve(this,Ao))return ve(this,Ao).continueRetry(),ve(this,Ao).promise}if(t&&this.setOptions(t),!this.options.queryFn){const N=this.observers.find(S=>S.options.queryFn);N&&this.setOptions(N.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const r=new AbortController,o=N=>{Object.defineProperty(N,"signal",{enumerable:!0,get:()=>(yt(this,kh,!0),r.signal)})},s=()=>{const N=cY(this.options,n),j=(()=>{const _={client:ve(this,jh),queryKey:this.queryKey,meta:this.meta};return o(_),_})();return yt(this,kh,!1),this.options.persister?this.options.persister(N,j,this):N(j)},a=(()=>{const N={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:ve(this,jh),state:this.state,fetchFn:s};return o(N),N})();(u=this.options.behavior)==null||u.onFetch(a,this),yt(this,gg,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=a.fetchOptions)==null?void 0:d.meta))&&Qt(this,Oa,kc).call(this,{type:"fetch",meta:(f=a.fetchOptions)==null?void 0:f.meta}),yt(this,Ao,fY({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,onCancel:N=>{N instanceof G2&&N.revert&&this.setState({...ve(this,gg),fetchStatus:"idle"}),r.abort()},onFail:(N,S)=>{Qt(this,Oa,kc).call(this,{type:"failed",failureCount:N,error:S})},onPause:()=>{Qt(this,Oa,kc).call(this,{type:"pause"})},onContinue:()=>{Qt(this,Oa,kc).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{const N=await ve(this,Ao).start();if(N===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(N),(m=(h=ve(this,ra).config).onSuccess)==null||m.call(h,N,this),(b=(g=ve(this,ra).config).onSettled)==null||b.call(g,N,this.state.error,this),N}catch(N){if(N instanceof G2){if(N.silent)return ve(this,Ao).promise;if(N.revert){if(this.state.data===void 0)throw N;return this.state.data}}throw Qt(this,Oa,kc).call(this,{type:"error",error:N}),(y=(x=ve(this,ra).config).onError)==null||y.call(x,N,this),(C=(w=ve(this,ra).config).onSettled)==null||C.call(w,this.state.data,N,this),N}finally{this.scheduleGc()}}},Nh=new WeakMap,gg=new WeakMap,ra=new WeakMap,jh=new WeakMap,Ao=new WeakMap,kv=new WeakMap,kh=new WeakMap,Oa=new WeakSet,kc=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...mY(r.data,this.options),fetchMeta:t.meta??null};case"success":const o={...r,...hB(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return yt(this,gg,t.manual?o:void 0),o;case"error":const s=t.error;return{...r,error:s,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),Ur.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),ve(this,ra).notify({query:this,type:"updated",action:t})})},GG);function mY(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:dY(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function hB(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function mB(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var di,Pn,_v,Hs,_h,bg,Pc,ld,Iv,xg,yg,Ih,Th,cd,vg,rr,Qx,Y2,Z2,X2,Q2,J2,eR,tR,pY,YG,aO=(YG=class extends Em{constructor(t,n){super();At(this,rr);At(this,di);At(this,Pn);At(this,_v);At(this,Hs);At(this,_h);At(this,bg);At(this,Pc);At(this,ld);At(this,Iv);At(this,xg);At(this,yg);At(this,Ih);At(this,Th);At(this,cd);At(this,vg,new Set);this.options=n,yt(this,di,t),yt(this,ld,null),yt(this,Pc,K2()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(ve(this,Pn).addObserver(this),pB(ve(this,Pn),this.options)?Qt(this,rr,Qx).call(this):this.updateResult(),Qt(this,rr,Q2).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return nR(ve(this,Pn),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return nR(ve(this,Pn),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Qt(this,rr,J2).call(this),Qt(this,rr,eR).call(this),ve(this,Pn).removeObserver(this)}setOptions(t){const n=this.options,r=ve(this,Pn);if(this.options=ve(this,di).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ia(this.options.enabled,ve(this,Pn))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Qt(this,rr,tR).call(this),ve(this,Pn).setOptions(this.options),n._defaulted&&!h0(this.options,n)&&ve(this,di).getQueryCache().notify({type:"observerOptionsUpdated",query:ve(this,Pn),observer:this});const o=this.hasListeners();o&&gB(ve(this,Pn),r,this.options,n)&&Qt(this,rr,Qx).call(this),this.updateResult(),o&&(ve(this,Pn)!==r||ia(this.options.enabled,ve(this,Pn))!==ia(n.enabled,ve(this,Pn))||_d(this.options.staleTime,ve(this,Pn))!==_d(n.staleTime,ve(this,Pn)))&&Qt(this,rr,Y2).call(this);const s=Qt(this,rr,Z2).call(this);o&&(ve(this,Pn)!==r||ia(this.options.enabled,ve(this,Pn))!==ia(n.enabled,ve(this,Pn))||s!==ve(this,cd))&&Qt(this,rr,X2).call(this,s)}getOptimisticResult(t){const n=ve(this,di).getQueryCache().build(ve(this,di),t),r=this.createResult(n,t);return Bye(this,r)&&(yt(this,Hs,r),yt(this,bg,this.options),yt(this,_h,ve(this,Pn).state)),r}getCurrentResult(){return ve(this,Hs)}trackResult(t,n){return new Proxy(t,{get:(r,o)=>(this.trackProp(o),n==null||n(o),o==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&ve(this,Pc).status==="pending"&&ve(this,Pc).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,o))})}trackProp(t){ve(this,vg).add(t)}getCurrentQuery(){return ve(this,Pn)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=ve(this,di).defaultQueryOptions(t),r=ve(this,di).getQueryCache().build(ve(this,di),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Qt(this,rr,Qx).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),ve(this,Hs)))}createResult(t,n){var T;const r=ve(this,Pn),o=this.options,s=ve(this,Hs),i=ve(this,_h),a=ve(this,bg),u=t!==r?t.state:ve(this,_v),{state:d}=t;let f={...d},h=!1,m;if(n._optimisticResults){const I=this.hasListeners(),E=!I&&pB(t,n),D=I&&gB(t,r,n,o);(E||D)&&(f={...f,...mY(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:g,errorUpdatedAt:b,status:x}=f;m=f.data;let y=!1;if(n.placeholderData!==void 0&&m===void 0&&x==="pending"){let I;s!=null&&s.isPlaceholderData&&n.placeholderData===(a==null?void 0:a.placeholderData)?(I=s.data,y=!0):I=typeof n.placeholderData=="function"?n.placeholderData((T=ve(this,yg))==null?void 0:T.state.data,ve(this,yg)):n.placeholderData,I!==void 0&&(x="success",m=W2(s==null?void 0:s.data,I,n),h=!0)}if(n.select&&m!==void 0&&!y)if(s&&m===(i==null?void 0:i.data)&&n.select===ve(this,Iv))m=ve(this,xg);else try{yt(this,Iv,n.select),m=n.select(m),m=W2(s==null?void 0:s.data,m,n),yt(this,xg,m),yt(this,ld,null)}catch(I){yt(this,ld,I)}ve(this,ld)&&(g=ve(this,ld),m=ve(this,xg),b=Date.now(),x="error");const w=f.fetchStatus==="fetching",C=x==="pending",N=x==="error",S=C&&w,j=m!==void 0,k={status:x,fetchStatus:f.fetchStatus,isPending:C,isSuccess:x==="success",isError:N,isInitialLoading:S,isLoading:S,data:m,dataUpdatedAt:f.dataUpdatedAt,error:g,errorUpdatedAt:b,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:f.dataUpdateCount>0||f.errorUpdateCount>0,isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:w,isRefetching:w&&!C,isLoadingError:N&&!j,isPaused:f.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:N&&j,isStale:lO(t,n),refetch:this.refetch,promise:ve(this,Pc),isEnabled:ia(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const I=R=>{k.status==="error"?R.reject(k.error):k.data!==void 0&&R.resolve(k.data)},E=()=>{const R=yt(this,Pc,k.promise=K2());I(R)},D=ve(this,Pc);switch(D.status){case"pending":t.queryHash===r.queryHash&&I(D);break;case"fulfilled":(k.status==="error"||k.data!==D.value)&&E();break;case"rejected":(k.status!=="error"||k.error!==D.reason)&&E();break}}return k}updateResult(){const t=ve(this,Hs),n=this.createResult(ve(this,Pn),this.options);if(yt(this,_h,ve(this,Pn).state),yt(this,bg,this.options),ve(this,_h).data!==void 0&&yt(this,yg,ve(this,Pn)),h0(n,t))return;yt(this,Hs,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:o}=this.options,s=typeof o=="function"?o():o;if(s==="all"||!s&&!ve(this,vg).size)return!0;const i=new Set(s??ve(this,vg));return this.options.throwOnError&&i.add("error"),Object.keys(ve(this,Hs)).some(a=>{const c=a;return ve(this,Hs)[c]!==t[c]&&i.has(c)})};Qt(this,rr,pY).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Qt(this,rr,Q2).call(this)}},di=new WeakMap,Pn=new WeakMap,_v=new WeakMap,Hs=new WeakMap,_h=new WeakMap,bg=new WeakMap,Pc=new WeakMap,ld=new WeakMap,Iv=new WeakMap,xg=new WeakMap,yg=new WeakMap,Ih=new WeakMap,Th=new WeakMap,cd=new WeakMap,vg=new WeakMap,rr=new WeakSet,Qx=function(t){Qt(this,rr,tR).call(this);let n=ve(this,Pn).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(gs)),n},Y2=function(){Qt(this,rr,J2).call(this);const t=_d(this.options.staleTime,ve(this,Pn));if(Zh||ve(this,Hs).isStale||!q2(t))return;const r=lY(ve(this,Hs).dataUpdatedAt,t)+1;yt(this,Ih,lh.setTimeout(()=>{ve(this,Hs).isStale||this.updateResult()},r))},Z2=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(ve(this,Pn)):this.options.refetchInterval)??!1},X2=function(t){Qt(this,rr,eR).call(this),yt(this,cd,t),!(Zh||ia(this.options.enabled,ve(this,Pn))===!1||!q2(ve(this,cd))||ve(this,cd)===0)&&yt(this,Th,lh.setInterval(()=>{(this.options.refetchIntervalInBackground||iO.isFocused())&&Qt(this,rr,Qx).call(this)},ve(this,cd)))},Q2=function(){Qt(this,rr,Y2).call(this),Qt(this,rr,X2).call(this,Qt(this,rr,Z2).call(this))},J2=function(){ve(this,Ih)&&(lh.clearTimeout(ve(this,Ih)),yt(this,Ih,void 0))},eR=function(){ve(this,Th)&&(lh.clearInterval(ve(this,Th)),yt(this,Th,void 0))},tR=function(){const t=ve(this,di).getQueryCache().build(ve(this,di),this.options);if(t===ve(this,Pn))return;const n=ve(this,Pn);yt(this,Pn,t),yt(this,_v,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},pY=function(t){Ur.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(ve(this,Hs))}),ve(this,di).getQueryCache().notify({query:ve(this,Pn),type:"observerResultsUpdated"})})},YG);function zye(e,t){return ia(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function pB(e,t){return zye(e,t)||e.state.data!==void 0&&nR(e,t,t.refetchOnMount)}function nR(e,t,n){if(ia(t.enabled,e)!==!1&&_d(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&lO(e,t)}return!1}function gB(e,t,n,r){return(e!==t||ia(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&lO(e,n)}function lO(e,t){return ia(t.enabled,e)!==!1&&e.isStaleByTime(_d(t.staleTime,e))}function Bye(e,t){return!h0(e.getCurrentResult(),t)}function bB(e){return{onFetch:(t,n)=>{var d,f,h,m,g;const r=t.options,o=(h=(f=(d=t.fetchOptions)==null?void 0:d.meta)==null?void 0:f.fetchMore)==null?void 0:h.direction,s=((m=t.state.data)==null?void 0:m.pages)||[],i=((g=t.state.data)==null?void 0:g.pageParams)||[];let a={pages:[],pageParams:[]},c=0;const u=async()=>{let b=!1;const x=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?b=!0:t.signal.addEventListener("abort",()=>{b=!0}),t.signal)})},y=cY(t.options,t.fetchOptions),w=async(C,N,S)=>{if(b)return Promise.reject();if(N==null&&C.pages.length)return Promise.resolve(C);const _=(()=>{const E={client:t.client,queryKey:t.queryKey,pageParam:N,direction:S?"backward":"forward",meta:t.options.meta};return x(E),E})(),k=await y(_),{maxPages:T}=t.options,I=S?Rye:Mye;return{pages:I(C.pages,k,T),pageParams:I(C.pageParams,N,T)}};if(o&&s.length){const C=o==="backward",N=C?Vye:xB,S={pages:s,pageParams:i},j=N(r,S);a=await w(S,j,C)}else{const C=e??s.length;do{const N=c===0?i[0]??r.initialPageParam:xB(r,a);if(c>0&&N==null)break;a=await w(a,N),c++}while(c<C)}return a};t.options.persister?t.fetchFn=()=>{var b,x;return(x=(b=t.options).persister)==null?void 0:x.call(b,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function xB(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Vye(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var Tv,Al,qs,Eh,Pl,Ju,ZG,Hye=(ZG=class extends hY{constructor(t){super();At(this,Pl);At(this,Tv);At(this,Al);At(this,qs);At(this,Eh);yt(this,Tv,t.client),this.mutationId=t.mutationId,yt(this,qs,t.mutationCache),yt(this,Al,[]),this.state=t.state||gY(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){ve(this,Al).includes(t)||(ve(this,Al).push(t),this.clearGcTimeout(),ve(this,qs).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){yt(this,Al,ve(this,Al).filter(n=>n!==t)),this.scheduleGc(),ve(this,qs).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){ve(this,Al).length||(this.state.status==="pending"?this.scheduleGc():ve(this,qs).remove(this))}continue(){var t;return((t=ve(this,Eh))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,a,c,u,d,f,h,m,g,b,x,y,w,C,N,S,j,_,k,T;const n=()=>{Qt(this,Pl,Ju).call(this,{type:"continue"})},r={client:ve(this,Tv),meta:this.options.meta,mutationKey:this.options.mutationKey};yt(this,Eh,fY({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(I,E)=>{Qt(this,Pl,Ju).call(this,{type:"failed",failureCount:I,error:E})},onPause:()=>{Qt(this,Pl,Ju).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ve(this,qs).canRun(this)}));const o=this.state.status==="pending",s=!ve(this,Eh).canStart();try{if(o)n();else{Qt(this,Pl,Ju).call(this,{type:"pending",variables:t,isPaused:s}),await((a=(i=ve(this,qs).config).onMutate)==null?void 0:a.call(i,t,this,r));const E=await((u=(c=this.options).onMutate)==null?void 0:u.call(c,t,r));E!==this.state.context&&Qt(this,Pl,Ju).call(this,{type:"pending",context:E,variables:t,isPaused:s})}const I=await ve(this,Eh).start();return await((f=(d=ve(this,qs).config).onSuccess)==null?void 0:f.call(d,I,t,this.state.context,this,r)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,I,t,this.state.context,r)),await((b=(g=ve(this,qs).config).onSettled)==null?void 0:b.call(g,I,null,this.state.variables,this.state.context,this,r)),await((y=(x=this.options).onSettled)==null?void 0:y.call(x,I,null,t,this.state.context,r)),Qt(this,Pl,Ju).call(this,{type:"success",data:I}),I}catch(I){try{throw await((C=(w=ve(this,qs).config).onError)==null?void 0:C.call(w,I,t,this.state.context,this,r)),await((S=(N=this.options).onError)==null?void 0:S.call(N,I,t,this.state.context,r)),await((_=(j=ve(this,qs).config).onSettled)==null?void 0:_.call(j,void 0,I,this.state.variables,this.state.context,this,r)),await((T=(k=this.options).onSettled)==null?void 0:T.call(k,void 0,I,t,this.state.context,r)),I}finally{Qt(this,Pl,Ju).call(this,{type:"error",error:I})}}finally{ve(this,qs).runNext(this)}}},Tv=new WeakMap,Al=new WeakMap,qs=new WeakMap,Eh=new WeakMap,Pl=new WeakSet,Ju=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Ur.batch(()=>{ve(this,Al).forEach(r=>{r.onMutationUpdate(t)}),ve(this,qs).notify({mutation:this,type:"updated",action:t})})},ZG);function gY(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Fc,La,Ev,XG,qye=(XG=class extends Em{constructor(t={}){super();At(this,Fc);At(this,La);At(this,Ev);this.config=t,yt(this,Fc,new Set),yt(this,La,new Map),yt(this,Ev,0)}build(t,n,r){const o=new Hye({client:t,mutationCache:this,mutationId:++hC(this,Ev)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){ve(this,Fc).add(t);const n=pC(t);if(typeof n=="string"){const r=ve(this,La).get(n);r?r.push(t):ve(this,La).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(ve(this,Fc).delete(t)){const n=pC(t);if(typeof n=="string"){const r=ve(this,La).get(n);if(r)if(r.length>1){const o=r.indexOf(t);o!==-1&&r.splice(o,1)}else r[0]===t&&ve(this,La).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=pC(t);if(typeof n=="string"){const r=ve(this,La).get(n),o=r==null?void 0:r.find(s=>s.state.status==="pending");return!o||o===t}else return!0}runNext(t){var r;const n=pC(t);if(typeof n=="string"){const o=(r=ve(this,La).get(n))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(o==null?void 0:o.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ur.batch(()=>{ve(this,Fc).forEach(t=>{this.notify({type:"removed",mutation:t})}),ve(this,Fc).clear(),ve(this,La).clear()})}getAll(){return Array.from(ve(this,Fc))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>uB(n,r))}findAll(t={}){return this.getAll().filter(n=>uB(t,n))}notify(t){Ur.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Ur.batch(()=>Promise.all(t.map(n=>n.continue().catch(gs))))}},Fc=new WeakMap,La=new WeakMap,Ev=new WeakMap,XG);function pC(e){var t;return(t=e.options.scope)==null?void 0:t.id}var Oc,ud,fi,Lc,hu,d1,rR,QG,Uye=(QG=class extends Em{constructor(n,r){super();At(this,hu);At(this,Oc);At(this,ud);At(this,fi);At(this,Lc);yt(this,Oc,n),this.setOptions(r),this.bindMethods(),Qt(this,hu,d1).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var o;const r=this.options;this.options=ve(this,Oc).defaultMutationOptions(n),h0(this.options,r)||ve(this,Oc).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ve(this,fi),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&Xh(r.mutationKey)!==Xh(this.options.mutationKey)?this.reset():((o=ve(this,fi))==null?void 0:o.state.status)==="pending"&&ve(this,fi).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=ve(this,fi))==null||n.removeObserver(this)}onMutationUpdate(n){Qt(this,hu,d1).call(this),Qt(this,hu,rR).call(this,n)}getCurrentResult(){return ve(this,ud)}reset(){var n;(n=ve(this,fi))==null||n.removeObserver(this),yt(this,fi,void 0),Qt(this,hu,d1).call(this),Qt(this,hu,rR).call(this)}mutate(n,r){var o;return yt(this,Lc,r),(o=ve(this,fi))==null||o.removeObserver(this),yt(this,fi,ve(this,Oc).getMutationCache().build(ve(this,Oc),this.options)),ve(this,fi).addObserver(this),ve(this,fi).execute(n)}},Oc=new WeakMap,ud=new WeakMap,fi=new WeakMap,Lc=new WeakMap,hu=new WeakSet,d1=function(){var r;const n=((r=ve(this,fi))==null?void 0:r.state)??gY();yt(this,ud,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},rR=function(n){Ur.batch(()=>{var r,o,s,i,a,c,u,d;if(ve(this,Lc)&&this.hasListeners()){const f=ve(this,ud).variables,h=ve(this,ud).context,m={client:ve(this,Oc),meta:this.options.meta,mutationKey:this.options.mutationKey};(n==null?void 0:n.type)==="success"?((o=(r=ve(this,Lc)).onSuccess)==null||o.call(r,n.data,f,h,m),(i=(s=ve(this,Lc)).onSettled)==null||i.call(s,n.data,null,f,h,m)):(n==null?void 0:n.type)==="error"&&((c=(a=ve(this,Lc)).onError)==null||c.call(a,n.error,f,h,m),(d=(u=ve(this,Lc)).onSettled)==null||d.call(u,void 0,n.error,f,h,m))}this.listeners.forEach(f=>{f(ve(this,ud))})})},QG);function yB(e,t){const n=new Set(t);return e.filter(r=>!n.has(r))}function Wye(e,t,n){const r=e.slice(0);return r[t]=n,r}var Dh,Mi,wg,Cg,oa,dd,Dv,Mv,Rv,cs,oR,sR,iR,aR,lR,JG,Kye=(JG=class extends Em{constructor(t,n,r){super();At(this,cs);At(this,Dh);At(this,Mi);At(this,wg);At(this,Cg);At(this,oa);At(this,dd);At(this,Dv);At(this,Mv);At(this,Rv,[]);yt(this,Dh,t),yt(this,Cg,r),yt(this,wg,[]),yt(this,oa,[]),yt(this,Mi,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&ve(this,oa).forEach(t=>{t.subscribe(n=>{Qt(this,cs,aR).call(this,t,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,ve(this,oa).forEach(t=>{t.destroy()})}setQueries(t,n){if(yt(this,wg,t),yt(this,Cg,n),process.env.NODE_ENV!=="production"){const r=t.map(o=>ve(this,Dh).defaultQueryOptions(o).queryHash);new Set(r).size!==r.length&&console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.")}Ur.batch(()=>{const r=ve(this,oa),o=Qt(this,cs,iR).call(this,ve(this,wg));yt(this,Rv,o),o.forEach(f=>f.observer.setOptions(f.defaultedQueryOptions));const s=o.map(f=>f.observer),i=s.map(f=>f.getCurrentResult()),a=r.length!==s.length,c=s.some((f,h)=>f!==r[h]),u=a||c,d=u?!0:i.some((f,h)=>{const m=ve(this,Mi)[h];return!m||!h0(f,m)});!u&&!d||(u&&yt(this,oa,s),yt(this,Mi,i),this.hasListeners()&&(u&&(yB(r,s).forEach(f=>{f.destroy()}),yB(s,r).forEach(f=>{f.subscribe(h=>{Qt(this,cs,aR).call(this,f,h)})})),Qt(this,cs,lR).call(this)))})}getCurrentResult(){return ve(this,Mi)}getQueries(){return ve(this,oa).map(t=>t.getCurrentQuery())}getObservers(){return ve(this,oa)}getOptimisticResult(t,n){const r=Qt(this,cs,iR).call(this,t),o=r.map(s=>s.observer.getOptimisticResult(s.defaultedQueryOptions));return[o,s=>Qt(this,cs,sR).call(this,s??o,n),()=>Qt(this,cs,oR).call(this,o,r)]}},Dh=new WeakMap,Mi=new WeakMap,wg=new WeakMap,Cg=new WeakMap,oa=new WeakMap,dd=new WeakMap,Dv=new WeakMap,Mv=new WeakMap,Rv=new WeakMap,cs=new WeakSet,oR=function(t,n){return n.map((r,o)=>{const s=t[o];return r.defaultedQueryOptions.notifyOnChangeProps?s:r.observer.trackResult(s,i=>{n.forEach(a=>{a.observer.trackProp(i)})})})},sR=function(t,n){return n?((!ve(this,dd)||ve(this,Mi)!==ve(this,Mv)||n!==ve(this,Dv))&&(yt(this,Dv,n),yt(this,Mv,ve(this,Mi)),yt(this,dd,aN(ve(this,dd),n(t)))),ve(this,dd)):t},iR=function(t){const n=new Map;ve(this,oa).forEach(o=>{const s=o.options.queryHash;if(!s)return;const i=n.get(s);i?i.push(o):n.set(s,[o])});const r=[];return t.forEach(o=>{var c;const s=ve(this,Dh).defaultQueryOptions(o),a=((c=n.get(s.queryHash))==null?void 0:c.shift())??new aO(ve(this,Dh),s);r.push({defaultedQueryOptions:s,observer:a})}),r},aR=function(t,n){const r=ve(this,oa).indexOf(t);r!==-1&&(yt(this,Mi,Wye(ve(this,Mi),r,n)),Qt(this,cs,lR).call(this))},lR=function(){var t;if(this.hasListeners()){const n=ve(this,dd),r=Qt(this,cs,oR).call(this,ve(this,Mi),ve(this,Rv)),o=Qt(this,cs,sR).call(this,r,(t=ve(this,Cg))==null?void 0:t.combine);n!==o&&Ur.batch(()=>{this.listeners.forEach(s=>{s(ve(this,Mi))})})}},JG),Fl,eY,bY=(eY=class extends Em{constructor(t={}){super();At(this,Fl);this.config=t,yt(this,Fl,new Map)}build(t,n,r){const o=n.queryKey,s=n.queryHash??sO(o,n);let i=this.get(s);return i||(i=new $ye({client:t,queryKey:o,queryHash:s,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(i)),i}add(t){ve(this,Fl).has(t.queryHash)||(ve(this,Fl).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=ve(this,Fl).get(t.queryHash);n&&(t.destroy(),n===t&&ve(this,Fl).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Ur.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return ve(this,Fl).get(t)}getAll(){return[...ve(this,Fl).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>cB(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>cB(t,r)):n}notify(t){Ur.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Ur.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Ur.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Fl=new WeakMap,eY),Zr,fd,hd,Sg,Ng,md,jg,kg,tY,Gye=(tY=class{constructor(e={}){At(this,Zr);At(this,fd);At(this,hd);At(this,Sg);At(this,Ng);At(this,md);At(this,jg);At(this,kg);yt(this,Zr,e.queryCache||new bY),yt(this,fd,e.mutationCache||new qye),yt(this,hd,e.defaultOptions||{}),yt(this,Sg,new Map),yt(this,Ng,new Map),yt(this,md,0)}mount(){hC(this,md)._++,ve(this,md)===1&&(yt(this,jg,iO.subscribe(async e=>{e&&(await this.resumePausedMutations(),ve(this,Zr).onFocus())})),yt(this,kg,cN.subscribe(async e=>{e&&(await this.resumePausedMutations(),ve(this,Zr).onOnline())})))}unmount(){var e,t;hC(this,md)._--,ve(this,md)===0&&((e=ve(this,jg))==null||e.call(this),yt(this,jg,void 0),(t=ve(this,kg))==null||t.call(this),yt(this,kg,void 0))}isFetching(e){return ve(this,Zr).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return ve(this,fd).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=ve(this,Zr).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=ve(this,Zr).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(_d(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return ve(this,Zr).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),o=ve(this,Zr).get(r.queryHash),s=o==null?void 0:o.state.data,i=Tye(t,s);if(i!==void 0)return ve(this,Zr).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return Ur.batch(()=>ve(this,Zr).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=ve(this,Zr).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=ve(this,Zr);Ur.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=ve(this,Zr);return Ur.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=Ur.batch(()=>ve(this,Zr).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(gs).catch(gs)}invalidateQueries(e,t={}){return Ur.batch(()=>(ve(this,Zr).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Ur.batch(()=>ve(this,Zr).findAll(e).filter(o=>!o.isDisabled()&&!o.isStatic()).map(o=>{let s=o.fetch(void 0,n);return n.throwOnError||(s=s.catch(gs)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(gs)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=ve(this,Zr).build(this,t);return n.isStaleByTime(_d(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(gs).catch(gs)}fetchInfiniteQuery(e){return e.behavior=bB(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(gs).catch(gs)}ensureInfiniteQueryData(e){return e.behavior=bB(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return cN.isOnline()?ve(this,fd).resumePausedMutations():Promise.resolve()}getQueryCache(){return ve(this,Zr)}getMutationCache(){return ve(this,fd)}getDefaultOptions(){return ve(this,hd)}setDefaultOptions(e){yt(this,hd,e)}setQueryDefaults(e,t){ve(this,Sg).set(Xh(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...ve(this,Sg).values()],n={};return t.forEach(r=>{f0(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){ve(this,Ng).set(Xh(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...ve(this,Ng).values()],n={};return t.forEach(r=>{f0(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...ve(this,hd).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=sO(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===lN&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...ve(this,hd).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){ve(this,Zr).clear(),ve(this,fd).clear()}},Zr=new WeakMap,fd=new WeakMap,hd=new WeakMap,Sg=new WeakMap,Ng=new WeakMap,md=new WeakMap,jg=new WeakMap,kg=new WeakMap,tY),cO=te.createContext(void 0),Wr=e=>{const t=te.useContext(cO);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Yye=({client:e,children:t})=>(te.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),l.jsx(cO.Provider,{value:e,children:t})),xY=te.createContext(!1),yY=()=>te.useContext(xY);xY.Provider;function Zye(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xye=te.createContext(Zye()),vY=()=>te.useContext(Xye),wY=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},CY=e=>{te.useEffect(()=>{e.clearReset()},[e])},SY=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||uY(n,[e.error,r])),NY=e=>{if(e.suspense){const n=o=>o==="static"?o:Math.max(o??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...o)=>n(r(...o)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},jY=(e,t)=>e.isLoading&&e.isFetching&&!t,cR=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,uN=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function ib({queries:e,...t},n){const r=Wr(),o=yY(),s=vY(),i=te.useMemo(()=>e.map(b=>{const x=r.defaultQueryOptions(b);return x._optimisticResults=o?"isRestoring":"optimistic",x}),[e,r,o]);i.forEach(b=>{NY(b),wY(b,s)}),CY(s);const[a]=te.useState(()=>new Kye(r,i,t)),[c,u,d]=a.getOptimisticResult(i,t.combine),f=!o&&t.subscribed!==!1;te.useSyncExternalStore(te.useCallback(b=>f?a.subscribe(Ur.batchCalls(b)):gs,[a,f]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),te.useEffect(()=>{a.setQueries(i,t)},[i,t,a]);const m=c.some((b,x)=>cR(i[x],b))?c.flatMap((b,x)=>{const y=i[x];if(y){const w=new aO(r,y);if(cR(y,b))return uN(y,w,s);jY(b,o)&&uN(y,w,s)}return[]}):[];if(m.length>0)throw Promise.all(m);const g=c.find((b,x)=>{const y=i[x];return y&&SY({result:b,errorResetBoundary:s,throwOnError:y.throwOnError,query:r.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(g!=null&&g.error)throw g.error;return u(d())}function Qye(e,t,n){var f,h,m,g,b;if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=yY(),o=vY(),s=Wr(),i=s.defaultQueryOptions(e);(h=(f=s.getDefaultOptions().queries)==null?void 0:f._experimental_beforeQuery)==null||h.call(f,i),process.env.NODE_ENV!=="production"&&(i.queryFn||console.error(`[${i.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),i._optimisticResults=r?"isRestoring":"optimistic",NY(i),wY(i,o),CY(o);const a=!s.getQueryCache().get(i.queryHash),[c]=te.useState(()=>new t(s,i)),u=c.getOptimisticResult(i),d=!r&&e.subscribed!==!1;if(te.useSyncExternalStore(te.useCallback(x=>{const y=d?c.subscribe(Ur.batchCalls(x)):gs;return c.updateResult(),y},[c,d]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),te.useEffect(()=>{c.setOptions(i)},[i,c]),cR(i,u))throw uN(i,c,o);if(SY({result:u,errorResetBoundary:o,throwOnError:i.throwOnError,query:s.getQueryCache().get(i.queryHash),suspense:i.suspense}))throw u.error;if((g=(m=s.getDefaultOptions().queries)==null?void 0:m._experimental_afterQuery)==null||g.call(m,i,u),i.experimental_prefetchInRender&&!Zh&&jY(u,r)){const x=a?uN(i,c,o):(b=s.getQueryCache().get(i.queryHash))==null?void 0:b.promise;x==null||x.catch(gs).finally(()=>{c.updateResult()})}return i.notifyOnChangeProps?u:c.trackResult(u)}function Un(e,t){return Qye(e,aO)}function Jye(e,t){const n=Wr(),r=n.getQueryCache();return te.useSyncExternalStore(te.useCallback(o=>r.subscribe(Ur.batchCalls(o)),[r]),()=>n.isFetching(e),()=>n.isFetching(e))}function ks(e,t){const n=Wr(),[r]=te.useState(()=>new Uye(n,e));te.useEffect(()=>{r.setOptions(e)},[r,e]);const o=te.useSyncExternalStore(te.useCallback(i=>r.subscribe(Ur.batchCalls(i)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),s=te.useCallback((i,a)=>{r.mutate(i,a).catch(gs)},[r]);if(o.error&&uY(r.options.throwOnError,[o.error]))throw o.error;return{...o,mutate:s,mutateAsync:o.mutate}}function e0e(){const e=v.useContext(cO);if(e&&e.isSemaphorClient)return e}function kY({children:e}){const{setIsSessionExpired:t}=p.useDashboardActions(),n=e0e(),[r]=v.useState(()=>{const o=new Gye({queryCache:new bY({onError:s=>{s instanceof Error?(console.error(`Something went wrong: ${s.message}`),s.message==="invalid token"&&t(!0)):console.error("Something went wrong:",s)}}),defaultOptions:{queries:{gcTime:36e5,staleTime:3e5,refetchOnWindowFocus:!1,retry:!1}}});return o.isSemaphorClient=!0,o});return n?l.jsx(l.Fragment,{children:e}):l.jsx(Yye,{client:r,children:e})}const t0e={id:"",authToken:void 0,tokenProps:{}},Av=v.createContext(t0e),uO=({children:e,dashboardProps:t})=>{const n=v.useMemo(()=>{let r={};const o=t.authToken;return o&&(r=je.jwtDecode(o.accessToken)),{...t,tokenProps:r}},[t]);return l.jsx(kY,{children:l.jsx(Av.Provider,{value:n,children:e})})};function It(){const e=v.useContext(Av);if(e===void 0)throw new Error("useApplicationContext must be used within a ApplicationContextProvider");return e}const _s=p.create()(p.immer(e=>({initialDashboard:null,selectedDashboard:null,selectedVisual:null,lastSelectedDashboard:null,lastSelectedVisual:null,showHub:!1,actions:{setInitialDashboard:t=>{e(n=>{n.initialDashboard=t})},selectDashboard:t=>{e(n=>{var r;((r=n.selectedDashboard)==null?void 0:r.id)!==t.id&&(n.lastSelectedDashboard=n.selectedDashboard,n.selectedDashboard=t),n.showHub=!1})},updateSelectedDashboard:t=>{e(n=>{n.selectedDashboard=t})},selectVisual:t=>{e(n=>{n.lastSelectedVisual=n.selectedVisual,n.selectedVisual=t})},clearSelectedDashboard:()=>{e(t=>{t.lastSelectedDashboard=t.selectedDashboard,t.selectedDashboard=null,t.showHub=!0})},clearSelectedVisual:()=>{e(t=>{t.lastSelectedVisual=t.selectedVisual,t.selectedVisual=null})},setShowHub:t=>{e(n=>{n.showHub=t})}}}))),n0e=()=>_s(e=>e.selectedVisual),Dm=()=>_s(e=>e.actions);function Pv(){const{authToken:e,version:t,tokenProps:n,id:r}=It(),o=_s(g=>g.selectedDashboard),s=_s(g=>g.showHub),i=p.useDashboardStore(g=>g.selectedLensId),a=r0e({showHub:s,selectedDashboardId:o==null?void 0:o.id,dashboardId:r,tokenDashboardId:n==null?void 0:n.dashboard_id});function c(){return!(!(e!=null&&e.accessToken)||!a)}const{data:u,isLoading:d,isFetching:f,isError:h,refetch:m}=Un({queryKey:["dashboard",i,e==null?void 0:e.accessToken,a],queryFn:()=>p.getDashboard(n.apiServiceUrl,e==null?void 0:e.accessToken,{lensId:i,version:t,dashboardId:a}),enabled:c()});return{data:u,isLoading:d,isFetching:f,isError:h,refetch:m,dashboardIdToFetch:a}}function r0e({showHub:e,selectedDashboardId:t,dashboardId:n,tokenDashboardId:r}){return e?null:t||n||r||null}function o0e(){const{authToken:e}=It(),t=p.useDashboardStore(r=>r.authToken),{setAuthToken:n}=p.useDashboardActions();return v.useLayoutEffect(()=>{const r=e==null?void 0:e.accessToken,o=t==null?void 0:t.accessToken;e&&r!==o&&n(e)},[e,t,n]),e}function _Y(e){const t=v.useCallback(s=>`semaphor-default-sheet-${s}`,[]),n=v.useCallback(()=>{if(!e)return null;try{const s=t(e);return localStorage.getItem(s)}catch(s){return console.error("Error reading default sheet preference:",s),null}},[e,t]),r=v.useCallback(s=>{if(!(!e||!s))try{const i=t(e);localStorage.setItem(i,s)}catch(i){console.error("Error saving default sheet preference:",i)}},[e,t]),o=v.useCallback(()=>{if(e)try{const s=t(e);localStorage.removeItem(s)}catch(s){console.error("Error clearing default sheet preference:",s)}},[e,t]);return{getDefaultSheetId:n,setDefaultSheetId:r,clearDefaultSheetId:o}}const vB=/\[\[\s*param\.([A-Za-z0-9_.-]+)\s*\]\]/g,wB=/\bparam\s*\(\s*(['"])([^'"]+)\1/g;function s0e(e){const t=[];let n=0;for(;n<e.length;){const r=e.indexOf("{{",n),o=e.indexOf("{%",n);let s=-1,i="";if(r===-1?(s=o,i="%}"):o===-1||r<o?(s=r,i="}}"):(s=o,i="%}"),s===-1)break;const a=e.indexOf(i,s+2);if(a===-1){n=s+2;continue}t.push(e.slice(s+2,a)),n=a+2}return t}function dO(e){var r,o;if(!e)return[];const t=new Set;let n;for(vB.lastIndex=0;(n=vB.exec(e))!==null;){const s=(r=n[1])==null?void 0:r.trim();s&&t.add(s)}for(const s of s0e(e))for(wB.lastIndex=0;(n=wB.exec(s))!==null;){const i=(o=n[2])==null?void 0:o.trim();i&&t.add(i)}return Array.from(t)}function Ek(e){const t=new Set,n=new Map;for(const r of e.controlBindings||[])t.add(r.controlId),r.target==="sql_param"&&n.set(r.paramId,r.controlId);for(const r of dO(e.sql))t.add(n.get(r)??r);return Array.from(t)}function IY(e){const t=new Map,n=new Map;for(const r of e.controlBindings||[])r.target==="sql_param"&&n.set(r.paramId,r.controlId);for(const r of dO(e.sql))t.set(r,{paramId:r,controlId:n.get(r)??r});return Array.from(t.values())}const i0e=["kpi","table","detailTable","aggregateTable","pivotTable","bar","horizontalBar","stackedBar","line","stackedLine","area","stackedArea","combo","pie","doughnut","polarArea","radar","scatter","bubble","tornado","pyramid","range","funnel","bullet","heatmap","treemap","map","matrixTable"],a0e=new Set(i0e),l0e=["table","detailTable","aggregateTable","pivotTable","matrixTable"],c0e=new Set(l0e);function TY(e){return typeof e=="string"&&c0e.has(e)}function Fv(e){return typeof e=="string"&&a0e.has(e)}function dN(e){return(e==null?void 0:e.type)==="number"||(e==null?void 0:e.type)==="currency"}function EY(e){var n,r;const t=(r=(n=e.preferences)==null?void 0:n.formatNumber)==null?void 0:r.enabled;return t===!1||t==="false"}function DY(e){return(e==null?void 0:e.type)==="number"}function u0e(e){var n;if(!DY(e))return!1;const t=(n=e==null?void 0:e.numberFormat)==null?void 0:n.style;return t===void 0||t==="decimal"||t==="currency"}function Dk(e,t){const n=t==null?void 0:t.type;if(n&&n!=="none"&&n!=="number")return{currencyBindable:!1};const r=n==="number"?t!=null&&t.numberFormat?p.fromColumnNumberFormat(t.numberFormat,{preserveOmittedProperties:!0}):{type:"number"}:void 0,o=p.fromSemanticFormat(e.format,{preserveOmittedProperties:!0}),s=va.normalizeAnalyticsCatalogDataType(e.dataType)==="number"?{type:"number"}:void 0,a=(t==null?void 0:t.inheritMetricFormat)===!1||!!(t!=null&&t.numberFormat)&&(t==null?void 0:t.inheritMetricFormat)!==!0?r:o||s||r;return{authoredFormat:a,currencyBindable:dN(a)}}function fO(e,t){var c,u;const n=p.fromSemanticFormat(t.format,{preserveOmittedProperties:!0}),r=p.fromNumberAxisFormat((c=e.preferences)==null?void 0:c.numberAxisFormat),o=EY(e)?void 0:p.fromLegacyFormatNumber((u=e.preferences)==null?void 0:u.formatNumber),s=va.normalizeAnalyticsCatalogDataType(t.dataType)==="number"?{type:"number"}:void 0,i=n||r||o||s;return{authoredFormat:i,source:n?"semantic":r?"number_axis":o?"legacy":s?"inferred":void 0,currencyBindable:dN(i)}}function m0(e,t={}){var h,m,g,b,x,y;const n=t.metricIndex??0,r=!!((h=e.sql)!=null&&h.trim()),o=p.fromPersistedKpiFormatOptions((g=(m=e.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:g.formatOptions),s=n===0?p.fromLegacyFormatNumber((b=e.preferences)==null?void 0:b.formatNumber):void 0,i=EY(e);if(r){const w=t.resultColumnKey?{kind:"column",columnKey:t.resultColumnKey}:void 0;return{target:w,authoredFormat:o||s,currencyBindable:!i&&!!w&&dN(o)}}const a=(y=(x=e.config)==null?void 0:x.metricColumns)==null?void 0:y[n],c=a!=null&&a.id?{kind:"metric",metricId:a.id}:void 0,u=p.fromSemanticFormat(a==null?void 0:a.format,{preserveOmittedProperties:!0}),d=va.normalizeAnalyticsCatalogDataType(a==null?void 0:a.dataType)==="number"?{type:"number"}:void 0,f=o||u||s||d;return{target:c,authoredFormat:f,currencyBindable:!i&&Fv(e.type)&&!!c&&dN(f)}}function hO(){const e=new Set;return(t,n,r)=>{const o=t.id||t.alias||t.name||`field_${n+1}`,s=[o];r.kind==="axis"&&r.grain&&s.push(`${o}-${r.grain}`),r.kind==="value"&&s.push(`${o}-${r.aggregate.toLowerCase()}`),s.push(`${o}-${n+1}`);for(const c of s)if(!e.has(c))return e.add(c),c;let i=n+1,a=`${o}-${i}`;for(;e.has(a);)i+=1,a=`${o}-${i}`;return e.add(a),a}}function MY(e){return e==="COUNT"||e==="SUM"||e==="AVG"||e==="MIN"||e==="MAX"||e==="MEDIAN"||e==="DISTINCT"?e:"SUM"}function CB(e){return`measure:${e}`}function Mk(e){var o,s,i,a,c,u,d;const t=(o=e.config)==null?void 0:o.metricColumns;if(Array.isArray(t)){const f=hO();return t.map((h,m)=>{const g=f(h,m,{kind:"value",aggregate:MY(h.aggregate)});return{measureId:CB(g),format:h.format,metric:h}})}const n=((i=(s=e.config)==null?void 0:s.matrixIntent)==null?void 0:i.values)||((a=e.config)==null?void 0:a.values)||[],r=((u=(c=e.config)==null?void 0:c.matrixIntent)==null?void 0:u.source)||((d=e.config)==null?void 0:d.source);return n.map((f,h)=>{const m=d0e(f.field,f.aggregate,r),g=f.id||`${m}-${h}`;return{measureId:CB(g),format:f.format,value:f}})}function d0e(e,t,n){const r=e.source||n;return[r==null?void 0:r.kind,(r==null?void 0:r.kind)==="semantic"?r.domainId:void 0,(r==null?void 0:r.kind)==="semantic"?r.datasetId:void 0,(r==null?void 0:r.kind)==="semantic"?r.datasetName:void 0,(r==null?void 0:r.kind)==="physical"?r.connectionId:void 0,(r==null?void 0:r.kind)==="physical"?r.databaseName:void 0,(r==null?void 0:r.kind)==="physical"?r.schemaName:void 0,(r==null?void 0:r.kind)==="physical"?r.tableName:void 0,e.name,e.role,t].filter(Boolean).join(":")}function RY(e){const t=new Map;if(!e.result||!e.presentation.preferences)return t;const n=new Map((e.card?Mk(e.card):[]).map(r=>[r.measureId,r]));for(const[r,o]of Object.entries(e.result.measuresById)){const s=n.get(r),i=mO(s?s.format:o.format);i&&t.set(r,$t.resolveNumericPresentation(i,e.presentation.preferences,e.presentation.resolveBoundCurrency({kind:"matrix_measure",measureId:r})))}return t}function AY(e){const{cell:t}=e;if(t.presence==="missing"||t.presence==="densified")return"—";if(t.presence==="presentNull"||t.value===null||t.value===void 0)return"";const n=f0e(t.value),r=e.formatsByMeasureId.get(t.measureId);return n!==void 0&&r?$t.formatNumericCanonical(n,r):n!==void 0?new Intl.NumberFormat("en-US",{maximumFractionDigits:6}).format(n):String(t.value)}function mO(e){if(typeof e=="object"&&(e==null?void 0:e.type)==="datetime")return;const t=p.fromSemanticFormat(e,{preserveOmittedProperties:!0});if(!t)return{type:"number"};if(Kt.isNumericCanonicalFormat(t))return t}function f0e(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||!e.trim())return;const t=Number(e);return Number.isFinite(t)?t:void 0}function pO(e){var t,n;return e.type==="detailTable"?((t=e.config)==null?void 0:t.detailColumns)||[]:((n=e.config)==null?void 0:n.metricColumns)||[]}function PY(e){return new Set(p.getDashboardCards(e).flatMap(t=>(t.controlBindings||[]).filter(Ov).map(n=>n.controlId)))}function h0e(e,t){const n=[t.id,t.alias,t.label,t.name,t.qualifiedFieldName].filter(s=>!!s);for(const s of n)if(e[s])return e[s];const r=new Set(n.map(s=>s.trim().toLowerCase())),o=Object.entries(e).find(([s])=>r.has(s.trim().toLowerCase()));return o==null?void 0:o[1]}function SB(e){return[...new Map(e.map(t=>[ba(t),t])).values()]}function m0e(e){if(e.metric)return Dk(e.metric,void 0).currencyBindable;const t=mO(e.format);return(t==null?void 0:t.type)==="number"||(t==null?void 0:t.type)==="currency"}function gO(e,t=[]){var C,N,S;const n=!!((C=e.sql)!=null&&C.trim()),r=Fv(e.type),o=n&&r&&e.type!=="kpi"&&e.type!=="matrixTable",s=pO(e),i=((S=(N=e.preferences)==null?void 0:N.tablePrefs)==null?void 0:S.columnSettingsMap)||{},a=!n&&e.type==="kpi"?s.map((j,_)=>m0(e,{metricIndex:_})):[],c=!n&&e.type==="matrixTable"?Mk(e):[],u=(n?[]:s).map(j=>({kind:"metric",metricId:j.id})),d=c.map(j=>({kind:"matrix_measure",measureId:j.measureId})),f=c.filter(m0e).map(j=>({kind:"matrix_measure",measureId:j.measureId})),h=e.type==="matrixTable"?[]:e.type==="kpi"?a.filter(j=>j.currencyBindable).flatMap(j=>j.target?[j.target]:[]):(n||!r?[]:s).filter(j=>(TY(e.type)?Dk(j,h0e(i,j)):fO(e,j)).currencyBindable).map(j=>({kind:"metric",metricId:j.id})),m=[...new Set(t)],g=(o?m:[]).map(j=>({kind:"column",columnKey:j})),b=(o?m:[]).filter(j=>u0e(i[j])).map(j=>({kind:"column",columnKey:j})),x=(n&&e.type==="kpi"?m.slice(0,1):[]).map(j=>({kind:"column",columnKey:j})),y=n&&e.type==="kpi"?m0(e,{resultColumnKey:m[0]}):void 0,w=r&&(y!=null&&y.currencyBindable)?x:[];return{knownTargets:SB([...e.type==="matrixTable"?d:u,...g,...x]),eligibleTargets:SB([...h,...f,...b,...w])}}function FY(e,t){const n=m0(e,{resultColumnKey:t});return n.currencyBindable?n.target:void 0}function ec(e){var t;return(t=e.card.sql)!=null&&t.trim()?{kind:"column",columnKey:e.columnKey}:e.metricId?{kind:"metric",metricId:e.metricId}:void 0}function ba(e){return e.kind==="metric"?`metric:${e.metricId}`:e.kind==="column"?`column:${e.columnKey}`:`matrix_measure:${e.measureId}`}function p0e(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(t.kind==="metric"&&typeof t.metricId=="string"&&t.metricId.trim())return{kind:"metric",metricId:t.metricId};if(t.kind==="column"&&typeof t.columnKey=="string"&&t.columnKey.trim())return{kind:"column",columnKey:t.columnKey};if(t.kind==="matrix_measure"&&typeof t.measureId=="string"&&t.measureId.trim())return{kind:"matrix_measure",measureId:t.measureId}}function Ov(e){return e.target==="presentation_currency"}function g0e(e){return e.target!=="sql_param"&&e.target!=="presentation_currency"}function NB(e){const t=Li.canonicalizeSupportedCurrencyCode(e);return typeof e=="string"&&e===t?t:void 0}function OY(e){if(e.type!=="enum"||e.source.kind!=="manual")return{diagnostic:"invalid_control_type"};const t=e.source.options.map(n=>NB(n.value));if(t.length===0||t.some(n=>!n))return{diagnostic:"invalid_currency_option"};if(e.requiredAtExecution){const n=e.initialValueStrategy==="saved_default"?NB(e.defaultValue):void 0;if(!n||!t.includes(n))return{diagnostic:"invalid_control_default"}}return{control:e,currencies:t}}function b0e(e){return"control"in OY(e)}function LY(e){const t=PY(e.dashboard);if(t.size===0)return{definitions:e.definitions||[],values:e.values||{}};const n=new Set([...t].filter(r=>!e.referencedControlIds.has(r)));return{definitions:(e.definitions||[]).filter(r=>!n.has(r.id)),values:Object.fromEntries(Object.entries(e.values||{}).filter(([r])=>!n.has(r)))}}function $Y(e){return LY({...e,referencedControlIds:new Set(Ek({sql:e.filterSql,controlBindings:[]}))})}function x0e(e){var t;return LY({...e,referencedControlIds:new Set(Ek({sql:(t=e.source)==null?void 0:t.sql,controlBindings:[]}))})}function zY(e){return{knownKeys:new Set(e.knownTargets.map(ba)),eligibleKeys:new Set(e.eligibleTargets.map(ba)),controlsById:new Map((e.controls||[]).map(t=>[t.id,t]))}}function BY(e,t){if(!e||typeof e!="object"||e.target!=="presentation_currency")return{};const n=e,r=typeof n.controlId=="string"&&n.controlId.trim()?n.controlId:void 0;if(!r)return{diagnostic:{code:"invalid_binding_shape"}};const o=p0e(n.presentationTarget);if(!o)return{diagnostic:{code:"missing_target",controlId:r}};const s=ba(o);if(!t.knownKeys.has(s))return{diagnostic:{code:"stale_target",controlId:r}};if(!t.eligibleKeys.has(s))return{diagnostic:{code:"inapplicable_target",controlId:r}};const i=t.controlsById.get(r);if(!i)return{diagnostic:{code:"missing_control",controlId:r}};const a=OY(i);return"diagnostic"in a?{diagnostic:{code:a.diagnostic,controlId:r}}:{binding:{controlId:r,presentationTarget:o,control:a.control,currencies:a.currencies}}}function y0e(e){const t=zY(e);return(e.bindings||[]).flatMap(n=>{const r=BY(n,t);return"diagnostic"in r?[r.diagnostic]:[]})}function VY(e){var o;const t=[],n=ba(e.target),r=zY(e);for(const s of e.bindings||[]){const i=BY(s,r);if("diagnostic"in i){t.push(i.diagnostic);continue}const a=i.binding;if(!a||ba(a.presentationTarget)!==n)continue;const u=Li.canonicalizeSupportedCurrencyCode((o=e.values)==null?void 0:o[a.control.id]);if(!(!u||!a.currencies.includes(u)))return{currency:u,diagnostics:t}}return{diagnostics:t}}function v0e(e,t){if(!e||typeof e!="object"||!("kind"in e))return e;switch(e.kind){case"manual":return{kind:"manual",...t!=null&&t.includePresentation?{options:e.options.map(n=>({value:n.value,label:n.label,presentation:n.presentation}))}:{optionValues:e.options.map(n=>n.value).sort()}};case"dataset_values":return{kind:"dataset_values",fieldId:e.fieldId,connectionId:e.connectionId||""};case"field_allowlist":return{kind:"field_allowlist",fieldIds:[...e.fieldIds].sort()};case"metric_allowlist":return{kind:"metric_allowlist",metricIds:[...e.metricIds].sort()};case"sql_query":return{kind:"sql_query",connectionId:e.connectionId,sql:e.sql,valueColumn:e.valueColumn,labelColumn:e.labelColumn};default:return e}}function w0e(e,t){return{id:e.id,scope:e.scope,type:e.type,source:v0e(e.source,t),initialValueStrategy:e.initialValueStrategy,defaultValue:e.defaultValue,requiredAtExecution:e.requiredAtExecution,...t!=null&&t.includePresentation?{label:e.label,helpText:e.helpText,hidden:e.hidden,locked:e.locked,placement:e.placement,showLabel:e.showLabel,toolbarWidth:e.toolbarWidth}:{}}}function C0e(e,t){return e.target==="sql_param"||e.target==="presentation_currency"?e:e.target==="config_field_selector"&&!(t!=null&&t.includePresentation)?{...e,mapping:Object.fromEntries(Object.entries(e.mapping).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>{const o={...r};return delete o.format,delete o.dateFormat,delete o.customFormat,delete o.semanticTemporalPresentation,[n,o]}))}:{...e,mapping:Object.fromEntries(Object.entries(e.mapping).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).sort(([o],[s])=>o.localeCompare(s))):r]))}}function jB(e=[],t){return[...e].map(n=>w0e(n,t)).sort((n,r)=>n.id.localeCompare(r.id)||n.scope.localeCompare(r.scope)||n.type.localeCompare(r.type))}function S0e(e=[],t){return e.filter(n=>(t==null?void 0:t.includePresentation)||!Ov(n)).map(n=>C0e(n,t)).sort((n,r)=>Ho.stableSerialize(n).localeCompare(Ho.stableSerialize(r)))}function uR(e,t){return e?Ho.stableSerialize({controlDefinitions:jB(e.controlDefinitions,t),cardControlDefinitions:jB(e.cardControlDefinitions,t),controlBindings:S0e(e.controlBindings,t)}):"__none__"}function VT(e,t){return e&&t.has(e)?e:null}function N0e({selectedSheetId:e,preservedSelectedSheetId:t,defaultSheetId:n,sheets:r}){var s;const o=new Set((r||[]).map(i=>i.id).filter(i=>typeof i=="string"));return VT(e,o)||VT(t,o)||VT(n,o)||((s=r==null?void 0:r[0])==null?void 0:s.id)||null}function HY(e){const t=e.trim().split(/[^A-Za-z0-9]+/).filter(Boolean).map(r=>r.toLowerCase());if(!t.length)return"input";const n=t.map((r,o)=>o===0?r:_B(r)).join("");return/^[A-Za-z]/.test(n)?n:`input${_B(n)}`}function bO(e,t){const n=HY(e);return qY(n,t)}function Lv(e){const n=e.trim().replace(/^\{\{\s*/,"").replace(/\s*\}\}$/,"").replace(/[^A-Za-z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"");return n?/^[A-Za-z]/.test(n)?n:`input_${n}`:"input"}function Od(e,t){return qY(Lv(e),t)}function qY(e,t){const n=new Set(t.map(o=>o.variableName).filter(o=>!!o));if(!n.has(e))return e;let r=2;for(;n.has(`${e}${r}`);)r+=1;return`${e}${r}`}function xO(e){return p.getDataType(e.dataType)==="date"?["label","start","end","range"]:["label","value"]}function yO(e){return k0e(e)?["label","value"]:["value"]}function kB(e){return e.kind==="filter"?`filter:${e.filter.id}`:`control:${e.control.id}`}function j0e(e){return{placement:e.hide||e.displayMode==="canvas"?"hidden":"toolbar",...e.toolbarWidth?{widthPx:e.toolbarWidth}:{}}}function UY(e){return{placement:e.hidden?"hidden":e.placement||(e.scope==="card"?"card_header":"toolbar"),...e.toolbarWidth?{widthPx:e.toolbarWidth}:{}}}function fN(e){return!!e.compatibility}function k0e(e){return e.type==="enum"||e.type==="multi_enum"||e.type==="field_selector"||e.type==="metric_selector"||e.type==="aggregation_selector"||e.type==="grain_selector"}function _B(e){return e&&e[0].toUpperCase()+e.slice(1)}function _0e(e){var i,a;const t=[...e.inputs||[]],n=new Set(t.map(c=>c.id)),r=new Set((e.sheets||[]).filter(c=>c.kind==="document").map(c=>c.id));let o=!1;for(const c of e.sheets||[])if(!(c.kind!=="document"||!((a=(i=c.document)==null?void 0:i.inputs)!=null&&a.length)))for(const u of c.document.inputs)n.has(u.id)||(t.push(I0e(u,c.id)),n.add(u.id),o=!0);const s=t.map(c=>{if(c.kind==="filter"&&IB(c,r)&&c.filter.variableName!==c.variableName)return o=!0,{...c,filter:{...c.filter,variableName:c.variableName}};if(c.kind!=="control"||!IB(c,r))return c;const u=Od(c.control.id||c.variableName,t.filter(d=>d.id!==c.id));return c.variableName===u&&c.control.id===u?c:(o=!0,{...c,variableName:u,control:{...c.control,id:u}})});return o?{...e,inputs:s}:e}function I0e(e,t){const n={id:e.id,label:e.label,variableName:e.variableName,description:e.description,requiredAtExecution:e.requiredAtExecution,scope:{kind:"sheets",sheetIds:[t]},runtimeScope:"perSheet",presentation:{placement:"toolbar"},exports:e.exports,compatibility:{source:"documentInput",sheetId:t,inputId:e.id}};return e.kind==="filter"?{...n,kind:"filter",filter:e.filter}:{...n,kind:"control",control:e.control}}function IB(e,t){var n;switch(e.scope.kind){case"allSheets":return!((n=e.scope.sheetKinds)!=null&&n.length)||e.scope.sheetKinds.includes("document");case"sheets":return e.scope.sheetIds.some(r=>t.has(r));case"documentSections":return t.has(e.scope.sheetId);default:return!1}}function T0e(e,t={}){if(!e)return[];const n=[],r=[...t.existingInputs||[]];for(const o of e.inlineFilters||[]){const s=o.title||o.column||o.id,i=E0e(o),a={id:Oi.getCardInlineFilterCompatInputId(e.id,o.id),kind:"filter",label:s,variableName:o.variableName?Od(o.variableName,r):bO(s,r),scope:{kind:"cards",cardIds:[e.id]},runtimeScope:"perCard",presentation:{placement:"card_header"},filter:i,exports:xO(i),compatibility:{source:"cardInlineFilter",cardId:e.id,filterId:o.id}};r.push(a),n.push(a)}for(const o of e.controls||[]){const s=o.label||o.id,i={id:Oi.getCardControlCompatInputId(e.id,o.id),kind:"control",label:s,variableName:Od(o.id,r),scope:{kind:"cards",cardIds:[e.id]},runtimeScope:"perCard",presentation:UY(o),control:o,exports:yO(o),requiredAtExecution:o.requiredAtExecution,compatibility:{source:"cardControl",cardId:e.id,controlId:o.id}};r.push(i),n.push(i)}return n}function E0e(e){return{kind:"field",id:e.id,variableName:e.variableName,type:e.type,uiType:e.uiType,dateSelectionMode:e.dateSelectionMode,defaultValues:e.defaultValues,defaultDateFilter:e.defaultDateFilter,connectionId:e.connectionId,title:e.title,column:e.column,dataType:e.dataType,table:e.table,database:e.database,qualifiedTableName:e.qualifiedTableName,sql:e.sql,operation:e.operation,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext,searchMode:e.searchMode,customFilterPreferences:e.customFilterPreferences,showLabel:e.showLabel,toolbarWidth:e.width,displayMode:"toolbar"}}function D0e(e,t={}){const n=[],r=[...t.existingInputs||[]];for(const o of e.controls||[]){const s=o.label||o.id,i={id:Oi.getDashboardControlCompatInputId(o.id),kind:"control",label:s,variableName:Od(o.id,r),scope:{kind:"allSheets",sheetKinds:["dashboard"]},runtimeScope:"shared",presentation:UY(o),control:o,exports:yO(o),requiredAtExecution:o.requiredAtExecution,compatibility:{source:"dashboardControl",controlId:o.id}};r.push(i),n.push(i)}return n}function M0e(e,t={}){const n=[],r=[...t.existingInputs||[]],o=t.availableSheetIds||(e.sheets||[]).filter(u=>u.kind!=="document").map(u=>u.id),s=p.getDashboardCardEntries({sheets:e.sheets}),i=t.availableCardIds?new Set(t.availableCardIds):void 0,a=s.filter(u=>!i||i.has(u.card.id)),c=t.availableCardIds||a.map(u=>u.card.id);for(const u of e.filters||[]){const d=u.title||u.column||u.id,f={id:Oi.getDashboardFilterCompatInputId(u.id),kind:"filter",label:d,variableName:u.variableName?Od(u.variableName,r):bO(d,r),scope:R0e(u,{availableDashboardSheetIds:o,availableCardEntries:a,availableCardIds:c}),runtimeScope:"shared",presentation:j0e(u),filter:u,exports:xO(u),compatibility:{source:"dashboardFilter",filterId:u.id}};r.push(f),n.push(f)}return n}function R0e(e,t){if(e.applyToCardIds!==void 0){const n=new Set(TB(e,t));return{kind:"cards",cardIds:e.applyToCardIds.filter(r=>n.has(r))}}if(e.excludeCardIds!==void 0){const n=new Set(e.excludeCardIds);return{kind:"cards",cardIds:TB(e,t).filter(o=>!n.has(o))}}if(e.sheetId)return{kind:"sheets",sheetIds:[e.sheetId]};if(e.applyToSheetIds!==void 0)return{kind:"sheets",sheetIds:e.applyToSheetIds};if(e.excludeSheetIds!==void 0){const n=new Set(e.excludeSheetIds);return{kind:"sheets",sheetIds:t.availableDashboardSheetIds.filter(r=>!n.has(r))}}return{kind:"allSheets",sheetKinds:["dashboard"]}}function TB(e,t){return!e.sheetId&&e.applyToSheetIds===void 0&&e.excludeSheetIds===void 0?t.availableCardIds:t.availableCardEntries.filter(n=>A0e(e,n.sheet.id)).map(n=>n.card.id)}function A0e(e,t){return e.sheetId&&e.sheetId!==t?!1:e.applyToSheetIds!==void 0?e.applyToSheetIds.includes(t):e.excludeSheetIds!==void 0?!e.excludeSheetIds.includes(t):!0}function uf({dashboard:e,dashboardInputValues:t}){var r,o;const n=!!(Object.keys((t==null?void 0:t.shared)||{}).length||Object.values((t==null?void 0:t.bySheetId)||{}).some(s=>Object.keys(s).length>0)||Object.values((t==null?void 0:t.byCardId)||{}).some(s=>Object.keys(s).length>0)||Object.values((t==null?void 0:t.byDocumentSectionId)||{}).some(s=>Object.keys(s).length>0));return!!((r=e.inputs)!=null&&r.length||e.defaultInputValues||(o=e.filters)!=null&&o.some(s=>s.kind==="global-date")||n)}function ab({dashboard:e,card:t,availableSheetIds:n,availableCardIds:r}){const o=e.inputs||[],s=[],i=[...o],a=M0e(e,{existingInputs:i,availableSheetIds:n,availableCardIds:r});s.push(...a),i.push(...a);const c=D0e(e,{existingInputs:i});s.push(...c),i.push(...c);const u=T0e(t,{existingInputs:i});return s.push(...u),{authoredInputs:o,compatibilityInputs:s,allInputs:[...o,...s]}}function Yi({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,runtimeValues:s,mode:i="interactive",timezone:a}){var y;const c={sheetId:t,cardId:n==null?void 0:n.id,sectionId:r,sheetKind:o||K0e(e,t)},u=ab({dashboard:e,card:n}),d=Rk(u.allInputs);P0e(d);const f=d.filter(w=>Qh(w,c));W0e(f);const h=f.map(w=>O0e({dashboard:e,input:w,runtimeValues:s,target:c,timezone:a})),m=$0e({resolvedInputs:h,card:n}),g=z0e(h),b=(y=h.find(w=>w.kind==="filter"&&p.isGlobalDateFilter(w.filter)))==null?void 0:y.comparisonSelection,x=h.flatMap((w,C)=>{var j;const N=f[C];if(!N||!p.isComparisonCapableDashboardDateInput(N)||!w.comparisonSelection)return[];const S=((j=w.slot)==null?void 0:j.status)==="set"&&w.slot.value.kind==="filter"?w.slot.value.filterValue:void 0;return[{inputId:w.id,filterId:N.filter.id,label:w.label,filter:N.filter,filterValue:S,selection:w.comparisonSelection}]});return{inputs:f,resolvedInputs:h,...m,...g,...b?{globalDateComparisonSelection:b}:{},dateComparisonInputs:x,missingRequiredInputs:h.filter(w=>w.missingRequiredValue)}}function P0e(e){if(e.filter(n=>n.kind==="filter"&&p.isGlobalDateFilter(n.filter)).length>1)throw new Error("Dashboard input contract allows exactly one Global Date input.")}function Qh(e,t){var n;if(!F0e(e,t))return!1;switch(e.scope.kind){case"allSheets":return(n=e.scope.sheetKinds)!=null&&n.length?t.sheetKind?e.scope.sheetKinds.includes(t.sheetKind):!1:!!t.sheetId||!!t.cardId;case"sheets":return!!t.sheetId&&e.scope.sheetIds.includes(t.sheetId);case"cards":return!!t.cardId&&e.scope.cardIds.includes(t.cardId);case"documentSections":return!!t.sheetId&&!!t.sectionId&&e.scope.sheetId===t.sheetId&&e.scope.sectionIds.includes(t.sectionId);default:return!1}}function F0e(e,t){return t.sheetKind!=="document"||!e.compatibility||e.compatibility.source==="documentInput"?!0:e.compatibility.source==="cardInlineFilter"||e.compatibility.source==="cardControl"?!!t.cardId&&e.compatibility.cardId===t.cardId:!1}function Rk(e){const t=new Set(e.filter(n=>!fN(n)).map(kB));return e.filter(n=>!fN(n)||!t.has(kB(n)))}function O0e(e){var d,f;const t=p.getDashboardInputRuntimeSlot(e.runtimeValues.dashboardInputValues,e.input,e.target),n=p.getDashboardInputRuntimeSlot(e.dashboard.defaultInputValues,e.input,e.target),r=(t==null?void 0:t.comparisonSelection)??(n==null?void 0:n.comparisonSelection),o=p.isComparisonCapableDashboardDateInput(e.input);if(r&&!o)throw new Error(`Dashboard input "${e.input.id}" carries comparison state but is not a supported dashboard date filter.`);const i=fN(e.input)&&((d=e.input.compatibility)==null?void 0:d.source)!=="documentInput"?B0e(e):p.hydrateAuthoredDashboardInputSlot({dashboard:e.dashboard,input:e.input,runtimeValues:e.runtimeValues.dashboardInputValues,target:e.target,timezone:e.timezone}),a=(i==null?void 0:i.status)==="set"&&i.value.kind===e.input.kind?i.value:void 0;if(i!=null&&i.comparisonSelection){if(!o)throw new Error(`Dashboard input "${e.input.id}" carries comparison state but is not a supported dashboard date filter.`);const h=$r.validateGlobalDateComparisonSelection(i.comparisonSelection,`dashboardInputValues.${e.input.id}.comparisonSelection`);if(!h.ok)throw new Error(((f=h.errors[0])==null?void 0:f.message)||"Invalid comparison selection.")}if(e.input.kind==="filter"){const h=(a==null?void 0:a.kind)==="filter"?WY(e.input,a.filterValue):void 0,m=H0e({input:e.input,filterValue:h,timezone:e.timezone});return{id:e.input.id,kind:"filter",label:e.input.label,variableName:e.input.variableName,requiredAtExecution:!!e.input.requiredAtExecution,slot:i,rawValue:h?G0e(h.values):void 0,displayValue:EB(m.label??m.value),exports:m,filter:e.input.filter,filterValue:h,missingRequiredValue:!!e.input.requiredAtExecution&&!h,...o&&(i!=null&&i.comparisonSelection)?{comparisonSelection:i.comparisonSelection}:{}}}const c=(a==null?void 0:a.kind)==="control"?a.value:void 0,u=q0e({input:e.input,value:c});return{id:e.input.id,kind:"control",label:e.input.label,variableName:e.input.variableName,requiredAtExecution:!!e.input.requiredAtExecution,slot:i,rawValue:c,displayValue:EB(u.label??u.value),exports:u,control:e.input.control,controlValue:c,missingRequiredValue:!!e.input.requiredAtExecution&&!L0e(c)}}function L0e(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function $0e({resolvedInputs:e,card:t}){const n=[],r=new Map,o=new Map,s={};for(const c of e){if(c.kind==="filter"){c.filter&&c.filterValue&&n.push(c.filterValue);continue}c.control&&(U0e(c)?o.set(c.control.id,c.control):r.set(c.control.id,c.control),c.controlValue!==void 0&&(s[c.control.id]=c.controlValue))}const i=new Set([...r.keys(),...o.keys()]),a=((t==null?void 0:t.controlBindings)||[]).filter(c=>i.has(c.controlId));return{activeFilters:n,controlDefinitions:Array.from(r.values()),cardControlDefinitions:Array.from(o.values()),controlBindings:a,controlValues:s}}function z0e(e){const t={},n={};for(const r of e)n[r.id]=r,t[r.variableName]=r;return{variablesByName:t,variablesById:n}}function B0e(e){var i,a,c,u;const t=(i=e.input.compatibility)==null?void 0:i.source,n=p.getDashboardInputRuntimeSlot(e.runtimeValues.dashboardInputValues,e.input,e.target),r=p.hydrateAuthoredDashboardInputSlot({dashboard:e.dashboard,input:e.input,runtimeValues:e.runtimeValues.dashboardInputValues,target:e.target,timezone:e.timezone});if((n==null?void 0:n.status)==="set"||(n==null?void 0:n.status)==="cleared")return r;if(e.input.kind==="filter"){const d=e.input.filter.id,f=t==="cardInlineFilter"?e.target.cardId?(c=(a=e.runtimeValues.inlineFilterValuesMap)==null?void 0:a[e.target.cardId])==null?void 0:c.find(m=>m.filterId===d):void 0:(u=e.runtimeValues.filterValues)==null?void 0:u.find(m=>m.filterId===d),h=p.isComparisonCapableDashboardDateInput(e.input)?(r==null?void 0:r.comparisonSelection)??(f?{mode:"off"}:void 0):void 0;if(f){const m=p.createFilterDashboardInputSlot(WY(e.input,f));return(m==null?void 0:m.status)==="set"?{...m,...h?{comparisonSelection:h}:{}}:h?{comparisonSelection:h}:void 0}return h?{comparisonSelection:h}:void 0}const o=e.input.control.id,s=V0e({source:t,target:e.target,runtimeValues:e.runtimeValues});if(s.values&&Object.prototype.hasOwnProperty.call(s.values,o))return p.createControlDashboardInputSlot(s.values[o]);if(!s.isExplicit)return t==="dashboardControl"?p.createControlDashboardInputSlot(p.resolveSavedDefaultValue(e.input.control,e.dashboard.defaultControlValues)):p.getBackingDefaultSlot(e.input,e.timezone)}function V0e({source:e,target:t,runtimeValues:n}){var r;return e==="cardControl"&&t.cardId?{values:(r=n.cardControlValuesMap)==null?void 0:r[t.cardId],isExplicit:!!(n.cardControlValuesMap&&Object.prototype.hasOwnProperty.call(n.cardControlValuesMap,t.cardId))}:{values:n.controlValues,isExplicit:n.controlValues!==void 0}}function WY(e,t){const n=t.filterId===e.filter.id?t:{...t,filterId:e.filter.id};if(p.isCompatibleFilterValue(e.filter,n))return p.normalizeDashboardDateComparisonFilterValue(e,n)}function H0e({input:e,filterValue:t,timezone:n}){const r=e.exports||xO(e.filter),o=(t==null?void 0:t.values)||[],s=p.getDataType(e.filter.dataType)==="date",i=o.map(X0e),a=s?i.length>1?`${i[0]} - ${i[1]}`:i[0]||"":i.join(", "),c={};for(const u of r)u==="start"?c.start=i[0]||null:u==="end"?c.end=i[1]||null:u==="range"?c.range=a||null:c[u]=a||null;return c}function q0e({input:e,value:t}){const n=e.exports||yO(e.control),r=Y0e(t),o=r.map(a=>Z0e(e.control,a)).join(", "),s=r.map(KY).join(", "),i={};for(const a of n)i[a]=a==="label"?o||null:s||null;return i}function U0e(e){return e.control?e.control.scope==="card"||e.id.startsWith("compat-card-control:"):!1}function W0e(e){const t=new Map;for(const n of e){if(fN(n))continue;const r=t.get(n.variableName);if(r)throw new Error(`Duplicate dashboard input variableName "${n.variableName}" for inputs "${r}" and "${n.id}" in the same resolved scope.`);t.set(n.variableName,n.id)}}function K0e(e,t){var r;if(!t)return;const n=(r=e.sheets)==null?void 0:r.find(o=>o.id===t);return(n==null?void 0:n.kind)==="document"?"document":"dashboard"}function G0e(e){return e.length>1?e:e[0]??null}function Y0e(e){return e==null?[]:Array.isArray(e)?e:[e]}function Z0e(e,t){var r;const n=KY(t);return e.source.kind==="manual"&&((r=e.source.options.find(o=>o.value===n))==null?void 0:r.label)||n}function KY(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e==null?"":JSON.stringify(e)}function X0e(e){return e instanceof Date?e.toISOString():typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e==null?"":JSON.stringify(e)}function EB(e){return e==null?"":String(e)}function dR({dashboard:e,dashboardInputValues:t,sheetId:n,cardId:r}){let o=p.compactDashboardInputValues(t||{});const s=J0e({dashboard:e,sheetId:n,cardId:r});if(s.status==="unresolved")return{};o=Q0e({dashboardInputValues:o,savedSheetId:n,cardId:r,targets:s.targets});for(const i of s.targets){const a=Rk(ab({dashboard:e,card:i.card}).allInputs).filter(c=>p.canAddressDashboardInputRuntimeSlot(c,i)&&Qh(c,i));for(const c of a){const u=p.getDashboardInputRuntimeSlot(o,c,i);if(!u||u.status===void 0){o=p.setDashboardInputRuntimeSlot(o,c,i,{status:"cleared",comparisonSelection:u==null?void 0:u.comparisonSelection});continue}u.status==="set"&&p.isComparisonCapableDashboardDateInput(c)&&!u.comparisonSelection&&(o=p.setDashboardInputRuntimeSlot(o,c,i,{...u,comparisonSelection:{mode:"off"}}))}}return p.compactDashboardInputValues(o)}function Q0e({dashboardInputValues:e,savedSheetId:t,cardId:n,targets:r}){var c,u,d,f;const o={},s=new Set(r.flatMap(h=>h.sheetId?[h.sheetId]:[])),i=new Set(r.flatMap(h=>h.cardId?[h.cardId]:[])),a=new Set(r.flatMap(h=>h.sectionId?[h.sectionId]:[]));if(e.shared&&(o.shared={...e.shared}),n){const h=r[0],m=(t?(c=e.bySheetId)==null?void 0:c[t]:void 0)??(h.sheetId?(u=e.bySheetId)==null?void 0:u[h.sheetId]:void 0);h.sheetId&&m&&(o.bySheetId={[h.sheetId]:{...m}});const g=h.cardId?(d=e.byCardId)==null?void 0:d[h.cardId]:void 0;h.cardId&&g&&(o.byCardId={[h.cardId]:{...g}});const b=Object.entries(e.byDocumentSectionId||{}),x=(h.sectionId?(f=e.byDocumentSectionId)==null?void 0:f[h.sectionId]:void 0)??(b.length===1?b[0][1]:void 0);return h.sectionId&&x&&(o.byDocumentSectionId={[h.sectionId]:{...x}}),p.compactDashboardInputValues(o)}return o.bySheetId=HT(e.bySheetId,s),o.byCardId=HT(e.byCardId,i),o.byDocumentSectionId=HT(e.byDocumentSectionId,a),p.compactDashboardInputValues(o)}function HT(e,t){if(!e)return;const n=Object.entries(e).filter(([r])=>t.has(r));return n.length>0?Object.fromEntries(n.map(([r,o])=>[r,{...o}])):void 0}function J0e({dashboard:e,sheetId:t,cardId:n}){var i;if(n){const a=eve(e,n);return a?{status:"resolved",targets:[a]}:{status:"unresolved",targetKind:"card"}}const r=(e.sheets||[]).filter(a=>!t||a.id===t);if(t&&r.length===0)return{status:"unresolved",targetKind:"sheet"};const o=r.map(a=>({sheetId:a.id,sheetKind:a.kind||"dashboard"})),s=new Set(r.map(a=>a.id));for(const a of p.getDashboardCardEntries(e))s.has(a.sheet.id)&&o.push({sheetId:a.sheet.id,cardId:a.card.id,card:a.card,sheetKind:a.sheet.kind||"dashboard"});for(const a of r)if(a.kind==="document")for(const c of((i=a.document)==null?void 0:i.sections)||[])o.push({sheetId:a.id,sectionId:c.id,...(c.type==="table"||c.type==="chart")&&{cardId:c.card.id,card:c.card},sheetKind:"document"});return{status:"resolved",targets:o.length>0?o:[{}]}}function eve(e,t){var r;const n=p.findCardLocationById(e,t);if(n)return{sheetId:n.sheet.id,cardId:n.card.id,card:n.card,sheetKind:n.sheet.kind||"dashboard"};for(const o of e.sheets||[])if(o.kind==="document"){for(const s of((r=o.document)==null?void 0:r.sections)||[])if((s.type==="table"||s.type==="chart")&&s.card.id===t)return{sheetId:o.id,sectionId:s.id,cardId:s.card.id,card:s.card,sheetKind:"document"}}}function GY({dashboardInputValues:e,dashboard:t,filterValues:n,sheetId:r,cardId:o,sectionId:s,sheetKind:i}){var u;if(!((u=t.inputs)!=null&&u.length))return e;const a=new Map(n.map(d=>[d.filterId,d]));let c=e||{};for(const d of t.inputs){if(d.kind!=="filter"||!Qh(d,{sheetId:r,cardId:o,sectionId:s,sheetKind:i}))continue;const f=a.get(d.filter.id),h=f?p.createFilterDashboardInputSlot(f):void 0,m=(h==null?void 0:h.status)==="set"?h:{status:"cleared"};c=p.setDashboardInputRuntimeValueAspect(c,d,{sheetId:r,cardId:o,sectionId:s},m)}return c}function ru({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,mode:s,runtimeValues:i,generatedAt:a,timezone:c}){const u=f1({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,mode:s,runtimeValues:i,timezone:c});return{context:u,snapshot:{...t?{sheetId:t}:{},...n!=null&&n.id?{cardId:n.id}:{},mode:s,dashboardInputValues:nve({inputs:u.inputs,context:u,sheetId:t,cardId:n==null?void 0:n.id,sectionId:r}),generatedAt:a,timezone:c}}}function YY({sectionIds:e,...t}){const n=new Set,r=o=>{for(const s of o.missingRequiredInputs)n.add(s.label)};r(f1(t));for(const o of e)r(f1({...t,sectionId:o}));for(const{sectionId:o,card:s}of XY(t.dashboard,t.sheetId,e))r(f1({...t,sectionId:o,card:s}));return Array.from(n)}function vO({sheetIds:e,sheetKind:t="dashboard",...n}){const r=e.map(a=>ru({...n,sheetId:a,sheetKind:t})),o=e.flatMap(a=>tve(n.dashboard,a).map(c=>ru({...n,sheetId:a,card:c,sheetKind:t}))),s=r[0]||o[0]||ru({...n,sheetKind:t}),i=QY(...r.map(a=>a.snapshot.dashboardInputValues),...o.map(a=>a.snapshot.dashboardInputValues));return{context:s.context,snapshot:{...e.length===1?{sheetId:e[0]}:{},mode:n.mode,dashboardInputValues:i,generatedAt:n.generatedAt,timezone:n.timezone}}}function tve(e,t){var i;const n=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),r=[],o=new Set,s=a=>{!(a!=null&&a.id)||o.has(a.id)||(o.add(a.id),r.push(a))};for(const a of(n==null?void 0:n.cards)||[])s(a);for(const a of(n==null?void 0:n.frames)||[])for(const c of(a==null?void 0:a.cards)||[])s(c);return r}function ZY({sectionIds:e,...t}){const n=ru(t),r=e.map(s=>ru({...t,sectionId:s})),o=XY(t.dashboard,t.sheetId,e).map(({sectionId:s,card:i})=>ru({...t,sectionId:s,card:i}));return{...n,snapshot:{...n.snapshot,dashboardInputValues:QY(n.snapshot.dashboardInputValues,...r.map(s=>s.snapshot.dashboardInputValues),...o.map(s=>s.snapshot.dashboardInputValues))}}}function XY(e,t,n){var i,a;const r=new Set(n),o=(i=e.sheets)==null?void 0:i.find(c=>c.id===t);return(((a=o==null?void 0:o.document)==null?void 0:a.sections)||[]).flatMap(c=>c.id&&r.has(c.id)&&c.card?[{sectionId:c.id,card:c.card}]:[])}function nve({inputs:e,context:t,sheetId:n,cardId:r,sectionId:o}){const s=new Map(t.resolvedInputs.map(a=>[a.id,a]));let i={};for(const a of e){const c=s.get(a.id),u=(c==null?void 0:c.slot)||{status:"cleared"};i=p.setDashboardInputRuntimeSlot(i,a,{sheetId:n,cardId:r,sectionId:o},u)}return p.compactDashboardInputValues(i)}function rve(e){return e==="document"||e==="visual"?"export":"print"}function f1({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,mode:s,runtimeValues:i,timezone:a}){return Yi({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,runtimeValues:i,mode:rve(s),timezone:a})}function QY(...e){const t={};for(const n of e)n.shared&&(t.shared={...t.shared,...n.shared}),qT(t,"bySheetId",n.bySheetId),qT(t,"byCardId",n.byCardId),qT(t,"byDocumentSectionId",n.byDocumentSectionId);return p.compactDashboardInputValues(t)}function qT(e,t,n){if(n){e[t]||(e[t]={});for(const[r,o]of Object.entries(n))e[t][r]={...e[t][r],...o}}}function JY(e){var n;return typeof window>"u"||new URLSearchParams(window.location.search).get("isPdfRender")!=="true"?null:((n=lb(e))==null?void 0:n.reportContext)??null}function lb(e){if(typeof window>"u")return e?$t.parsePresentationExecutionSnapshot(e):null;const t=new URLSearchParams(window.location.search);if(t.get("isPdfRender")!=="true")return null;if(e)return $t.parsePresentationExecutionSnapshot(e);const n=t.get("presentationExecutionSnapshot");if(!n)return null;let r;try{r=JSON.parse(n)}catch{throw new $t.PresentationExecutionSnapshotError("Internal print presentation snapshot JSON is invalid.")}return $t.parsePresentationExecutionSnapshot(r)}function $v(){if(typeof window>"u")return;const e=new URLSearchParams(window.location.search).get("presentationAttachmentIndex");if(e===null)return;const t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error("Internal print presentation attachment index is invalid");return t}function ove(e){return e==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e}function sve(e,t){const n=ove(e);return n==="dark"?Jl({...t==null?void 0:t.default},{...t==null?void 0:t.dark}):t==null?void 0:t.default}function DB(e,t,n){return wye(sve(e,t),n)}function ive(e){return Ho.stableSerialize({hasExplicitDefaultControlValues:e!==void 0,values:e??null})}function ave(e,t){const{controlContractOverrides:n,cardId:r}=t;if(!n||(n.controlDefinitions!==void 0&&(e.controls=n.controlDefinitions),typeof r!="string"||r.trim().length===0))return e;const o=p.findCardById(e,r);return o&&(n.cardControlDefinitions!==void 0&&(o.controls=n.cardControlDefinitions),n.controlBindings!==void 0&&(o.controlBindings=n.controlBindings)),e}function lve(e,t){const n=v.useRef({key:t,value:e});return n.current.key!==t&&(n.current={key:t,value:e}),n.current.value}function cve({customStyle:e,currentTheme:t,onSave:n,onEvent:r,defaultFilterValues:o,defaultControlValues:s,controlContractOverrides:i,dashboardInputExecutionSnapshot:a,interactionExecutionSnapshot:c,presentationExecutionSnapshot:u,type:d,cardId:f,selectedSheetId:h,onFilterValuesChange:m}){var ie,we;const{authToken:g,tokenProps:b}=It(),x=g==null?void 0:g.accessToken,y=g==null?void 0:g.refreshToken,w=v.useMemo(()=>JY(u),[u]);o0e();const C=p.useDashboardStore(fe=>fe.selectedLensId),N=p.useDashboardStore(fe=>fe.relaodToken),{data:S,isLoading:j,isFetching:_,isError:k,refetch:T,dashboardIdToFetch:I}=Pv(),E=(ie=S==null?void 0:S.dashboard)==null?void 0:ie.id,{getDefaultSheetId:D,clearDefaultSheetId:R}=_Y(E),[A,F]=v.useState(o||[]),z=v.useRef(null),L=v.useRef(null),$=ive(s),H=uR(i),M=uR(i,{includePresentation:!0}),B=v.useRef(s);B.current=s;const W=v.useRef($);W.current=$;const P=lve(i,M),G=v.useRef(null),Z=v.useRef(!1),X=v.useRef({dashboardId:null,defaultControlValuesKey:$,controlContractOverridesKey:H}),{setTheme:Y}=oO(),{compiledAppearance:O}=p.useAppearance(),q=p.useDashboardStore(fe=>fe.dashboard.globalStyle),U=v.useMemo(()=>S!=null&&S.dashboard?_0e(ave(Ks(S.dashboard),{controlContractOverrides:P,cardId:f})):void 0,[S==null?void 0:S.dashboard,P,d,f]),{setDashboardWithFilterValues:V,hydrateRuntimeControlValues:K,setStyle:Q,setOnSaveFunction:se,setLenses:oe,setSelectedLensId:me,setInlineFilterValuesMap:le}=p.useDashboardActions();p.useDashboardStore(fe=>fe.actions.setCustomCards);const ue=p.useDashboardStore(fe=>fe.filterValues),ne=p.useDashboardStore(fe=>fe.actions.setThemeStyle),de=p.useDashboardStore(fe=>fe.actions.setDashboardTheme),Ce=p.useDashboardStore(fe=>fe.actions.setOnEvent);v.useEffect(()=>{const fe=L.current;fe&&fe!==I&&p.storeEvents.emit("dashboard:unload"),L.current=I},[I]),v.useEffect(()=>{N&&T()},[T,N]),v.useEffect(()=>{var ee;const fe=((ee=S==null?void 0:S.dashboard)==null?void 0:ee.id)||null,ae=z.current;fe&&fe!==ae&&p.storeEvents.emit("dashboard:load"),z.current=fe},[(we=S==null?void 0:S.dashboard)==null?void 0:we.id]),v.useEffect(()=>{de(O.mode)},[O.mode,de]),v.useEffect(()=>{t&&Y(t)},[t,Y]);const ce=v.useCallback(()=>{const fe=Ks(dt.DEFAULT_STYLE),ae=Jl(fe,q);if(e){const ee=Jl(ae,e),J=DB(O.mode,ee,O);ne(J),Q(ee)}else{const ee=DB(O.mode,ae,O);ne(ee),Q(dt.DEFAULT_STYLE)}},[O,e,q,ne,Q]);return v.useEffect(()=>{S&&S.dashboard&&ce()},[O.mode,e,q,ce,S]),v.useEffect(()=>{var ct,rt,Ct,Lt,vt,Tt;function fe(Me,Je){const kt=Me.filters||[],mt=[];for(const _t of Je){const Rt=kt.find(Pt=>Pt.id===_t.filterId);Rt&&mt.push({filterId:_t.filterId,name:Rt.column,operation:_t.operation,valueType:p.getFilterValueType(Rt),values:_t.values,dataType:Rt.dataType,fieldMeta:Rt.fieldMeta,semanticContext:Rt.semanticContext})}return mt}if(!S||!U)return;const ae=U,ee=p.useDashboardStore.getState(),J=ee.reportContextSessionAccessToken===x&&((ct=ee.dashboard)==null?void 0:ct.id)===U.id&&ee.reportContext!==null,re=w??S.initialReportContext,pe=(J?(rt=ee.reportContext)==null?void 0:rt.calendar.tz:void 0)??re.calendar.tz,{filterValues:Ee,defaultLensId:Te,lenses:ze}=S;function Pe(){if(Ee&&(Ee==null?void 0:Ee.length)>0)return Ee;const Je=[...p.buildFilterValuesFromDefaults(ae.filters,pe)];if(ae.defaultFilterValues&&ae.defaultFilterValues.length>0)for(const _t of ae.defaultFilterValues){const Rt=Je.findIndex(Pt=>Pt.filterId===_t.filterId);Rt>=0?Je[Rt]=_t:Je.push(_t)}const kt=fe(ae,A||[]),mt=[...Je];for(const _t of kt){const Rt=mt.findIndex(Pt=>Pt.filterId===_t.filterId);Rt>=0?mt[Rt]=_t:mt.push(_t)}return mt}const He=G.current===U.id&&((Ct=ee.dashboard)==null?void 0:Ct.id)===U.id,ye=Pe(),Ke=He?p.resolveSameDashboardFilterValues({previousFilters:(Lt=ee.dashboard)==null?void 0:Lt.filters,nextFilters:ae.filters,currentFilterValues:ee.filterValues,defaultFilterValues:ye}):ye,We=p.computeInlineFilterDefaults(ae,pe),Qe=He&&X.current.controlContractOverridesKey===H?p.flattenRuntimeControlValues({dashboardValues:ee.controlValues,cardValuesMap:ee.cardControlValuesMap}):B.current,xe=ee.selectedSheetId;let Ve=D(),Ae=xe;Ae&&((vt=U==null?void 0:U.sheets)!=null&&vt.some(Je=>Je.id===Ae)||(Ae=null)),Ve&&((Tt=U==null?void 0:U.sheets)!=null&&Tt.some(Je=>Je.id===Ve)||(R(),Ve=null));const ke=N0e({selectedSheetId:h,preservedSelectedSheetId:Ae,defaultSheetId:Ve,sheets:U==null?void 0:U.sheets}),Be=!!a,Ie=!!(C||S!=null&&S.defaultLensId),$e=!Be&&Z.current,st=a?dR({dashboard:ae,dashboardInputValues:a.dashboardInputValues,sheetId:a.sheetId,cardId:a.cardId}):(S==null?void 0:S.inputValues)!=null?dR({dashboard:ae,dashboardInputValues:S.inputValues.dashboardInputValues}):void 0;V(ae,Ke||[],Qe,{selectedSheetId:ke,reportContext:J?void 0:re,authToken:x?{accessToken:x,refreshToken:y}:void 0,...S!=null&&S.semanticExecutionPayload?{semanticExecutionPayload:S.semanticExecutionPayload}:{},...a?{dashboardInputValues:st,dashboardInputReferenceTime:a.generatedAt}:Ie?{dashboardInputValues:st||{},dashboardInputReferenceTime:(S==null?void 0:S.inputValues)!=null?S.inputValues.generatedAt:void 0}:$e?{dashboardInputValues:{},dashboardInputReferenceTime:void 0}:{}}),c&&p.useInteractionStore.setState({interactionStates:Ks(c)}),Z.current=Be,G.current=U.id,X.current.dashboardId!==U.id&&(X.current={dashboardId:U.id,defaultControlValuesKey:W.current,controlContractOverridesKey:H}),le(We),ze&&oe(ze),Te&&me(Te)},[S,C,oe,V,me,le,A,h,D,R,H,a,c,U,x,y,w]),v.useEffect(()=>{if(!(U!=null&&U.id))return;const fe=X.current;if(fe.dashboardId!==U.id){X.current={dashboardId:U.id,defaultControlValuesKey:$,controlContractOverridesKey:H};return}fe.defaultControlValuesKey===$&&fe.controlContractOverridesKey===H||(K(U,B.current),X.current={dashboardId:U.id,defaultControlValuesKey:$,controlContractOverridesKey:H})},[U,$,H,K]),v.useEffect(()=>{m&&ue&&m(ue)},[ue,m]),v.useEffect(()=>{n&&se(n),r&&Ce(r)},[n,se,r,Ce]),{isFetching:_,isLoading:j,isError:k,refetch:T}}const hN=te.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:p.cn("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));hN.displayName="Card";const wO=te.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:p.cn("flex flex-col space-y-1.5 p-6",e),...t}));wO.displayName="CardHeader";const cb=te.forwardRef(({className:e,...t},n)=>l.jsx("h3",{ref:n,className:p.cn("text-2xl font-semibold leading-none tracking-tight",e),...t}));cb.displayName="CardTitle";const uve=te.forwardRef(({className:e,...t},n)=>l.jsx("p",{ref:n,className:p.cn("text-sm text-muted-foreground",e),...t}));uve.displayName="CardDescription";const CO=te.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:p.cn("px-6 pt-0",e),...t}));CO.displayName="CardContent";const eZ=te.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:p.cn("flex items-center p-6 pt-0",e),...t}));eZ.displayName="CardFooter";/**
|
|
1
|
+
"use strict";var Lxe=Object.defineProperty;var sB=e=>{throw TypeError(e)};var $xe=(e,t,n)=>t in e?Lxe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ne=(e,t,n)=>$xe(e,typeof t!="symbol"?t+"":t,n),$T=(e,t,n)=>t.has(e)||sB("Cannot "+n);var ve=(e,t,n)=>($T(e,t,"read from private field"),n?n.call(e):t.get(e)),At=(e,t,n)=>t.has(e)?sB("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),yt=(e,t,n,r)=>($T(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Qt=(e,t,n)=>($T(e,t,"access private method"),n);var hC=(e,t,n,r)=>({set _(o){yt(e,t,o,n)},get _(){return ve(e,t,r)}});const l=require("react/jsx-runtime"),v=require("react"),br=require("react-dom"),p=require("./switch-BHOdIXq3.cjs"),je=require("./x-B6ghREd2.cjs"),dt=require("./saved-temporal-bucket-format-CFfWXRl9.cjs"),va=require("./validators-BDYprKI9.cjs");require("./analyze-result-contract-LPDNldic.cjs");const Li=require("../value-format-preferences/index.cjs"),cf=require("./index-ByFbacH7.cjs"),zxe=require("react-dom/client"),qc=require("./temporal-bucket-authoring-o3Emn05L.cjs"),Ft=require("./search-BqqhaMx9.cjs"),Tk=require("./canonical-result-keys-BA0HCP4e.cjs"),Bxe=require("./color-CyB5o13F.cjs"),Vxe=require("./token-types-D7CaaI80.cjs"),it=require("./index-C99Ow35Y.cjs"),$r=require("./temporal-bucket-DHY1y9lq.cjs"),fn=require("./pivot-header-presentation-DhyQXxKq.cjs"),wa=require("./pivot-result-identity-Bb4EixVN.cjs"),$t=require("./pivot-result-lifecycle-DmcF1ris.cjs"),Kt=require("./format-types-PSZZ7hG8.cjs"),Oi=require("./matrix-result-contract-zamd9euI.cjs"),Ho=require("./normalize-dashboard-for-dirty-check-BXRUMVb2.cjs"),xr=require("./common-types-C57kJ59w.cjs"),nY=require("../dashboard-assistant/index.cjs"),rY=require("./report-runtime-context-DqxS4wbi.cjs"),Hxe=require("./contracts-CtB2VONT.cjs"),qxe=require("../layouts/index.cjs"),iB=require("./index-F25jnH0p.cjs");function rO(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const aB=rO(l),te=rO(v),V2=rO(br);function Uxe(e){return Kt.toDate(e).getMonth()}function Wxe(e){return Kt.toDate(e).getFullYear()}function Xx(e,t){const r=Zxe(e);let o;if(r.date){const c=Xxe(r.date,2);o=Qxe(c.restDateString,c.year)}if(!o||isNaN(o.getTime()))return new Date(NaN);const s=o.getTime();let i=0,a;if(r.time&&(i=Jxe(r.time),isNaN(i)))return new Date(NaN);if(r.timezone){if(a=eye(r.timezone),isNaN(a))return new Date(NaN)}else{const c=new Date(s+i),u=new Date(0);return u.setFullYear(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()),u.setHours(c.getUTCHours(),c.getUTCMinutes(),c.getUTCSeconds(),c.getUTCMilliseconds()),u}return new Date(s+i+a)}const mC={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},Kxe=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,Gxe=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,Yxe=/^([+-])(\d{2})(?::?(\d{2}))?$/;function Zxe(e){const t={},n=e.split(mC.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],mC.timeZoneDelimiter.test(t.date)&&(t.date=e.split(mC.timeZoneDelimiter)[0],r=e.substr(t.date.length,e.length))),r){const o=mC.timezone.exec(r);o?(t.time=r.replace(o[1],""),t.timezone=o[1]):t.time=r}return t}function Xxe(e,t){const n=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),r=e.match(n);if(!r)return{year:NaN,restDateString:""};const o=r[1]?parseInt(r[1]):null,s=r[2]?parseInt(r[2]):null;return{year:s===null?o:s*100,restDateString:e.slice((r[1]||r[2]).length)}}function Qxe(e,t){if(t===null)return new Date(NaN);const n=e.match(Kxe);if(!n)return new Date(NaN);const r=!!n[4],o=ux(n[1]),s=ux(n[2])-1,i=ux(n[3]),a=ux(n[4]),c=ux(n[5])-1;if(r)return sye(t,a,c)?tye(t,a,c):new Date(NaN);{const u=new Date(0);return!rye(t,s,i)||!oye(t,o)?new Date(NaN):(u.setUTCFullYear(t,s,Math.max(o,i)),u)}}function ux(e){return e?parseInt(e):1}function Jxe(e){const t=e.match(Gxe);if(!t)return NaN;const n=zT(t[1]),r=zT(t[2]),o=zT(t[3]);return iye(n,r,o)?n*Kt.millisecondsInHour+r*Kt.millisecondsInMinute+o*1e3:NaN}function zT(e){return e&&parseFloat(e.replace(",","."))||0}function eye(e){if(e==="Z")return 0;const t=e.match(Yxe);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),o=t[3]&&parseInt(t[3])||0;return aye(r,o)?n*(r*Kt.millisecondsInHour+o*Kt.millisecondsInMinute):NaN}function tye(e,t,n){const r=new Date(0);r.setUTCFullYear(e,0,4);const o=r.getUTCDay()||7,s=(t-1)*7+n+1-o;return r.setUTCDate(r.getUTCDate()+s),r}const nye=[31,null,31,30,31,30,31,31,30,31,30,31];function oY(e){return e%400===0||e%4===0&&e%100!==0}function rye(e,t,n){return t>=0&&t<=11&&n>=1&&n<=(nye[t]||(oY(e)?29:28))}function oye(e,t){return t>=1&&t<=(oY(e)?366:365)}function sye(e,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function iye(e,t,n){return e===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&e>=0&&e<25}function aye(e,t){return t>=0&&t<=59}var sN={exports:{}};sN.exports;(function(e,t){var n=200,r="__lodash_hash_undefined__",o=800,s=16,i=9007199254740991,a="[object Arguments]",c="[object Array]",u="[object AsyncFunction]",d="[object Boolean]",f="[object Date]",h="[object Error]",m="[object Function]",g="[object GeneratorFunction]",b="[object Map]",x="[object Number]",y="[object Null]",w="[object Object]",C="[object Proxy]",N="[object RegExp]",S="[object Set]",j="[object String]",_="[object Undefined]",k="[object WeakMap]",T="[object ArrayBuffer]",I="[object DataView]",E="[object Float32Array]",D="[object Float64Array]",R="[object Int8Array]",A="[object Int16Array]",F="[object Int32Array]",z="[object Uint8Array]",L="[object Uint8ClampedArray]",$="[object Uint16Array]",H="[object Uint32Array]",M=/[\\^$.*+?()[\]{}|]/g,B=/^\[object .+?Constructor\]$/,W=/^(?:0|[1-9]\d*)$/,P={};P[E]=P[D]=P[R]=P[A]=P[F]=P[z]=P[L]=P[$]=P[H]=!0,P[a]=P[c]=P[T]=P[d]=P[I]=P[f]=P[h]=P[m]=P[b]=P[x]=P[w]=P[N]=P[S]=P[j]=P[k]=!1;var G=typeof dt.commonjsGlobal=="object"&&dt.commonjsGlobal&&dt.commonjsGlobal.Object===Object&&dt.commonjsGlobal,Z=typeof self=="object"&&self&&self.Object===Object&&self,X=G||Z||Function("return this")(),Y=t&&!t.nodeType&&t,O=Y&&!0&&e&&!e.nodeType&&e,q=O&&O.exports===Y,U=q&&G.process,V=function(){try{var be=O&&O.require&&O.require("util").types;return be||U&&U.binding&&U.binding("util")}catch{}}(),K=V&&V.isTypedArray;function Q(be,_e,qe){switch(qe.length){case 0:return be.call(_e);case 1:return be.call(_e,qe[0]);case 2:return be.call(_e,qe[0],qe[1]);case 3:return be.call(_e,qe[0],qe[1],qe[2])}return be.apply(_e,qe)}function se(be,_e){for(var qe=-1,Ot=Array(be);++qe<be;)Ot[qe]=_e(qe);return Ot}function oe(be){return function(_e){return be(_e)}}function me(be,_e){return be==null?void 0:be[_e]}function le(be,_e){return function(qe){return be(_e(qe))}}var ue=Array.prototype,ne=Function.prototype,de=Object.prototype,Ce=X["__core-js_shared__"],ce=ne.toString,ie=de.hasOwnProperty,we=function(){var be=/[^.]+$/.exec(Ce&&Ce.keys&&Ce.keys.IE_PROTO||"");return be?"Symbol(src)_1."+be:""}(),fe=de.toString,ae=ce.call(Object),ee=RegExp("^"+ce.call(ie).replace(M,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),J=q?X.Buffer:void 0,re=X.Symbol,pe=X.Uint8Array;J&&J.allocUnsafe;var Ee=le(Object.getPrototypeOf,Object),Te=Object.create,ze=de.propertyIsEnumerable,Pe=ue.splice,He=re?re.toStringTag:void 0,ye=function(){try{var be=Co(Object,"defineProperty");return be({},"",{}),be}catch{}}(),Ke=J?J.isBuffer:void 0,We=Math.max,Qe=Date.now,xe=Co(X,"Map"),Ve=Co(Object,"create"),Ae=function(){function be(){}return function(_e){if(!Ht(_e))return{};if(Te)return Te(_e);be.prototype=_e;var qe=new be;return be.prototype=void 0,qe}}();function ke(be){var _e=-1,qe=be==null?0:be.length;for(this.clear();++_e<qe;){var Ot=be[_e];this.set(Ot[0],Ot[1])}}function Be(){this.__data__=Ve?Ve(null):{},this.size=0}function Ie(be){var _e=this.has(be)&&delete this.__data__[be];return this.size-=_e?1:0,_e}function $e(be){var _e=this.__data__;if(Ve){var qe=_e[be];return qe===r?void 0:qe}return ie.call(_e,be)?_e[be]:void 0}function st(be){var _e=this.__data__;return Ve?_e[be]!==void 0:ie.call(_e,be)}function ct(be,_e){var qe=this.__data__;return this.size+=this.has(be)?0:1,qe[be]=Ve&&_e===void 0?r:_e,this}ke.prototype.clear=Be,ke.prototype.delete=Ie,ke.prototype.get=$e,ke.prototype.has=st,ke.prototype.set=ct;function rt(be){var _e=-1,qe=be==null?0:be.length;for(this.clear();++_e<qe;){var Ot=be[_e];this.set(Ot[0],Ot[1])}}function Ct(){this.__data__=[],this.size=0}function Lt(be){var _e=this.__data__,qe=ot(_e,be);if(qe<0)return!1;var Ot=_e.length-1;return qe==Ot?_e.pop():Pe.call(_e,qe,1),--this.size,!0}function vt(be){var _e=this.__data__,qe=ot(_e,be);return qe<0?void 0:_e[qe][1]}function Tt(be){return ot(this.__data__,be)>-1}function Me(be,_e){var qe=this.__data__,Ot=ot(qe,be);return Ot<0?(++this.size,qe.push([be,_e])):qe[Ot][1]=_e,this}rt.prototype.clear=Ct,rt.prototype.delete=Lt,rt.prototype.get=vt,rt.prototype.has=Tt,rt.prototype.set=Me;function Je(be){var _e=-1,qe=be==null?0:be.length;for(this.clear();++_e<qe;){var Ot=be[_e];this.set(Ot[0],Ot[1])}}function kt(){this.size=0,this.__data__={hash:new ke,map:new(xe||rt),string:new ke}}function mt(be){var _e=Lr(this,be).delete(be);return this.size-=_e?1:0,_e}function _t(be){return Lr(this,be).get(be)}function Rt(be){return Lr(this,be).has(be)}function Pt(be,_e){var qe=Lr(this,be),Ot=qe.size;return qe.set(be,_e),this.size+=qe.size==Ot?0:1,this}Je.prototype.clear=kt,Je.prototype.delete=mt,Je.prototype.get=_t,Je.prototype.has=Rt,Je.prototype.set=Pt;function wt(be){var _e=this.__data__=new rt(be);this.size=_e.size}function Et(){this.__data__=new rt,this.size=0}function Bt(be){var _e=this.__data__,qe=_e.delete(be);return this.size=_e.size,qe}function un(be){return this.__data__.get(be)}function Ge(be){return this.__data__.has(be)}function Re(be,_e){var qe=this.__data__;if(qe instanceof rt){var Ot=qe.__data__;if(!xe||Ot.length<n-1)return Ot.push([be,_e]),this.size=++qe.size,this;qe=this.__data__=new Je(Ot)}return qe.set(be,_e),this.size=qe.size,this}wt.prototype.clear=Et,wt.prototype.delete=Bt,wt.prototype.get=un,wt.prototype.has=Ge,wt.prototype.set=Re;function De(be,_e){var qe=vc(be),Ot=!qe&&yc(be),gn=!qe&&!Ot&&us(be),Vn=!qe&&!Ot&&!gn&&Gt(be),mr=qe||Ot||gn||Vn,Hn=mr?se(be.length,String):[],cr=Hn.length;for(var _i in be)mr&&(_i=="length"||gn&&(_i=="offset"||_i=="parent")||Vn&&(_i=="buffer"||_i=="byteLength"||_i=="byteOffset")||xl(_i,cr))||Hn.push(_i);return Hn}function he(be,_e,qe){(qe!==void 0&&!yl(be[_e],qe)||qe===void 0&&!(_e in be))&&Dt(be,_e,qe)}function Fe(be,_e,qe){var Ot=be[_e];(!(ie.call(be,_e)&&yl(Ot,qe))||qe===void 0&&!(_e in be))&&Dt(be,_e,qe)}function ot(be,_e){for(var qe=be.length;qe--;)if(yl(be[qe][0],_e))return qe;return-1}function Dt(be,_e,qe){_e=="__proto__"&&ye?ye(be,_e,{configurable:!0,enumerable:!0,value:qe,writable:!0}):be[_e]=qe}var nt=Rs();function ge(be){return be==null?be===void 0?_:y:He&&He in Object(be)?Qi(be):oi(be)}function Se(be){return wn(be)&&ge(be)==a}function Oe(be){if(!Ht(be)||Ps(be))return!1;var _e=Wu(be)?ee:B;return _e.test(Uu(be))}function Ye(be){return wn(be)&&Xe(be.length)&&!!P[ge(be)]}function bt(be){if(!Ht(be))return qu(be);var _e=If(be),qe=[];for(var Ot in be)Ot=="constructor"&&(_e||!ie.call(be,Ot))||qe.push(Ot);return qe}function St(be,_e,qe,Ot,gn){be!==_e&&nt(_e,function(Vn,mr){if(gn||(gn=new wt),Ht(Vn))on(be,_e,mr,qe,St,Ot,gn);else{var Hn=Ot?Ot($n(be,mr),Vn,mr+"",be,_e,gn):void 0;Hn===void 0&&(Hn=Vn),he(be,mr,Hn)}},An)}function on(be,_e,qe,Ot,gn,Vn,mr){var Hn=$n(be,qe),cr=$n(_e,qe),_i=mr.get(cr);if(_i){he(be,qe,_i);return}var Fs=Vn?Vn(Hn,cr,qe+"",be,_e,mr):void 0,Gu=Fs===void 0;if(Gu){var lx=vc(cr),cx=!lx&&us(cr),fC=!lx&&!cx&&Gt(cr);Fs=cr,lx||cx||fC?vc(Hn)?Fs=Hn:So(Hn)?Fs=Vt(Hn):cx?(Gu=!1,Fs=et(cr)):fC?(Gu=!1,Fs=ht(cr)):Fs=[]:nn(cr)||yc(cr)?(Fs=Hn,yc(Hn)?Fs=or(Hn):(!Ht(Hn)||Wu(Hn))&&(Fs=Hu(cr))):Gu=!1}Gu&&(mr.set(cr,Fs),gn(Fs,cr,Ot,Vn,mr),mr.delete(cr)),he(be,qe,Fs)}function sn(be,_e){return Tf(xc(be,_e,co),be+"")}var Le=ye?function(be,_e){return ye(be,"toString",{configurable:!0,enumerable:!1,value:Nr(_e),writable:!0})}:co;function et(be,_e){return be.slice()}function at(be){var _e=new be.constructor(be.byteLength);return new pe(_e).set(new pe(be)),_e}function ht(be,_e){var qe=at(be.buffer);return new be.constructor(qe,be.byteOffset,be.length)}function Vt(be,_e){var qe=-1,Ot=be.length;for(_e||(_e=Array(Ot));++qe<Ot;)_e[qe]=be[qe];return _e}function Xn(be,_e,qe,Ot){var gn=!qe;qe||(qe={});for(var Vn=-1,mr=_e.length;++Vn<mr;){var Hn=_e[Vn],cr=void 0;cr===void 0&&(cr=be[Hn]),gn?Dt(qe,Hn,cr):Fe(qe,Hn,cr)}return qe}function Go(be){return sn(function(_e,qe){var Ot=-1,gn=qe.length,Vn=gn>1?qe[gn-1]:void 0,mr=gn>2?qe[2]:void 0;for(Vn=be.length>3&&typeof Vn=="function"?(gn--,Vn):void 0,mr&&ki(qe[0],qe[1],mr)&&(Vn=gn<3?void 0:Vn,gn=1),_e=Object(_e);++Ot<gn;){var Hn=qe[Ot];Hn&&be(_e,Hn,Ot,Vn)}return _e})}function Rs(be){return function(_e,qe,Ot){for(var gn=-1,Vn=Object(_e),mr=Ot(_e),Hn=mr.length;Hn--;){var cr=mr[++gn];if(qe(Vn[cr],cr,Vn)===!1)break}return _e}}function Lr(be,_e){var qe=be.__data__;return As(_e)?qe[typeof _e=="string"?"string":"hash"]:qe.map}function Co(be,_e){var qe=me(be,_e);return Oe(qe)?qe:void 0}function Qi(be){var _e=ie.call(be,He),qe=be[He];try{be[He]=void 0;var Ot=!0}catch{}var gn=fe.call(be);return Ot&&(_e?be[He]=qe:delete be[He]),gn}function Hu(be){return typeof be.constructor=="function"&&!If(be)?Ae(Ee(be)):{}}function xl(be,_e){var qe=typeof be;return _e=_e??i,!!_e&&(qe=="number"||qe!="symbol"&&W.test(be))&&be>-1&&be%1==0&&be<_e}function ki(be,_e,qe){if(!Ht(qe))return!1;var Ot=typeof _e;return(Ot=="number"?vl(qe)&&xl(_e,qe.length):Ot=="string"&&_e in qe)?yl(qe[_e],be):!1}function As(be){var _e=typeof be;return _e=="string"||_e=="number"||_e=="symbol"||_e=="boolean"?be!=="__proto__":be===null}function Ps(be){return!!we&&we in be}function If(be){var _e=be&&be.constructor,qe=typeof _e=="function"&&_e.prototype||de;return be===qe}function qu(be){var _e=[];if(be!=null)for(var qe in Object(be))_e.push(qe);return _e}function oi(be){return fe.call(be)}function xc(be,_e,qe){return _e=We(_e===void 0?be.length-1:_e,0),function(){for(var Ot=arguments,gn=-1,Vn=We(Ot.length-_e,0),mr=Array(Vn);++gn<Vn;)mr[gn]=Ot[_e+gn];gn=-1;for(var Hn=Array(_e+1);++gn<_e;)Hn[gn]=Ot[gn];return Hn[_e]=qe(mr),Q(be,this,Hn)}}function $n(be,_e){if(!(_e==="constructor"&&typeof be[_e]=="function")&&_e!="__proto__")return be[_e]}var Tf=Ma(Le);function Ma(be){var _e=0,qe=0;return function(){var Ot=Qe(),gn=s-(Ot-qe);if(qe=Ot,gn>0){if(++_e>=o)return arguments[0]}else _e=0;return be.apply(void 0,arguments)}}function Uu(be){if(be!=null){try{return ce.call(be)}catch{}try{return be+""}catch{}}return""}function yl(be,_e){return be===_e||be!==be&&_e!==_e}var yc=Se(function(){return arguments}())?Se:function(be){return wn(be)&&ie.call(be,"callee")&&!ze.call(be,"callee")},vc=Array.isArray;function vl(be){return be!=null&&Xe(be.length)&&!Wu(be)}function So(be){return wn(be)&&vl(be)}var us=Ke||Ku;function Wu(be){if(!Ht(be))return!1;var _e=ge(be);return _e==m||_e==g||_e==u||_e==C}function Xe(be){return typeof be=="number"&&be>-1&&be%1==0&&be<=i}function Ht(be){var _e=typeof be;return be!=null&&(_e=="object"||_e=="function")}function wn(be){return be!=null&&typeof be=="object"}function nn(be){if(!wn(be)||ge(be)!=w)return!1;var _e=Ee(be);if(_e===null)return!0;var qe=ie.call(_e,"constructor")&&_e.constructor;return typeof qe=="function"&&qe instanceof qe&&ce.call(qe)==ae}var Gt=K?oe(K):Ye;function or(be){return Xn(be,An(be))}function An(be){return vl(be)?De(be):bt(be)}var Dr=Go(function(be,_e,qe){St(be,_e,qe)});function Nr(be){return function(){return be}}function co(be){return be}function Ku(){return!1}e.exports=Dr})(sN,sN.exports);var lye=sN.exports;const Jl=dt.getDefaultExportFromCjs(lye),cye={theme:"system",setTheme:()=>null},sY=v.createContext(cye);function iN(e,t="system"){return uye(e)?e:t}function uye(e){return e==="light"||e==="dark"||e==="system"}const oO=()=>{const e=v.useContext(sY);if(e===void 0)throw new Error("useTheme must be used within a ThemeProvider");return e},iY=(e,t)=>{const n={};if(e===null||t===null)return t;const r=new Set([...Object.keys(e),...Object.keys(t)]);for(const o of r){if(!(o in e)&&o in t){n[o]=t[o];continue}if(o in e&&!(o in t)){n[o]=void 0;continue}const s=e[o],i=t[o];if(!H2(s,i))if(Array.isArray(s)&&Array.isArray(i))n[o]=i;else if(lB(s)&&lB(i)){const a=iY(s,i);Object.keys(a).length>0&&(n[o]=a)}else n[o]=i}return n},H2=(e,t)=>{if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((o,s)=>H2(o,t[s]));const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(o=>H2(e[o],t[o]))}return!1},lB=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ks=e=>{if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(e);if(e instanceof RegExp)return new RegExp(e);if(Array.isArray(e))return e.map(n=>Ks(n));const t={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=Ks(e[n]));return t},aY="__semaphorAuthoredFontFamily";var VG,HG;const dye=(HG=(VG=dt.DEFAULT_STYLE.default.chart)==null?void 0:VG.font)==null?void 0:HG.family,fye=new Set([dye,"Open Sans, Arial, sans-serif",'"Open Sans", Arial, sans-serif'].filter(Boolean));function hye(e,t){if(!e)return t?{family:t}:void 0;const{[aY]:n,...r}=e,o=mye(r.family,t,!!n);return{...r,...o?{family:o}:void 0}}function mye(e,t,n=!1){return n&&e||e&&!pye(e)?e:t||e}function pye(e){return fye.has(e.trim())}function gye(e,t){if(!t)return e;const n={...e,font:sa(e.font,t)},r=yye(e.plugins,t);r&&(n.plugins=r);const o=vye(e.scales,t);return o&&(n.scales=o),n}function bye(e,t){return!e||!t?e:e.map(n=>{if(!n||typeof n!="object")return n;const r=n,o=r.datalabels;return!o||typeof o!="object"?n:{...r,datalabels:{...o,font:sa(o.font,t)}}})}function xye(e,t){if(!e||typeof e!="object"||!t)return e;const n=e.datasets;return Array.isArray(n)?{...e,datasets:bye(n,t)}:e}function yye(e,t){var n;return e&&{...e,title:e.title?{...e.title,font:sa(e.title.font,t)}:e.title,subtitle:e.subtitle?{...e.subtitle,font:sa(e.subtitle.font,t)}:e.subtitle,legend:e.legend?{...e.legend,labels:e.legend.labels?{...e.legend.labels,font:sa(e.legend.labels.font,t)}:e.legend.labels}:e.legend,tooltip:e.tooltip?{...e.tooltip,titleFont:sa(e.tooltip.titleFont,t),bodyFont:sa(e.tooltip.bodyFont,t),footerFont:sa(e.tooltip.footerFont,t)}:e.tooltip,datalabels:e.datalabels?{...e.datalabels,font:sa((n=e.datalabels)==null?void 0:n.font,t)}:e.datalabels}}function vye(e,t){return e&&Object.entries(e).reduce((n,[r,o])=>{if(!o||typeof o!="object")return n[r]=o,n;const s=o;return n[r]={...s,ticks:s.ticks?{...s.ticks,font:sa(s.ticks.font,t)}:s.ticks,title:s.title?{...s.title,font:sa(s.title.font,t)}:s.title,pointLabels:s.pointLabels?{...s.pointLabels,font:sa(s.pointLabels.font,t)}:s.pointLabels},n},{})}function sa(e,t){return typeof e=="function"?e:{...t,...e&&typeof e=="object"?e:{}}}function wye(e,t){const n=Ks(e??{}),r=Cye(t);if(!r)return n;const o=Jl(n,r);return jye(o,r),o}function Cye(e){var h,m,g,b;const t=(h=e.scheme.components)==null?void 0:h.chart,n=cf.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes[e.mode],r=(m=n.components)==null?void 0:m.chart,o=(g=n.tokens)==null?void 0:g.typography,s={};Nye(t==null?void 0:t.palette,r==null?void 0:r.palette)&&(s.dataset={backgroundColor:[...t.palette],borderColor:[...t.palette]});const i=(b=e.scheme.tokens)==null?void 0:b.typography,a=ap(i==null?void 0:i.fontFamily,o==null?void 0:o.fontFamily),c=ap(i==null?void 0:i.baseFontSize,o==null?void 0:o.baseFontSize);if(a||c!==void 0){const x={...a?{family:a}:void 0,...c!==void 0?{size:c}:void 0};a&&(x[aY]=!0),s.font=x}const u=ap(t==null?void 0:t.gridColor,r==null?void 0:r.gridColor),d=ap(t==null?void 0:t.axisColor,r==null?void 0:r.axisColor)??ap(t==null?void 0:t.foreground,r==null?void 0:r.foreground);(u||d)&&(s.options={scales:{x:BT({gridColor:u,axisColor:d}),y:BT({gridColor:u,axisColor:d}),y2:BT({gridColor:u,axisColor:d}),r:Sye({gridColor:u,axisColor:d})}});const f=ap(t==null?void 0:t.foreground,r==null?void 0:r.foreground);return f&&(s.options=Jl(s.options??{},{plugins:{legend:{labels:{color:f}}}})),Object.keys(s).length>0?{chart:s}:void 0}function BT({gridColor:e,axisColor:t}){return{...e?{grid:{color:e}}:void 0,...t?{ticks:{color:t},title:{color:t}}:void 0}}function Sye({gridColor:e,axisColor:t}){return{...e?{grid:{color:e},angleLines:{color:e}}:void 0,...t?{ticks:{color:t},title:{color:t},pointLabels:{color:t}}:void 0}}function Nye(e,t){return e!=null&&e.length?!(t!=null&&t.length)||e.length!==t.length?!0:e.some((n,r)=>n!==t[r]):!1}function ap(e,t){return e!==void 0&&e!==t?e:void 0}function jye(e,t){var r;const n=(r=t.chart)==null?void 0:r.dataset;n&&(e.chart=e.chart??{},e.chart.dataset=e.chart.dataset??{},Array.isArray(n.backgroundColor)&&(e.chart.dataset.backgroundColor=[...n.backgroundColor]),Array.isArray(n.borderColor)&&(e.chart.dataset.borderColor=[...n.borderColor]))}var Em=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},kye={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Rl,wh,qG,_ye=(qG=class{constructor(){At(this,Rl,kye);At(this,wh,!1)}setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&ve(this,wh)&&e!==ve(this,Rl)&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:ve(this,Rl),provider:e}),yt(this,Rl,e),process.env.NODE_ENV!=="production"&&yt(this,wh,!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&yt(this,wh,!0),ve(this,Rl).setTimeout(e,t)}clearTimeout(e){ve(this,Rl).clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&yt(this,wh,!0),ve(this,Rl).setInterval(e,t)}clearInterval(e){ve(this,Rl).clearInterval(e)}},Rl=new WeakMap,wh=new WeakMap,qG),lh=new _ye;function Iye(e){setTimeout(e,0)}var Zh=typeof window>"u"||"Deno"in globalThis;function gs(){}function Tye(e,t){return typeof e=="function"?e(t):e}function q2(e){return typeof e=="number"&&e>=0&&e!==1/0}function lY(e,t){return Math.max(e+(t||0)-Date.now(),0)}function _d(e,t){return typeof e=="function"?e(t):e}function ia(e,t){return typeof e=="function"?e(t):e}function cB(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:s,queryKey:i,stale:a}=e;if(i){if(r){if(t.queryHash!==sO(i,t.options))return!1}else if(!f0(t.queryKey,i))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||o&&o!==t.state.fetchStatus||s&&!s(t))}function uB(e,t){const{exact:n,status:r,predicate:o,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(Xh(t.options.mutationKey)!==Xh(s))return!1}else if(!f0(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function sO(e,t){return((t==null?void 0:t.queryKeyHashFn)||Xh)(e)}function Xh(e){return JSON.stringify(e,(t,n)=>U2(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function f0(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>f0(e[n],t[n])):!1}var Eye=Object.prototype.hasOwnProperty;function aN(e,t){if(e===t)return e;const n=dB(e)&&dB(t);if(!n&&!(U2(e)&&U2(t)))return t;const o=(n?e:Object.keys(e)).length,s=n?t:Object.keys(t),i=s.length,a=n?new Array(i):{};let c=0;for(let u=0;u<i;u++){const d=n?u:s[u],f=e[d],h=t[d];if(f===h){a[d]=f,(n?u<o:Eye.call(e,d))&&c++;continue}if(f===null||h===null||typeof f!="object"||typeof h!="object"){a[d]=h;continue}const m=aN(f,h);a[d]=m,m===f&&c++}return o===i&&c===o?e:a}function h0(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function dB(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function U2(e){if(!fB(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!fB(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function fB(e){return Object.prototype.toString.call(e)==="[object Object]"}function Dye(e){return new Promise(t=>{lh.setTimeout(t,e)})}function W2(e,t,n){if(typeof n.structuralSharing=="function")return n.structuralSharing(e,t);if(n.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return aN(e,t)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${n.queryHash}]: ${r}`),r}return aN(e,t)}return t}function Mye(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function Rye(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var lN=Symbol();function cY(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===lN&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===lN?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function uY(e,t){return typeof e=="function"?e(...t):!!e}var Ch,id,hg,UG,Aye=(UG=class extends Em{constructor(){super();At(this,Ch);At(this,id);At(this,hg);yt(this,hg,t=>{if(!Zh&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ve(this,id)||this.setEventListener(ve(this,hg))}onUnsubscribe(){var t;this.hasListeners()||((t=ve(this,id))==null||t.call(this),yt(this,id,void 0))}setEventListener(t){var n;yt(this,hg,t),(n=ve(this,id))==null||n.call(this),yt(this,id,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){ve(this,Ch)!==t&&(yt(this,Ch,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof ve(this,Ch)=="boolean"?ve(this,Ch):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},Ch=new WeakMap,id=new WeakMap,hg=new WeakMap,UG),iO=new Aye;function K2(){let e,t;const n=new Promise((o,s)=>{e=o,t=s});n.status="pending",n.catch(()=>{});function r(o){Object.assign(n,o),delete n.resolve,delete n.reject}return n.resolve=o=>{r({status:"fulfilled",value:o}),e(o)},n.reject=o=>{r({status:"rejected",reason:o}),t(o)},n}var Pye=Iye;function Fye(){let e=[],t=0,n=a=>{a()},r=a=>{a()},o=Pye;const s=a=>{t?e.push(a):o(()=>{n(a)})},i=()=>{const a=e;e=[],a.length&&o(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||i()}return c},batchCalls:a=>(...c)=>{s(()=>{a(...c)})},schedule:s,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{o=a}}}var Ur=Fye(),mg,ad,pg,WG,Oye=(WG=class extends Em{constructor(){super();At(this,mg,!0);At(this,ad);At(this,pg);yt(this,pg,t=>{if(!Zh&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){ve(this,ad)||this.setEventListener(ve(this,pg))}onUnsubscribe(){var t;this.hasListeners()||((t=ve(this,ad))==null||t.call(this),yt(this,ad,void 0))}setEventListener(t){var n;yt(this,pg,t),(n=ve(this,ad))==null||n.call(this),yt(this,ad,t(this.setOnline.bind(this)))}setOnline(t){ve(this,mg)!==t&&(yt(this,mg,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return ve(this,mg)}},mg=new WeakMap,ad=new WeakMap,pg=new WeakMap,WG),cN=new Oye;function Lye(e){return Math.min(1e3*2**e,3e4)}function dY(e){return(e??"online")==="online"?cN.isOnline():!0}var G2=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function fY(e){let t=!1,n=0,r;const o=K2(),s=()=>o.status!=="pending",i=b=>{var x;if(!s()){const y=new G2(b);h(y),(x=e.onCancel)==null||x.call(e,y)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>iO.isFocused()&&(e.networkMode==="always"||cN.isOnline())&&e.canRun(),d=()=>dY(e.networkMode)&&e.canRun(),f=b=>{s()||(r==null||r(),o.resolve(b))},h=b=>{s()||(r==null||r(),o.reject(b))},m=()=>new Promise(b=>{var x;r=y=>{(s()||u())&&b(y)},(x=e.onPause)==null||x.call(e)}).then(()=>{var b;r=void 0,s()||(b=e.onContinue)==null||b.call(e)}),g=()=>{if(s())return;let b;const x=n===0?e.initialPromise:void 0;try{b=x??e.fn()}catch(y){b=Promise.reject(y)}Promise.resolve(b).then(f).catch(y=>{var j;if(s())return;const w=e.retry??(Zh?0:3),C=e.retryDelay??Lye,N=typeof C=="function"?C(n,y):C,S=w===!0||typeof w=="number"&&n<w||typeof w=="function"&&w(n,y);if(t||!S){h(y);return}n++,(j=e.onFail)==null||j.call(e,n,y),Dye(N).then(()=>u()?void 0:m()).then(()=>{t?h(y):g()})})};return{promise:o,status:()=>o.status,cancel:i,continue:()=>(r==null||r(),o),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?g():m().then(g),o)}}var Sh,KG,hY=(KG=class{constructor(){At(this,Sh)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),q2(this.gcTime)&&yt(this,Sh,lh.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Zh?1/0:5*60*1e3))}clearGcTimeout(){ve(this,Sh)&&(lh.clearTimeout(ve(this,Sh)),yt(this,Sh,void 0))}},Sh=new WeakMap,KG),Nh,gg,ra,jh,Ao,kv,kh,Oa,kc,GG,$ye=(GG=class extends hY{constructor(t){super();At(this,Oa);At(this,Nh);At(this,gg);At(this,ra);At(this,jh);At(this,Ao);At(this,kv);At(this,kh);yt(this,kh,!1),yt(this,kv,t.defaultOptions),this.setOptions(t.options),this.observers=[],yt(this,jh,t.client),yt(this,ra,ve(this,jh).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,yt(this,Nh,mB(this.options)),this.state=t.state??ve(this,Nh),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=ve(this,Ao))==null?void 0:t.promise}setOptions(t){if(this.options={...ve(this,kv),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=mB(this.options);n.data!==void 0&&(this.setState(hB(n.data,n.dataUpdatedAt)),yt(this,Nh,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ve(this,ra).remove(this)}setData(t,n){const r=W2(this.state.data,t,this.options);return Qt(this,Oa,kc).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Qt(this,Oa,kc).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,o;const n=(r=ve(this,Ao))==null?void 0:r.promise;return(o=ve(this,Ao))==null||o.cancel(t),n?n.then(gs).catch(gs):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(ve(this,Nh))}isActive(){return this.observers.some(t=>ia(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===lN||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>_d(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!lY(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=ve(this,Ao))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=ve(this,Ao))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),ve(this,ra).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(ve(this,Ao)&&(ve(this,kh)?ve(this,Ao).cancel({revert:!0}):ve(this,Ao).cancelRetry()),this.scheduleGc()),ve(this,ra).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Qt(this,Oa,kc).call(this,{type:"invalidate"})}async fetch(t,n){var c,u,d,f,h,m,g,b,x,y,w,C;if(this.state.fetchStatus!=="idle"&&((c=ve(this,Ao))==null?void 0:c.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(ve(this,Ao))return ve(this,Ao).continueRetry(),ve(this,Ao).promise}if(t&&this.setOptions(t),!this.options.queryFn){const N=this.observers.find(S=>S.options.queryFn);N&&this.setOptions(N.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const r=new AbortController,o=N=>{Object.defineProperty(N,"signal",{enumerable:!0,get:()=>(yt(this,kh,!0),r.signal)})},s=()=>{const N=cY(this.options,n),j=(()=>{const _={client:ve(this,jh),queryKey:this.queryKey,meta:this.meta};return o(_),_})();return yt(this,kh,!1),this.options.persister?this.options.persister(N,j,this):N(j)},a=(()=>{const N={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:ve(this,jh),state:this.state,fetchFn:s};return o(N),N})();(u=this.options.behavior)==null||u.onFetch(a,this),yt(this,gg,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((d=a.fetchOptions)==null?void 0:d.meta))&&Qt(this,Oa,kc).call(this,{type:"fetch",meta:(f=a.fetchOptions)==null?void 0:f.meta}),yt(this,Ao,fY({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,onCancel:N=>{N instanceof G2&&N.revert&&this.setState({...ve(this,gg),fetchStatus:"idle"}),r.abort()},onFail:(N,S)=>{Qt(this,Oa,kc).call(this,{type:"failed",failureCount:N,error:S})},onPause:()=>{Qt(this,Oa,kc).call(this,{type:"pause"})},onContinue:()=>{Qt(this,Oa,kc).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{const N=await ve(this,Ao).start();if(N===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(N),(m=(h=ve(this,ra).config).onSuccess)==null||m.call(h,N,this),(b=(g=ve(this,ra).config).onSettled)==null||b.call(g,N,this.state.error,this),N}catch(N){if(N instanceof G2){if(N.silent)return ve(this,Ao).promise;if(N.revert){if(this.state.data===void 0)throw N;return this.state.data}}throw Qt(this,Oa,kc).call(this,{type:"error",error:N}),(y=(x=ve(this,ra).config).onError)==null||y.call(x,N,this),(C=(w=ve(this,ra).config).onSettled)==null||C.call(w,this.state.data,N,this),N}finally{this.scheduleGc()}}},Nh=new WeakMap,gg=new WeakMap,ra=new WeakMap,jh=new WeakMap,Ao=new WeakMap,kv=new WeakMap,kh=new WeakMap,Oa=new WeakSet,kc=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...mY(r.data,this.options),fetchMeta:t.meta??null};case"success":const o={...r,...hB(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return yt(this,gg,t.manual?o:void 0),o;case"error":const s=t.error;return{...r,error:s,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),Ur.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),ve(this,ra).notify({query:this,type:"updated",action:t})})},GG);function mY(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:dY(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function hB(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function mB(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var di,Pn,_v,Hs,_h,bg,Pc,ld,Iv,xg,yg,Ih,Th,cd,vg,rr,Qx,Y2,Z2,X2,Q2,J2,eR,tR,pY,YG,aO=(YG=class extends Em{constructor(t,n){super();At(this,rr);At(this,di);At(this,Pn);At(this,_v);At(this,Hs);At(this,_h);At(this,bg);At(this,Pc);At(this,ld);At(this,Iv);At(this,xg);At(this,yg);At(this,Ih);At(this,Th);At(this,cd);At(this,vg,new Set);this.options=n,yt(this,di,t),yt(this,ld,null),yt(this,Pc,K2()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(ve(this,Pn).addObserver(this),pB(ve(this,Pn),this.options)?Qt(this,rr,Qx).call(this):this.updateResult(),Qt(this,rr,Q2).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return nR(ve(this,Pn),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return nR(ve(this,Pn),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Qt(this,rr,J2).call(this),Qt(this,rr,eR).call(this),ve(this,Pn).removeObserver(this)}setOptions(t){const n=this.options,r=ve(this,Pn);if(this.options=ve(this,di).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ia(this.options.enabled,ve(this,Pn))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Qt(this,rr,tR).call(this),ve(this,Pn).setOptions(this.options),n._defaulted&&!h0(this.options,n)&&ve(this,di).getQueryCache().notify({type:"observerOptionsUpdated",query:ve(this,Pn),observer:this});const o=this.hasListeners();o&&gB(ve(this,Pn),r,this.options,n)&&Qt(this,rr,Qx).call(this),this.updateResult(),o&&(ve(this,Pn)!==r||ia(this.options.enabled,ve(this,Pn))!==ia(n.enabled,ve(this,Pn))||_d(this.options.staleTime,ve(this,Pn))!==_d(n.staleTime,ve(this,Pn)))&&Qt(this,rr,Y2).call(this);const s=Qt(this,rr,Z2).call(this);o&&(ve(this,Pn)!==r||ia(this.options.enabled,ve(this,Pn))!==ia(n.enabled,ve(this,Pn))||s!==ve(this,cd))&&Qt(this,rr,X2).call(this,s)}getOptimisticResult(t){const n=ve(this,di).getQueryCache().build(ve(this,di),t),r=this.createResult(n,t);return Bye(this,r)&&(yt(this,Hs,r),yt(this,bg,this.options),yt(this,_h,ve(this,Pn).state)),r}getCurrentResult(){return ve(this,Hs)}trackResult(t,n){return new Proxy(t,{get:(r,o)=>(this.trackProp(o),n==null||n(o),o==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&ve(this,Pc).status==="pending"&&ve(this,Pc).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,o))})}trackProp(t){ve(this,vg).add(t)}getCurrentQuery(){return ve(this,Pn)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=ve(this,di).defaultQueryOptions(t),r=ve(this,di).getQueryCache().build(ve(this,di),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Qt(this,rr,Qx).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),ve(this,Hs)))}createResult(t,n){var T;const r=ve(this,Pn),o=this.options,s=ve(this,Hs),i=ve(this,_h),a=ve(this,bg),u=t!==r?t.state:ve(this,_v),{state:d}=t;let f={...d},h=!1,m;if(n._optimisticResults){const I=this.hasListeners(),E=!I&&pB(t,n),D=I&&gB(t,r,n,o);(E||D)&&(f={...f,...mY(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:g,errorUpdatedAt:b,status:x}=f;m=f.data;let y=!1;if(n.placeholderData!==void 0&&m===void 0&&x==="pending"){let I;s!=null&&s.isPlaceholderData&&n.placeholderData===(a==null?void 0:a.placeholderData)?(I=s.data,y=!0):I=typeof n.placeholderData=="function"?n.placeholderData((T=ve(this,yg))==null?void 0:T.state.data,ve(this,yg)):n.placeholderData,I!==void 0&&(x="success",m=W2(s==null?void 0:s.data,I,n),h=!0)}if(n.select&&m!==void 0&&!y)if(s&&m===(i==null?void 0:i.data)&&n.select===ve(this,Iv))m=ve(this,xg);else try{yt(this,Iv,n.select),m=n.select(m),m=W2(s==null?void 0:s.data,m,n),yt(this,xg,m),yt(this,ld,null)}catch(I){yt(this,ld,I)}ve(this,ld)&&(g=ve(this,ld),m=ve(this,xg),b=Date.now(),x="error");const w=f.fetchStatus==="fetching",C=x==="pending",N=x==="error",S=C&&w,j=m!==void 0,k={status:x,fetchStatus:f.fetchStatus,isPending:C,isSuccess:x==="success",isError:N,isInitialLoading:S,isLoading:S,data:m,dataUpdatedAt:f.dataUpdatedAt,error:g,errorUpdatedAt:b,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:f.dataUpdateCount>0||f.errorUpdateCount>0,isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:w,isRefetching:w&&!C,isLoadingError:N&&!j,isPaused:f.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:N&&j,isStale:lO(t,n),refetch:this.refetch,promise:ve(this,Pc),isEnabled:ia(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const I=R=>{k.status==="error"?R.reject(k.error):k.data!==void 0&&R.resolve(k.data)},E=()=>{const R=yt(this,Pc,k.promise=K2());I(R)},D=ve(this,Pc);switch(D.status){case"pending":t.queryHash===r.queryHash&&I(D);break;case"fulfilled":(k.status==="error"||k.data!==D.value)&&E();break;case"rejected":(k.status!=="error"||k.error!==D.reason)&&E();break}}return k}updateResult(){const t=ve(this,Hs),n=this.createResult(ve(this,Pn),this.options);if(yt(this,_h,ve(this,Pn).state),yt(this,bg,this.options),ve(this,_h).data!==void 0&&yt(this,yg,ve(this,Pn)),h0(n,t))return;yt(this,Hs,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:o}=this.options,s=typeof o=="function"?o():o;if(s==="all"||!s&&!ve(this,vg).size)return!0;const i=new Set(s??ve(this,vg));return this.options.throwOnError&&i.add("error"),Object.keys(ve(this,Hs)).some(a=>{const c=a;return ve(this,Hs)[c]!==t[c]&&i.has(c)})};Qt(this,rr,pY).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Qt(this,rr,Q2).call(this)}},di=new WeakMap,Pn=new WeakMap,_v=new WeakMap,Hs=new WeakMap,_h=new WeakMap,bg=new WeakMap,Pc=new WeakMap,ld=new WeakMap,Iv=new WeakMap,xg=new WeakMap,yg=new WeakMap,Ih=new WeakMap,Th=new WeakMap,cd=new WeakMap,vg=new WeakMap,rr=new WeakSet,Qx=function(t){Qt(this,rr,tR).call(this);let n=ve(this,Pn).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(gs)),n},Y2=function(){Qt(this,rr,J2).call(this);const t=_d(this.options.staleTime,ve(this,Pn));if(Zh||ve(this,Hs).isStale||!q2(t))return;const r=lY(ve(this,Hs).dataUpdatedAt,t)+1;yt(this,Ih,lh.setTimeout(()=>{ve(this,Hs).isStale||this.updateResult()},r))},Z2=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(ve(this,Pn)):this.options.refetchInterval)??!1},X2=function(t){Qt(this,rr,eR).call(this),yt(this,cd,t),!(Zh||ia(this.options.enabled,ve(this,Pn))===!1||!q2(ve(this,cd))||ve(this,cd)===0)&&yt(this,Th,lh.setInterval(()=>{(this.options.refetchIntervalInBackground||iO.isFocused())&&Qt(this,rr,Qx).call(this)},ve(this,cd)))},Q2=function(){Qt(this,rr,Y2).call(this),Qt(this,rr,X2).call(this,Qt(this,rr,Z2).call(this))},J2=function(){ve(this,Ih)&&(lh.clearTimeout(ve(this,Ih)),yt(this,Ih,void 0))},eR=function(){ve(this,Th)&&(lh.clearInterval(ve(this,Th)),yt(this,Th,void 0))},tR=function(){const t=ve(this,di).getQueryCache().build(ve(this,di),this.options);if(t===ve(this,Pn))return;const n=ve(this,Pn);yt(this,Pn,t),yt(this,_v,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},pY=function(t){Ur.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(ve(this,Hs))}),ve(this,di).getQueryCache().notify({query:ve(this,Pn),type:"observerResultsUpdated"})})},YG);function zye(e,t){return ia(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function pB(e,t){return zye(e,t)||e.state.data!==void 0&&nR(e,t,t.refetchOnMount)}function nR(e,t,n){if(ia(t.enabled,e)!==!1&&_d(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&lO(e,t)}return!1}function gB(e,t,n,r){return(e!==t||ia(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&lO(e,n)}function lO(e,t){return ia(t.enabled,e)!==!1&&e.isStaleByTime(_d(t.staleTime,e))}function Bye(e,t){return!h0(e.getCurrentResult(),t)}function bB(e){return{onFetch:(t,n)=>{var d,f,h,m,g;const r=t.options,o=(h=(f=(d=t.fetchOptions)==null?void 0:d.meta)==null?void 0:f.fetchMore)==null?void 0:h.direction,s=((m=t.state.data)==null?void 0:m.pages)||[],i=((g=t.state.data)==null?void 0:g.pageParams)||[];let a={pages:[],pageParams:[]},c=0;const u=async()=>{let b=!1;const x=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?b=!0:t.signal.addEventListener("abort",()=>{b=!0}),t.signal)})},y=cY(t.options,t.fetchOptions),w=async(C,N,S)=>{if(b)return Promise.reject();if(N==null&&C.pages.length)return Promise.resolve(C);const _=(()=>{const E={client:t.client,queryKey:t.queryKey,pageParam:N,direction:S?"backward":"forward",meta:t.options.meta};return x(E),E})(),k=await y(_),{maxPages:T}=t.options,I=S?Rye:Mye;return{pages:I(C.pages,k,T),pageParams:I(C.pageParams,N,T)}};if(o&&s.length){const C=o==="backward",N=C?Vye:xB,S={pages:s,pageParams:i},j=N(r,S);a=await w(S,j,C)}else{const C=e??s.length;do{const N=c===0?i[0]??r.initialPageParam:xB(r,a);if(c>0&&N==null)break;a=await w(a,N),c++}while(c<C)}return a};t.options.persister?t.fetchFn=()=>{var b,x;return(x=(b=t.options).persister)==null?void 0:x.call(b,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function xB(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Vye(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var Tv,Al,qs,Eh,Pl,Ju,ZG,Hye=(ZG=class extends hY{constructor(t){super();At(this,Pl);At(this,Tv);At(this,Al);At(this,qs);At(this,Eh);yt(this,Tv,t.client),this.mutationId=t.mutationId,yt(this,qs,t.mutationCache),yt(this,Al,[]),this.state=t.state||gY(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){ve(this,Al).includes(t)||(ve(this,Al).push(t),this.clearGcTimeout(),ve(this,qs).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){yt(this,Al,ve(this,Al).filter(n=>n!==t)),this.scheduleGc(),ve(this,qs).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){ve(this,Al).length||(this.state.status==="pending"?this.scheduleGc():ve(this,qs).remove(this))}continue(){var t;return((t=ve(this,Eh))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,a,c,u,d,f,h,m,g,b,x,y,w,C,N,S,j,_,k,T;const n=()=>{Qt(this,Pl,Ju).call(this,{type:"continue"})},r={client:ve(this,Tv),meta:this.options.meta,mutationKey:this.options.mutationKey};yt(this,Eh,fY({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(I,E)=>{Qt(this,Pl,Ju).call(this,{type:"failed",failureCount:I,error:E})},onPause:()=>{Qt(this,Pl,Ju).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ve(this,qs).canRun(this)}));const o=this.state.status==="pending",s=!ve(this,Eh).canStart();try{if(o)n();else{Qt(this,Pl,Ju).call(this,{type:"pending",variables:t,isPaused:s}),await((a=(i=ve(this,qs).config).onMutate)==null?void 0:a.call(i,t,this,r));const E=await((u=(c=this.options).onMutate)==null?void 0:u.call(c,t,r));E!==this.state.context&&Qt(this,Pl,Ju).call(this,{type:"pending",context:E,variables:t,isPaused:s})}const I=await ve(this,Eh).start();return await((f=(d=ve(this,qs).config).onSuccess)==null?void 0:f.call(d,I,t,this.state.context,this,r)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,I,t,this.state.context,r)),await((b=(g=ve(this,qs).config).onSettled)==null?void 0:b.call(g,I,null,this.state.variables,this.state.context,this,r)),await((y=(x=this.options).onSettled)==null?void 0:y.call(x,I,null,t,this.state.context,r)),Qt(this,Pl,Ju).call(this,{type:"success",data:I}),I}catch(I){try{throw await((C=(w=ve(this,qs).config).onError)==null?void 0:C.call(w,I,t,this.state.context,this,r)),await((S=(N=this.options).onError)==null?void 0:S.call(N,I,t,this.state.context,r)),await((_=(j=ve(this,qs).config).onSettled)==null?void 0:_.call(j,void 0,I,this.state.variables,this.state.context,this,r)),await((T=(k=this.options).onSettled)==null?void 0:T.call(k,void 0,I,t,this.state.context,r)),I}finally{Qt(this,Pl,Ju).call(this,{type:"error",error:I})}}finally{ve(this,qs).runNext(this)}}},Tv=new WeakMap,Al=new WeakMap,qs=new WeakMap,Eh=new WeakMap,Pl=new WeakSet,Ju=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Ur.batch(()=>{ve(this,Al).forEach(r=>{r.onMutationUpdate(t)}),ve(this,qs).notify({mutation:this,type:"updated",action:t})})},ZG);function gY(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Fc,La,Ev,XG,qye=(XG=class extends Em{constructor(t={}){super();At(this,Fc);At(this,La);At(this,Ev);this.config=t,yt(this,Fc,new Set),yt(this,La,new Map),yt(this,Ev,0)}build(t,n,r){const o=new Hye({client:t,mutationCache:this,mutationId:++hC(this,Ev)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){ve(this,Fc).add(t);const n=pC(t);if(typeof n=="string"){const r=ve(this,La).get(n);r?r.push(t):ve(this,La).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(ve(this,Fc).delete(t)){const n=pC(t);if(typeof n=="string"){const r=ve(this,La).get(n);if(r)if(r.length>1){const o=r.indexOf(t);o!==-1&&r.splice(o,1)}else r[0]===t&&ve(this,La).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=pC(t);if(typeof n=="string"){const r=ve(this,La).get(n),o=r==null?void 0:r.find(s=>s.state.status==="pending");return!o||o===t}else return!0}runNext(t){var r;const n=pC(t);if(typeof n=="string"){const o=(r=ve(this,La).get(n))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(o==null?void 0:o.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Ur.batch(()=>{ve(this,Fc).forEach(t=>{this.notify({type:"removed",mutation:t})}),ve(this,Fc).clear(),ve(this,La).clear()})}getAll(){return Array.from(ve(this,Fc))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>uB(n,r))}findAll(t={}){return this.getAll().filter(n=>uB(t,n))}notify(t){Ur.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Ur.batch(()=>Promise.all(t.map(n=>n.continue().catch(gs))))}},Fc=new WeakMap,La=new WeakMap,Ev=new WeakMap,XG);function pC(e){var t;return(t=e.options.scope)==null?void 0:t.id}var Oc,ud,fi,Lc,hu,d1,rR,QG,Uye=(QG=class extends Em{constructor(n,r){super();At(this,hu);At(this,Oc);At(this,ud);At(this,fi);At(this,Lc);yt(this,Oc,n),this.setOptions(r),this.bindMethods(),Qt(this,hu,d1).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var o;const r=this.options;this.options=ve(this,Oc).defaultMutationOptions(n),h0(this.options,r)||ve(this,Oc).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ve(this,fi),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&Xh(r.mutationKey)!==Xh(this.options.mutationKey)?this.reset():((o=ve(this,fi))==null?void 0:o.state.status)==="pending"&&ve(this,fi).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=ve(this,fi))==null||n.removeObserver(this)}onMutationUpdate(n){Qt(this,hu,d1).call(this),Qt(this,hu,rR).call(this,n)}getCurrentResult(){return ve(this,ud)}reset(){var n;(n=ve(this,fi))==null||n.removeObserver(this),yt(this,fi,void 0),Qt(this,hu,d1).call(this),Qt(this,hu,rR).call(this)}mutate(n,r){var o;return yt(this,Lc,r),(o=ve(this,fi))==null||o.removeObserver(this),yt(this,fi,ve(this,Oc).getMutationCache().build(ve(this,Oc),this.options)),ve(this,fi).addObserver(this),ve(this,fi).execute(n)}},Oc=new WeakMap,ud=new WeakMap,fi=new WeakMap,Lc=new WeakMap,hu=new WeakSet,d1=function(){var r;const n=((r=ve(this,fi))==null?void 0:r.state)??gY();yt(this,ud,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},rR=function(n){Ur.batch(()=>{var r,o,s,i,a,c,u,d;if(ve(this,Lc)&&this.hasListeners()){const f=ve(this,ud).variables,h=ve(this,ud).context,m={client:ve(this,Oc),meta:this.options.meta,mutationKey:this.options.mutationKey};(n==null?void 0:n.type)==="success"?((o=(r=ve(this,Lc)).onSuccess)==null||o.call(r,n.data,f,h,m),(i=(s=ve(this,Lc)).onSettled)==null||i.call(s,n.data,null,f,h,m)):(n==null?void 0:n.type)==="error"&&((c=(a=ve(this,Lc)).onError)==null||c.call(a,n.error,f,h,m),(d=(u=ve(this,Lc)).onSettled)==null||d.call(u,void 0,n.error,f,h,m))}this.listeners.forEach(f=>{f(ve(this,ud))})})},QG);function yB(e,t){const n=new Set(t);return e.filter(r=>!n.has(r))}function Wye(e,t,n){const r=e.slice(0);return r[t]=n,r}var Dh,Mi,wg,Cg,oa,dd,Dv,Mv,Rv,cs,oR,sR,iR,aR,lR,JG,Kye=(JG=class extends Em{constructor(t,n,r){super();At(this,cs);At(this,Dh);At(this,Mi);At(this,wg);At(this,Cg);At(this,oa);At(this,dd);At(this,Dv);At(this,Mv);At(this,Rv,[]);yt(this,Dh,t),yt(this,Cg,r),yt(this,wg,[]),yt(this,oa,[]),yt(this,Mi,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&ve(this,oa).forEach(t=>{t.subscribe(n=>{Qt(this,cs,aR).call(this,t,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,ve(this,oa).forEach(t=>{t.destroy()})}setQueries(t,n){if(yt(this,wg,t),yt(this,Cg,n),process.env.NODE_ENV!=="production"){const r=t.map(o=>ve(this,Dh).defaultQueryOptions(o).queryHash);new Set(r).size!==r.length&&console.warn("[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.")}Ur.batch(()=>{const r=ve(this,oa),o=Qt(this,cs,iR).call(this,ve(this,wg));yt(this,Rv,o),o.forEach(f=>f.observer.setOptions(f.defaultedQueryOptions));const s=o.map(f=>f.observer),i=s.map(f=>f.getCurrentResult()),a=r.length!==s.length,c=s.some((f,h)=>f!==r[h]),u=a||c,d=u?!0:i.some((f,h)=>{const m=ve(this,Mi)[h];return!m||!h0(f,m)});!u&&!d||(u&&yt(this,oa,s),yt(this,Mi,i),this.hasListeners()&&(u&&(yB(r,s).forEach(f=>{f.destroy()}),yB(s,r).forEach(f=>{f.subscribe(h=>{Qt(this,cs,aR).call(this,f,h)})})),Qt(this,cs,lR).call(this)))})}getCurrentResult(){return ve(this,Mi)}getQueries(){return ve(this,oa).map(t=>t.getCurrentQuery())}getObservers(){return ve(this,oa)}getOptimisticResult(t,n){const r=Qt(this,cs,iR).call(this,t),o=r.map(s=>s.observer.getOptimisticResult(s.defaultedQueryOptions));return[o,s=>Qt(this,cs,sR).call(this,s??o,n),()=>Qt(this,cs,oR).call(this,o,r)]}},Dh=new WeakMap,Mi=new WeakMap,wg=new WeakMap,Cg=new WeakMap,oa=new WeakMap,dd=new WeakMap,Dv=new WeakMap,Mv=new WeakMap,Rv=new WeakMap,cs=new WeakSet,oR=function(t,n){return n.map((r,o)=>{const s=t[o];return r.defaultedQueryOptions.notifyOnChangeProps?s:r.observer.trackResult(s,i=>{n.forEach(a=>{a.observer.trackProp(i)})})})},sR=function(t,n){return n?((!ve(this,dd)||ve(this,Mi)!==ve(this,Mv)||n!==ve(this,Dv))&&(yt(this,Dv,n),yt(this,Mv,ve(this,Mi)),yt(this,dd,aN(ve(this,dd),n(t)))),ve(this,dd)):t},iR=function(t){const n=new Map;ve(this,oa).forEach(o=>{const s=o.options.queryHash;if(!s)return;const i=n.get(s);i?i.push(o):n.set(s,[o])});const r=[];return t.forEach(o=>{var c;const s=ve(this,Dh).defaultQueryOptions(o),a=((c=n.get(s.queryHash))==null?void 0:c.shift())??new aO(ve(this,Dh),s);r.push({defaultedQueryOptions:s,observer:a})}),r},aR=function(t,n){const r=ve(this,oa).indexOf(t);r!==-1&&(yt(this,Mi,Wye(ve(this,Mi),r,n)),Qt(this,cs,lR).call(this))},lR=function(){var t;if(this.hasListeners()){const n=ve(this,dd),r=Qt(this,cs,oR).call(this,ve(this,Mi),ve(this,Rv)),o=Qt(this,cs,sR).call(this,r,(t=ve(this,Cg))==null?void 0:t.combine);n!==o&&Ur.batch(()=>{this.listeners.forEach(s=>{s(ve(this,Mi))})})}},JG),Fl,eY,bY=(eY=class extends Em{constructor(t={}){super();At(this,Fl);this.config=t,yt(this,Fl,new Map)}build(t,n,r){const o=n.queryKey,s=n.queryHash??sO(o,n);let i=this.get(s);return i||(i=new $ye({client:t,queryKey:o,queryHash:s,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(i)),i}add(t){ve(this,Fl).has(t.queryHash)||(ve(this,Fl).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=ve(this,Fl).get(t.queryHash);n&&(t.destroy(),n===t&&ve(this,Fl).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Ur.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return ve(this,Fl).get(t)}getAll(){return[...ve(this,Fl).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>cB(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>cB(t,r)):n}notify(t){Ur.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Ur.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Ur.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Fl=new WeakMap,eY),Zr,fd,hd,Sg,Ng,md,jg,kg,tY,Gye=(tY=class{constructor(e={}){At(this,Zr);At(this,fd);At(this,hd);At(this,Sg);At(this,Ng);At(this,md);At(this,jg);At(this,kg);yt(this,Zr,e.queryCache||new bY),yt(this,fd,e.mutationCache||new qye),yt(this,hd,e.defaultOptions||{}),yt(this,Sg,new Map),yt(this,Ng,new Map),yt(this,md,0)}mount(){hC(this,md)._++,ve(this,md)===1&&(yt(this,jg,iO.subscribe(async e=>{e&&(await this.resumePausedMutations(),ve(this,Zr).onFocus())})),yt(this,kg,cN.subscribe(async e=>{e&&(await this.resumePausedMutations(),ve(this,Zr).onOnline())})))}unmount(){var e,t;hC(this,md)._--,ve(this,md)===0&&((e=ve(this,jg))==null||e.call(this),yt(this,jg,void 0),(t=ve(this,kg))==null||t.call(this),yt(this,kg,void 0))}isFetching(e){return ve(this,Zr).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return ve(this,fd).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=ve(this,Zr).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=ve(this,Zr).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(_d(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return ve(this,Zr).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),o=ve(this,Zr).get(r.queryHash),s=o==null?void 0:o.state.data,i=Tye(t,s);if(i!==void 0)return ve(this,Zr).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return Ur.batch(()=>ve(this,Zr).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=ve(this,Zr).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=ve(this,Zr);Ur.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=ve(this,Zr);return Ur.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=Ur.batch(()=>ve(this,Zr).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(gs).catch(gs)}invalidateQueries(e,t={}){return Ur.batch(()=>(ve(this,Zr).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Ur.batch(()=>ve(this,Zr).findAll(e).filter(o=>!o.isDisabled()&&!o.isStatic()).map(o=>{let s=o.fetch(void 0,n);return n.throwOnError||(s=s.catch(gs)),o.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(gs)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=ve(this,Zr).build(this,t);return n.isStaleByTime(_d(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(gs).catch(gs)}fetchInfiniteQuery(e){return e.behavior=bB(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(gs).catch(gs)}ensureInfiniteQueryData(e){return e.behavior=bB(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return cN.isOnline()?ve(this,fd).resumePausedMutations():Promise.resolve()}getQueryCache(){return ve(this,Zr)}getMutationCache(){return ve(this,fd)}getDefaultOptions(){return ve(this,hd)}setDefaultOptions(e){yt(this,hd,e)}setQueryDefaults(e,t){ve(this,Sg).set(Xh(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...ve(this,Sg).values()],n={};return t.forEach(r=>{f0(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){ve(this,Ng).set(Xh(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...ve(this,Ng).values()],n={};return t.forEach(r=>{f0(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...ve(this,hd).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=sO(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===lN&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...ve(this,hd).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){ve(this,Zr).clear(),ve(this,fd).clear()}},Zr=new WeakMap,fd=new WeakMap,hd=new WeakMap,Sg=new WeakMap,Ng=new WeakMap,md=new WeakMap,jg=new WeakMap,kg=new WeakMap,tY),cO=te.createContext(void 0),Wr=e=>{const t=te.useContext(cO);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Yye=({client:e,children:t})=>(te.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),l.jsx(cO.Provider,{value:e,children:t})),xY=te.createContext(!1),yY=()=>te.useContext(xY);xY.Provider;function Zye(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xye=te.createContext(Zye()),vY=()=>te.useContext(Xye),wY=(e,t)=>{(e.suspense||e.throwOnError||e.experimental_prefetchInRender)&&(t.isReset()||(e.retryOnMount=!1))},CY=e=>{te.useEffect(()=>{e.clearReset()},[e])},SY=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:o})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(o&&e.data===void 0||uY(n,[e.error,r])),NY=e=>{if(e.suspense){const n=o=>o==="static"?o:Math.max(o??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...o)=>n(r(...o)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},jY=(e,t)=>e.isLoading&&e.isFetching&&!t,cR=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,uN=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function ib({queries:e,...t},n){const r=Wr(),o=yY(),s=vY(),i=te.useMemo(()=>e.map(b=>{const x=r.defaultQueryOptions(b);return x._optimisticResults=o?"isRestoring":"optimistic",x}),[e,r,o]);i.forEach(b=>{NY(b),wY(b,s)}),CY(s);const[a]=te.useState(()=>new Kye(r,i,t)),[c,u,d]=a.getOptimisticResult(i,t.combine),f=!o&&t.subscribed!==!1;te.useSyncExternalStore(te.useCallback(b=>f?a.subscribe(Ur.batchCalls(b)):gs,[a,f]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),te.useEffect(()=>{a.setQueries(i,t)},[i,t,a]);const m=c.some((b,x)=>cR(i[x],b))?c.flatMap((b,x)=>{const y=i[x];if(y){const w=new aO(r,y);if(cR(y,b))return uN(y,w,s);jY(b,o)&&uN(y,w,s)}return[]}):[];if(m.length>0)throw Promise.all(m);const g=c.find((b,x)=>{const y=i[x];return y&&SY({result:b,errorResetBoundary:s,throwOnError:y.throwOnError,query:r.getQueryCache().get(y.queryHash),suspense:y.suspense})});if(g!=null&&g.error)throw g.error;return u(d())}function Qye(e,t,n){var f,h,m,g,b;if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=yY(),o=vY(),s=Wr(),i=s.defaultQueryOptions(e);(h=(f=s.getDefaultOptions().queries)==null?void 0:f._experimental_beforeQuery)==null||h.call(f,i),process.env.NODE_ENV!=="production"&&(i.queryFn||console.error(`[${i.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),i._optimisticResults=r?"isRestoring":"optimistic",NY(i),wY(i,o),CY(o);const a=!s.getQueryCache().get(i.queryHash),[c]=te.useState(()=>new t(s,i)),u=c.getOptimisticResult(i),d=!r&&e.subscribed!==!1;if(te.useSyncExternalStore(te.useCallback(x=>{const y=d?c.subscribe(Ur.batchCalls(x)):gs;return c.updateResult(),y},[c,d]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),te.useEffect(()=>{c.setOptions(i)},[i,c]),cR(i,u))throw uN(i,c,o);if(SY({result:u,errorResetBoundary:o,throwOnError:i.throwOnError,query:s.getQueryCache().get(i.queryHash),suspense:i.suspense}))throw u.error;if((g=(m=s.getDefaultOptions().queries)==null?void 0:m._experimental_afterQuery)==null||g.call(m,i,u),i.experimental_prefetchInRender&&!Zh&&jY(u,r)){const x=a?uN(i,c,o):(b=s.getQueryCache().get(i.queryHash))==null?void 0:b.promise;x==null||x.catch(gs).finally(()=>{c.updateResult()})}return i.notifyOnChangeProps?u:c.trackResult(u)}function Un(e,t){return Qye(e,aO)}function Jye(e,t){const n=Wr(),r=n.getQueryCache();return te.useSyncExternalStore(te.useCallback(o=>r.subscribe(Ur.batchCalls(o)),[r]),()=>n.isFetching(e),()=>n.isFetching(e))}function ks(e,t){const n=Wr(),[r]=te.useState(()=>new Uye(n,e));te.useEffect(()=>{r.setOptions(e)},[r,e]);const o=te.useSyncExternalStore(te.useCallback(i=>r.subscribe(Ur.batchCalls(i)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),s=te.useCallback((i,a)=>{r.mutate(i,a).catch(gs)},[r]);if(o.error&&uY(r.options.throwOnError,[o.error]))throw o.error;return{...o,mutate:s,mutateAsync:o.mutate}}function e0e(){const e=v.useContext(cO);if(e&&e.isSemaphorClient)return e}function kY({children:e}){const{setIsSessionExpired:t}=p.useDashboardActions(),n=e0e(),[r]=v.useState(()=>{const o=new Gye({queryCache:new bY({onError:s=>{s instanceof Error?(console.error(`Something went wrong: ${s.message}`),s.message==="invalid token"&&t(!0)):console.error("Something went wrong:",s)}}),defaultOptions:{queries:{gcTime:36e5,staleTime:3e5,refetchOnWindowFocus:!1,retry:!1}}});return o.isSemaphorClient=!0,o});return n?l.jsx(l.Fragment,{children:e}):l.jsx(Yye,{client:r,children:e})}const t0e={id:"",authToken:void 0,tokenProps:{}},Av=v.createContext(t0e),uO=({children:e,dashboardProps:t})=>{const n=v.useMemo(()=>{let r={};const o=t.authToken;return o&&(r=je.jwtDecode(o.accessToken)),{...t,tokenProps:r}},[t]);return l.jsx(kY,{children:l.jsx(Av.Provider,{value:n,children:e})})};function It(){const e=v.useContext(Av);if(e===void 0)throw new Error("useApplicationContext must be used within a ApplicationContextProvider");return e}const _s=p.create()(p.immer(e=>({initialDashboard:null,selectedDashboard:null,selectedVisual:null,lastSelectedDashboard:null,lastSelectedVisual:null,showHub:!1,actions:{setInitialDashboard:t=>{e(n=>{n.initialDashboard=t})},selectDashboard:t=>{e(n=>{var r;((r=n.selectedDashboard)==null?void 0:r.id)!==t.id&&(n.lastSelectedDashboard=n.selectedDashboard,n.selectedDashboard=t),n.showHub=!1})},updateSelectedDashboard:t=>{e(n=>{n.selectedDashboard=t})},selectVisual:t=>{e(n=>{n.lastSelectedVisual=n.selectedVisual,n.selectedVisual=t})},clearSelectedDashboard:()=>{e(t=>{t.lastSelectedDashboard=t.selectedDashboard,t.selectedDashboard=null,t.showHub=!0})},clearSelectedVisual:()=>{e(t=>{t.lastSelectedVisual=t.selectedVisual,t.selectedVisual=null})},setShowHub:t=>{e(n=>{n.showHub=t})}}}))),n0e=()=>_s(e=>e.selectedVisual),Dm=()=>_s(e=>e.actions);function Pv(){const{authToken:e,version:t,tokenProps:n,id:r}=It(),o=_s(g=>g.selectedDashboard),s=_s(g=>g.showHub),i=p.useDashboardStore(g=>g.selectedLensId),a=r0e({showHub:s,selectedDashboardId:o==null?void 0:o.id,dashboardId:r,tokenDashboardId:n==null?void 0:n.dashboard_id});function c(){return!(!(e!=null&&e.accessToken)||!a)}const{data:u,isLoading:d,isFetching:f,isError:h,refetch:m}=Un({queryKey:["dashboard",i,e==null?void 0:e.accessToken,a],queryFn:()=>p.getDashboard(n.apiServiceUrl,e==null?void 0:e.accessToken,{lensId:i,version:t,dashboardId:a}),enabled:c()});return{data:u,isLoading:d,isFetching:f,isError:h,refetch:m,dashboardIdToFetch:a}}function r0e({showHub:e,selectedDashboardId:t,dashboardId:n,tokenDashboardId:r}){return e?null:t||n||r||null}function o0e(){const{authToken:e}=It(),t=p.useDashboardStore(r=>r.authToken),{setAuthToken:n}=p.useDashboardActions();return v.useLayoutEffect(()=>{const r=e==null?void 0:e.accessToken,o=t==null?void 0:t.accessToken;e&&r!==o&&n(e)},[e,t,n]),e}function _Y(e){const t=v.useCallback(s=>`semaphor-default-sheet-${s}`,[]),n=v.useCallback(()=>{if(!e)return null;try{const s=t(e);return localStorage.getItem(s)}catch(s){return console.error("Error reading default sheet preference:",s),null}},[e,t]),r=v.useCallback(s=>{if(!(!e||!s))try{const i=t(e);localStorage.setItem(i,s)}catch(i){console.error("Error saving default sheet preference:",i)}},[e,t]),o=v.useCallback(()=>{if(e)try{const s=t(e);localStorage.removeItem(s)}catch(s){console.error("Error clearing default sheet preference:",s)}},[e,t]);return{getDefaultSheetId:n,setDefaultSheetId:r,clearDefaultSheetId:o}}const vB=/\[\[\s*param\.([A-Za-z0-9_.-]+)\s*\]\]/g,wB=/\bparam\s*\(\s*(['"])([^'"]+)\1/g;function s0e(e){const t=[];let n=0;for(;n<e.length;){const r=e.indexOf("{{",n),o=e.indexOf("{%",n);let s=-1,i="";if(r===-1?(s=o,i="%}"):o===-1||r<o?(s=r,i="}}"):(s=o,i="%}"),s===-1)break;const a=e.indexOf(i,s+2);if(a===-1){n=s+2;continue}t.push(e.slice(s+2,a)),n=a+2}return t}function dO(e){var r,o;if(!e)return[];const t=new Set;let n;for(vB.lastIndex=0;(n=vB.exec(e))!==null;){const s=(r=n[1])==null?void 0:r.trim();s&&t.add(s)}for(const s of s0e(e))for(wB.lastIndex=0;(n=wB.exec(s))!==null;){const i=(o=n[2])==null?void 0:o.trim();i&&t.add(i)}return Array.from(t)}function Ek(e){const t=new Set,n=new Map;for(const r of e.controlBindings||[])t.add(r.controlId),r.target==="sql_param"&&n.set(r.paramId,r.controlId);for(const r of dO(e.sql))t.add(n.get(r)??r);return Array.from(t)}function IY(e){const t=new Map,n=new Map;for(const r of e.controlBindings||[])r.target==="sql_param"&&n.set(r.paramId,r.controlId);for(const r of dO(e.sql))t.set(r,{paramId:r,controlId:n.get(r)??r});return Array.from(t.values())}const i0e=["kpi","table","detailTable","aggregateTable","pivotTable","bar","horizontalBar","stackedBar","line","stackedLine","area","stackedArea","combo","pie","doughnut","polarArea","radar","scatter","bubble","tornado","pyramid","range","funnel","bullet","heatmap","treemap","map","matrixTable"],a0e=new Set(i0e),l0e=["table","detailTable","aggregateTable","pivotTable","matrixTable"],c0e=new Set(l0e);function TY(e){return typeof e=="string"&&c0e.has(e)}function Fv(e){return typeof e=="string"&&a0e.has(e)}function dN(e){return(e==null?void 0:e.type)==="number"||(e==null?void 0:e.type)==="currency"}function EY(e){var n,r;const t=(r=(n=e.preferences)==null?void 0:n.formatNumber)==null?void 0:r.enabled;return t===!1||t==="false"}function DY(e){return(e==null?void 0:e.type)==="number"}function u0e(e){var n;if(!DY(e))return!1;const t=(n=e==null?void 0:e.numberFormat)==null?void 0:n.style;return t===void 0||t==="decimal"||t==="currency"}function Dk(e,t){const n=t==null?void 0:t.type;if(n&&n!=="none"&&n!=="number")return{currencyBindable:!1};const r=n==="number"?t!=null&&t.numberFormat?p.fromColumnNumberFormat(t.numberFormat,{preserveOmittedProperties:!0}):{type:"number"}:void 0,o=p.fromSemanticFormat(e.format,{preserveOmittedProperties:!0}),s=va.normalizeAnalyticsCatalogDataType(e.dataType)==="number"?{type:"number"}:void 0,a=(t==null?void 0:t.inheritMetricFormat)===!1||!!(t!=null&&t.numberFormat)&&(t==null?void 0:t.inheritMetricFormat)!==!0?r:o||s||r;return{authoredFormat:a,currencyBindable:dN(a)}}function fO(e,t){var c,u;const n=p.fromSemanticFormat(t.format,{preserveOmittedProperties:!0}),r=p.fromNumberAxisFormat((c=e.preferences)==null?void 0:c.numberAxisFormat),o=EY(e)?void 0:p.fromLegacyFormatNumber((u=e.preferences)==null?void 0:u.formatNumber),s=va.normalizeAnalyticsCatalogDataType(t.dataType)==="number"?{type:"number"}:void 0,i=n||r||o||s;return{authoredFormat:i,source:n?"semantic":r?"number_axis":o?"legacy":s?"inferred":void 0,currencyBindable:dN(i)}}function m0(e,t={}){var h,m,g,b,x,y;const n=t.metricIndex??0,r=!!((h=e.sql)!=null&&h.trim()),o=p.fromPersistedKpiFormatOptions((g=(m=e.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:g.formatOptions),s=n===0?p.fromLegacyFormatNumber((b=e.preferences)==null?void 0:b.formatNumber):void 0,i=EY(e);if(r){const w=t.resultColumnKey?{kind:"column",columnKey:t.resultColumnKey}:void 0;return{target:w,authoredFormat:o||s,currencyBindable:!i&&!!w&&dN(o)}}const a=(y=(x=e.config)==null?void 0:x.metricColumns)==null?void 0:y[n],c=a!=null&&a.id?{kind:"metric",metricId:a.id}:void 0,u=p.fromSemanticFormat(a==null?void 0:a.format,{preserveOmittedProperties:!0}),d=va.normalizeAnalyticsCatalogDataType(a==null?void 0:a.dataType)==="number"?{type:"number"}:void 0,f=o||u||s||d;return{target:c,authoredFormat:f,currencyBindable:!i&&Fv(e.type)&&!!c&&dN(f)}}function hO(){const e=new Set;return(t,n,r)=>{const o=t.id||t.alias||t.name||`field_${n+1}`,s=[o];r.kind==="axis"&&r.grain&&s.push(`${o}-${r.grain}`),r.kind==="value"&&s.push(`${o}-${r.aggregate.toLowerCase()}`),s.push(`${o}-${n+1}`);for(const c of s)if(!e.has(c))return e.add(c),c;let i=n+1,a=`${o}-${i}`;for(;e.has(a);)i+=1,a=`${o}-${i}`;return e.add(a),a}}function MY(e){return e==="COUNT"||e==="SUM"||e==="AVG"||e==="MIN"||e==="MAX"||e==="MEDIAN"||e==="DISTINCT"?e:"SUM"}function CB(e){return`measure:${e}`}function Mk(e){var o,s,i,a,c,u,d;const t=(o=e.config)==null?void 0:o.metricColumns;if(Array.isArray(t)){const f=hO();return t.map((h,m)=>{const g=f(h,m,{kind:"value",aggregate:MY(h.aggregate)});return{measureId:CB(g),format:h.format,metric:h}})}const n=((i=(s=e.config)==null?void 0:s.matrixIntent)==null?void 0:i.values)||((a=e.config)==null?void 0:a.values)||[],r=((u=(c=e.config)==null?void 0:c.matrixIntent)==null?void 0:u.source)||((d=e.config)==null?void 0:d.source);return n.map((f,h)=>{const m=d0e(f.field,f.aggregate,r),g=f.id||`${m}-${h}`;return{measureId:CB(g),format:f.format,value:f}})}function d0e(e,t,n){const r=e.source||n;return[r==null?void 0:r.kind,(r==null?void 0:r.kind)==="semantic"?r.domainId:void 0,(r==null?void 0:r.kind)==="semantic"?r.datasetId:void 0,(r==null?void 0:r.kind)==="semantic"?r.datasetName:void 0,(r==null?void 0:r.kind)==="physical"?r.connectionId:void 0,(r==null?void 0:r.kind)==="physical"?r.databaseName:void 0,(r==null?void 0:r.kind)==="physical"?r.schemaName:void 0,(r==null?void 0:r.kind)==="physical"?r.tableName:void 0,e.name,e.role,t].filter(Boolean).join(":")}function RY(e){const t=new Map;if(!e.result||!e.presentation.preferences)return t;const n=new Map((e.card?Mk(e.card):[]).map(r=>[r.measureId,r]));for(const[r,o]of Object.entries(e.result.measuresById)){const s=n.get(r),i=mO(s?s.format:o.format);i&&t.set(r,$t.resolveNumericPresentation(i,e.presentation.preferences,e.presentation.resolveBoundCurrency({kind:"matrix_measure",measureId:r})))}return t}function AY(e){const{cell:t}=e;if(t.presence==="missing"||t.presence==="densified")return"—";if(t.presence==="presentNull"||t.value===null||t.value===void 0)return"";const n=f0e(t.value),r=e.formatsByMeasureId.get(t.measureId);return n!==void 0&&r?$t.formatNumericCanonical(n,r):n!==void 0?new Intl.NumberFormat("en-US",{maximumFractionDigits:6}).format(n):String(t.value)}function mO(e){if(typeof e=="object"&&(e==null?void 0:e.type)==="datetime")return;const t=p.fromSemanticFormat(e,{preserveOmittedProperties:!0});if(!t)return{type:"number"};if(Kt.isNumericCanonicalFormat(t))return t}function f0e(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||!e.trim())return;const t=Number(e);return Number.isFinite(t)?t:void 0}function pO(e){var t,n;return e.type==="detailTable"?((t=e.config)==null?void 0:t.detailColumns)||[]:((n=e.config)==null?void 0:n.metricColumns)||[]}function PY(e){return new Set(p.getDashboardCards(e).flatMap(t=>(t.controlBindings||[]).filter(Ov).map(n=>n.controlId)))}function h0e(e,t){const n=[t.id,t.alias,t.label,t.name,t.qualifiedFieldName].filter(s=>!!s);for(const s of n)if(e[s])return e[s];const r=new Set(n.map(s=>s.trim().toLowerCase())),o=Object.entries(e).find(([s])=>r.has(s.trim().toLowerCase()));return o==null?void 0:o[1]}function SB(e){return[...new Map(e.map(t=>[ba(t),t])).values()]}function m0e(e){if(e.metric)return Dk(e.metric,void 0).currencyBindable;const t=mO(e.format);return(t==null?void 0:t.type)==="number"||(t==null?void 0:t.type)==="currency"}function gO(e,t=[]){var C,N,S;const n=!!((C=e.sql)!=null&&C.trim()),r=Fv(e.type),o=n&&r&&e.type!=="kpi"&&e.type!=="matrixTable",s=pO(e),i=((S=(N=e.preferences)==null?void 0:N.tablePrefs)==null?void 0:S.columnSettingsMap)||{},a=!n&&e.type==="kpi"?s.map((j,_)=>m0(e,{metricIndex:_})):[],c=!n&&e.type==="matrixTable"?Mk(e):[],u=(n?[]:s).map(j=>({kind:"metric",metricId:j.id})),d=c.map(j=>({kind:"matrix_measure",measureId:j.measureId})),f=c.filter(m0e).map(j=>({kind:"matrix_measure",measureId:j.measureId})),h=e.type==="matrixTable"?[]:e.type==="kpi"?a.filter(j=>j.currencyBindable).flatMap(j=>j.target?[j.target]:[]):(n||!r?[]:s).filter(j=>(TY(e.type)?Dk(j,h0e(i,j)):fO(e,j)).currencyBindable).map(j=>({kind:"metric",metricId:j.id})),m=[...new Set(t)],g=(o?m:[]).map(j=>({kind:"column",columnKey:j})),b=(o?m:[]).filter(j=>u0e(i[j])).map(j=>({kind:"column",columnKey:j})),x=(n&&e.type==="kpi"?m.slice(0,1):[]).map(j=>({kind:"column",columnKey:j})),y=n&&e.type==="kpi"?m0(e,{resultColumnKey:m[0]}):void 0,w=r&&(y!=null&&y.currencyBindable)?x:[];return{knownTargets:SB([...e.type==="matrixTable"?d:u,...g,...x]),eligibleTargets:SB([...h,...f,...b,...w])}}function FY(e,t){const n=m0(e,{resultColumnKey:t});return n.currencyBindable?n.target:void 0}function ec(e){var t;return(t=e.card.sql)!=null&&t.trim()?{kind:"column",columnKey:e.columnKey}:e.metricId?{kind:"metric",metricId:e.metricId}:void 0}function ba(e){return e.kind==="metric"?`metric:${e.metricId}`:e.kind==="column"?`column:${e.columnKey}`:`matrix_measure:${e.measureId}`}function p0e(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(t.kind==="metric"&&typeof t.metricId=="string"&&t.metricId.trim())return{kind:"metric",metricId:t.metricId};if(t.kind==="column"&&typeof t.columnKey=="string"&&t.columnKey.trim())return{kind:"column",columnKey:t.columnKey};if(t.kind==="matrix_measure"&&typeof t.measureId=="string"&&t.measureId.trim())return{kind:"matrix_measure",measureId:t.measureId}}function Ov(e){return e.target==="presentation_currency"}function g0e(e){return e.target!=="sql_param"&&e.target!=="presentation_currency"}function NB(e){const t=Li.canonicalizeSupportedCurrencyCode(e);return typeof e=="string"&&e===t?t:void 0}function OY(e){if(e.type!=="enum"||e.source.kind!=="manual")return{diagnostic:"invalid_control_type"};const t=e.source.options.map(n=>NB(n.value));if(t.length===0||t.some(n=>!n))return{diagnostic:"invalid_currency_option"};if(e.requiredAtExecution){const n=e.initialValueStrategy==="saved_default"?NB(e.defaultValue):void 0;if(!n||!t.includes(n))return{diagnostic:"invalid_control_default"}}return{control:e,currencies:t}}function b0e(e){return"control"in OY(e)}function LY(e){const t=PY(e.dashboard);if(t.size===0)return{definitions:e.definitions||[],values:e.values||{}};const n=new Set([...t].filter(r=>!e.referencedControlIds.has(r)));return{definitions:(e.definitions||[]).filter(r=>!n.has(r.id)),values:Object.fromEntries(Object.entries(e.values||{}).filter(([r])=>!n.has(r)))}}function $Y(e){return LY({...e,referencedControlIds:new Set(Ek({sql:e.filterSql,controlBindings:[]}))})}function x0e(e){var t;return LY({...e,referencedControlIds:new Set(Ek({sql:(t=e.source)==null?void 0:t.sql,controlBindings:[]}))})}function zY(e){return{knownKeys:new Set(e.knownTargets.map(ba)),eligibleKeys:new Set(e.eligibleTargets.map(ba)),controlsById:new Map((e.controls||[]).map(t=>[t.id,t]))}}function BY(e,t){if(!e||typeof e!="object"||e.target!=="presentation_currency")return{};const n=e,r=typeof n.controlId=="string"&&n.controlId.trim()?n.controlId:void 0;if(!r)return{diagnostic:{code:"invalid_binding_shape"}};const o=p0e(n.presentationTarget);if(!o)return{diagnostic:{code:"missing_target",controlId:r}};const s=ba(o);if(!t.knownKeys.has(s))return{diagnostic:{code:"stale_target",controlId:r}};if(!t.eligibleKeys.has(s))return{diagnostic:{code:"inapplicable_target",controlId:r}};const i=t.controlsById.get(r);if(!i)return{diagnostic:{code:"missing_control",controlId:r}};const a=OY(i);return"diagnostic"in a?{diagnostic:{code:a.diagnostic,controlId:r}}:{binding:{controlId:r,presentationTarget:o,control:a.control,currencies:a.currencies}}}function y0e(e){const t=zY(e);return(e.bindings||[]).flatMap(n=>{const r=BY(n,t);return"diagnostic"in r?[r.diagnostic]:[]})}function VY(e){var o;const t=[],n=ba(e.target),r=zY(e);for(const s of e.bindings||[]){const i=BY(s,r);if("diagnostic"in i){t.push(i.diagnostic);continue}const a=i.binding;if(!a||ba(a.presentationTarget)!==n)continue;const u=Li.canonicalizeSupportedCurrencyCode((o=e.values)==null?void 0:o[a.control.id]);if(!(!u||!a.currencies.includes(u)))return{currency:u,diagnostics:t}}return{diagnostics:t}}function v0e(e,t){if(!e||typeof e!="object"||!("kind"in e))return e;switch(e.kind){case"manual":return{kind:"manual",...t!=null&&t.includePresentation?{options:e.options.map(n=>({value:n.value,label:n.label,presentation:n.presentation}))}:{optionValues:e.options.map(n=>n.value).sort()}};case"dataset_values":return{kind:"dataset_values",fieldId:e.fieldId,connectionId:e.connectionId||""};case"field_allowlist":return{kind:"field_allowlist",fieldIds:[...e.fieldIds].sort()};case"metric_allowlist":return{kind:"metric_allowlist",metricIds:[...e.metricIds].sort()};case"sql_query":return{kind:"sql_query",connectionId:e.connectionId,sql:e.sql,valueColumn:e.valueColumn,labelColumn:e.labelColumn};default:return e}}function w0e(e,t){return{id:e.id,scope:e.scope,type:e.type,source:v0e(e.source,t),initialValueStrategy:e.initialValueStrategy,defaultValue:e.defaultValue,requiredAtExecution:e.requiredAtExecution,...t!=null&&t.includePresentation?{label:e.label,helpText:e.helpText,hidden:e.hidden,locked:e.locked,placement:e.placement,showLabel:e.showLabel,toolbarWidth:e.toolbarWidth}:{}}}function C0e(e,t){return e.target==="sql_param"||e.target==="presentation_currency"?e:e.target==="config_field_selector"&&!(t!=null&&t.includePresentation)?{...e,mapping:Object.fromEntries(Object.entries(e.mapping).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>{const o={...r};return delete o.format,delete o.dateFormat,delete o.customFormat,delete o.semanticTemporalPresentation,[n,o]}))}:{...e,mapping:Object.fromEntries(Object.entries(e.mapping).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).sort(([o],[s])=>o.localeCompare(s))):r]))}}function jB(e=[],t){return[...e].map(n=>w0e(n,t)).sort((n,r)=>n.id.localeCompare(r.id)||n.scope.localeCompare(r.scope)||n.type.localeCompare(r.type))}function S0e(e=[],t){return e.filter(n=>(t==null?void 0:t.includePresentation)||!Ov(n)).map(n=>C0e(n,t)).sort((n,r)=>Ho.stableSerialize(n).localeCompare(Ho.stableSerialize(r)))}function uR(e,t){return e?Ho.stableSerialize({controlDefinitions:jB(e.controlDefinitions,t),cardControlDefinitions:jB(e.cardControlDefinitions,t),controlBindings:S0e(e.controlBindings,t)}):"__none__"}function VT(e,t){return e&&t.has(e)?e:null}function N0e({selectedSheetId:e,preservedSelectedSheetId:t,defaultSheetId:n,sheets:r}){var s;const o=new Set((r||[]).map(i=>i.id).filter(i=>typeof i=="string"));return VT(e,o)||VT(t,o)||VT(n,o)||((s=r==null?void 0:r[0])==null?void 0:s.id)||null}function HY(e){const t=e.trim().split(/[^A-Za-z0-9]+/).filter(Boolean).map(r=>r.toLowerCase());if(!t.length)return"input";const n=t.map((r,o)=>o===0?r:_B(r)).join("");return/^[A-Za-z]/.test(n)?n:`input${_B(n)}`}function bO(e,t){const n=HY(e);return qY(n,t)}function Lv(e){const n=e.trim().replace(/^\{\{\s*/,"").replace(/\s*\}\}$/,"").replace(/[^A-Za-z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"");return n?/^[A-Za-z]/.test(n)?n:`input_${n}`:"input"}function Od(e,t){return qY(Lv(e),t)}function qY(e,t){const n=new Set(t.map(o=>o.variableName).filter(o=>!!o));if(!n.has(e))return e;let r=2;for(;n.has(`${e}${r}`);)r+=1;return`${e}${r}`}function xO(e){return p.getDataType(e.dataType)==="date"?["label","start","end","range"]:["label","value"]}function yO(e){return k0e(e)?["label","value"]:["value"]}function kB(e){return e.kind==="filter"?`filter:${e.filter.id}`:`control:${e.control.id}`}function j0e(e){return{placement:e.hide||e.displayMode==="canvas"?"hidden":"toolbar",...e.toolbarWidth?{widthPx:e.toolbarWidth}:{}}}function UY(e){return{placement:e.hidden?"hidden":e.placement||(e.scope==="card"?"card_header":"toolbar"),...e.toolbarWidth?{widthPx:e.toolbarWidth}:{}}}function fN(e){return!!e.compatibility}function k0e(e){return e.type==="enum"||e.type==="multi_enum"||e.type==="field_selector"||e.type==="metric_selector"||e.type==="aggregation_selector"||e.type==="grain_selector"}function _B(e){return e&&e[0].toUpperCase()+e.slice(1)}function _0e(e){var i,a;const t=[...e.inputs||[]],n=new Set(t.map(c=>c.id)),r=new Set((e.sheets||[]).filter(c=>c.kind==="document").map(c=>c.id));let o=!1;for(const c of e.sheets||[])if(!(c.kind!=="document"||!((a=(i=c.document)==null?void 0:i.inputs)!=null&&a.length)))for(const u of c.document.inputs)n.has(u.id)||(t.push(I0e(u,c.id)),n.add(u.id),o=!0);const s=t.map(c=>{if(c.kind==="filter"&&IB(c,r)&&c.filter.variableName!==c.variableName)return o=!0,{...c,filter:{...c.filter,variableName:c.variableName}};if(c.kind!=="control"||!IB(c,r))return c;const u=Od(c.control.id||c.variableName,t.filter(d=>d.id!==c.id));return c.variableName===u&&c.control.id===u?c:(o=!0,{...c,variableName:u,control:{...c.control,id:u}})});return o?{...e,inputs:s}:e}function I0e(e,t){const n={id:e.id,label:e.label,variableName:e.variableName,description:e.description,requiredAtExecution:e.requiredAtExecution,scope:{kind:"sheets",sheetIds:[t]},runtimeScope:"perSheet",presentation:{placement:"toolbar"},exports:e.exports,compatibility:{source:"documentInput",sheetId:t,inputId:e.id}};return e.kind==="filter"?{...n,kind:"filter",filter:e.filter}:{...n,kind:"control",control:e.control}}function IB(e,t){var n;switch(e.scope.kind){case"allSheets":return!((n=e.scope.sheetKinds)!=null&&n.length)||e.scope.sheetKinds.includes("document");case"sheets":return e.scope.sheetIds.some(r=>t.has(r));case"documentSections":return t.has(e.scope.sheetId);default:return!1}}function T0e(e,t={}){if(!e)return[];const n=[],r=[...t.existingInputs||[]];for(const o of e.inlineFilters||[]){const s=o.title||o.column||o.id,i=E0e(o),a={id:Oi.getCardInlineFilterCompatInputId(e.id,o.id),kind:"filter",label:s,variableName:o.variableName?Od(o.variableName,r):bO(s,r),scope:{kind:"cards",cardIds:[e.id]},runtimeScope:"perCard",presentation:{placement:"card_header"},filter:i,exports:xO(i),compatibility:{source:"cardInlineFilter",cardId:e.id,filterId:o.id}};r.push(a),n.push(a)}for(const o of e.controls||[]){const s=o.label||o.id,i={id:Oi.getCardControlCompatInputId(e.id,o.id),kind:"control",label:s,variableName:Od(o.id,r),scope:{kind:"cards",cardIds:[e.id]},runtimeScope:"perCard",presentation:UY(o),control:o,exports:yO(o),requiredAtExecution:o.requiredAtExecution,compatibility:{source:"cardControl",cardId:e.id,controlId:o.id}};r.push(i),n.push(i)}return n}function E0e(e){return{kind:"field",id:e.id,variableName:e.variableName,type:e.type,uiType:e.uiType,dateSelectionMode:e.dateSelectionMode,defaultValues:e.defaultValues,defaultDateFilter:e.defaultDateFilter,connectionId:e.connectionId,title:e.title,column:e.column,dataType:e.dataType,table:e.table,database:e.database,qualifiedTableName:e.qualifiedTableName,sql:e.sql,operation:e.operation,fieldMeta:e.fieldMeta,semanticContext:e.semanticContext,searchMode:e.searchMode,customFilterPreferences:e.customFilterPreferences,showLabel:e.showLabel,toolbarWidth:e.width,displayMode:"toolbar"}}function D0e(e,t={}){const n=[],r=[...t.existingInputs||[]];for(const o of e.controls||[]){const s=o.label||o.id,i={id:Oi.getDashboardControlCompatInputId(o.id),kind:"control",label:s,variableName:Od(o.id,r),scope:{kind:"allSheets",sheetKinds:["dashboard"]},runtimeScope:"shared",presentation:UY(o),control:o,exports:yO(o),requiredAtExecution:o.requiredAtExecution,compatibility:{source:"dashboardControl",controlId:o.id}};r.push(i),n.push(i)}return n}function M0e(e,t={}){const n=[],r=[...t.existingInputs||[]],o=t.availableSheetIds||(e.sheets||[]).filter(u=>u.kind!=="document").map(u=>u.id),s=p.getDashboardCardEntries({sheets:e.sheets}),i=t.availableCardIds?new Set(t.availableCardIds):void 0,a=s.filter(u=>!i||i.has(u.card.id)),c=t.availableCardIds||a.map(u=>u.card.id);for(const u of e.filters||[]){const d=u.title||u.column||u.id,f={id:Oi.getDashboardFilterCompatInputId(u.id),kind:"filter",label:d,variableName:u.variableName?Od(u.variableName,r):bO(d,r),scope:R0e(u,{availableDashboardSheetIds:o,availableCardEntries:a,availableCardIds:c}),runtimeScope:"shared",presentation:j0e(u),filter:u,exports:xO(u),compatibility:{source:"dashboardFilter",filterId:u.id}};r.push(f),n.push(f)}return n}function R0e(e,t){if(e.applyToCardIds!==void 0){const n=new Set(TB(e,t));return{kind:"cards",cardIds:e.applyToCardIds.filter(r=>n.has(r))}}if(e.excludeCardIds!==void 0){const n=new Set(e.excludeCardIds);return{kind:"cards",cardIds:TB(e,t).filter(o=>!n.has(o))}}if(e.sheetId)return{kind:"sheets",sheetIds:[e.sheetId]};if(e.applyToSheetIds!==void 0)return{kind:"sheets",sheetIds:e.applyToSheetIds};if(e.excludeSheetIds!==void 0){const n=new Set(e.excludeSheetIds);return{kind:"sheets",sheetIds:t.availableDashboardSheetIds.filter(r=>!n.has(r))}}return{kind:"allSheets",sheetKinds:["dashboard"]}}function TB(e,t){return!e.sheetId&&e.applyToSheetIds===void 0&&e.excludeSheetIds===void 0?t.availableCardIds:t.availableCardEntries.filter(n=>A0e(e,n.sheet.id)).map(n=>n.card.id)}function A0e(e,t){return e.sheetId&&e.sheetId!==t?!1:e.applyToSheetIds!==void 0?e.applyToSheetIds.includes(t):e.excludeSheetIds!==void 0?!e.excludeSheetIds.includes(t):!0}function uf({dashboard:e,dashboardInputValues:t}){var r,o;const n=!!(Object.keys((t==null?void 0:t.shared)||{}).length||Object.values((t==null?void 0:t.bySheetId)||{}).some(s=>Object.keys(s).length>0)||Object.values((t==null?void 0:t.byCardId)||{}).some(s=>Object.keys(s).length>0)||Object.values((t==null?void 0:t.byDocumentSectionId)||{}).some(s=>Object.keys(s).length>0));return!!((r=e.inputs)!=null&&r.length||e.defaultInputValues||(o=e.filters)!=null&&o.some(s=>s.kind==="global-date")||n)}function ab({dashboard:e,card:t,availableSheetIds:n,availableCardIds:r}){const o=e.inputs||[],s=[],i=[...o],a=M0e(e,{existingInputs:i,availableSheetIds:n,availableCardIds:r});s.push(...a),i.push(...a);const c=D0e(e,{existingInputs:i});s.push(...c),i.push(...c);const u=T0e(t,{existingInputs:i});return s.push(...u),{authoredInputs:o,compatibilityInputs:s,allInputs:[...o,...s]}}function Yi({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,runtimeValues:s,mode:i="interactive",timezone:a}){var y;const c={sheetId:t,cardId:n==null?void 0:n.id,sectionId:r,sheetKind:o||K0e(e,t)},u=ab({dashboard:e,card:n}),d=Rk(u.allInputs);P0e(d);const f=d.filter(w=>Qh(w,c));W0e(f);const h=f.map(w=>O0e({dashboard:e,input:w,runtimeValues:s,target:c,timezone:a})),m=$0e({resolvedInputs:h,card:n}),g=z0e(h),b=(y=h.find(w=>w.kind==="filter"&&p.isGlobalDateFilter(w.filter)))==null?void 0:y.comparisonSelection,x=h.flatMap((w,C)=>{var j;const N=f[C];if(!N||!p.isComparisonCapableDashboardDateInput(N)||!w.comparisonSelection)return[];const S=((j=w.slot)==null?void 0:j.status)==="set"&&w.slot.value.kind==="filter"?w.slot.value.filterValue:void 0;return[{inputId:w.id,filterId:N.filter.id,label:w.label,filter:N.filter,filterValue:S,selection:w.comparisonSelection}]});return{inputs:f,resolvedInputs:h,...m,...g,...b?{globalDateComparisonSelection:b}:{},dateComparisonInputs:x,missingRequiredInputs:h.filter(w=>w.missingRequiredValue)}}function P0e(e){if(e.filter(n=>n.kind==="filter"&&p.isGlobalDateFilter(n.filter)).length>1)throw new Error("Dashboard input contract allows exactly one Global Date input.")}function Qh(e,t){var n;if(!F0e(e,t))return!1;switch(e.scope.kind){case"allSheets":return(n=e.scope.sheetKinds)!=null&&n.length?t.sheetKind?e.scope.sheetKinds.includes(t.sheetKind):!1:!!t.sheetId||!!t.cardId;case"sheets":return!!t.sheetId&&e.scope.sheetIds.includes(t.sheetId);case"cards":return!!t.cardId&&e.scope.cardIds.includes(t.cardId);case"documentSections":return!!t.sheetId&&!!t.sectionId&&e.scope.sheetId===t.sheetId&&e.scope.sectionIds.includes(t.sectionId);default:return!1}}function F0e(e,t){return t.sheetKind!=="document"||!e.compatibility||e.compatibility.source==="documentInput"?!0:e.compatibility.source==="cardInlineFilter"||e.compatibility.source==="cardControl"?!!t.cardId&&e.compatibility.cardId===t.cardId:!1}function Rk(e){const t=new Set(e.filter(n=>!fN(n)).map(kB));return e.filter(n=>!fN(n)||!t.has(kB(n)))}function O0e(e){var d,f;const t=p.getDashboardInputRuntimeSlot(e.runtimeValues.dashboardInputValues,e.input,e.target),n=p.getDashboardInputRuntimeSlot(e.dashboard.defaultInputValues,e.input,e.target),r=(t==null?void 0:t.comparisonSelection)??(n==null?void 0:n.comparisonSelection),o=p.isComparisonCapableDashboardDateInput(e.input);if(r&&!o)throw new Error(`Dashboard input "${e.input.id}" carries comparison state but is not a supported dashboard date filter.`);const i=fN(e.input)&&((d=e.input.compatibility)==null?void 0:d.source)!=="documentInput"?B0e(e):p.hydrateAuthoredDashboardInputSlot({dashboard:e.dashboard,input:e.input,runtimeValues:e.runtimeValues.dashboardInputValues,target:e.target,timezone:e.timezone}),a=(i==null?void 0:i.status)==="set"&&i.value.kind===e.input.kind?i.value:void 0;if(i!=null&&i.comparisonSelection){if(!o)throw new Error(`Dashboard input "${e.input.id}" carries comparison state but is not a supported dashboard date filter.`);const h=$r.validateGlobalDateComparisonSelection(i.comparisonSelection,`dashboardInputValues.${e.input.id}.comparisonSelection`);if(!h.ok)throw new Error(((f=h.errors[0])==null?void 0:f.message)||"Invalid comparison selection.")}if(e.input.kind==="filter"){const h=(a==null?void 0:a.kind)==="filter"?WY(e.input,a.filterValue):void 0,m=H0e({input:e.input,filterValue:h,timezone:e.timezone});return{id:e.input.id,kind:"filter",label:e.input.label,variableName:e.input.variableName,requiredAtExecution:!!e.input.requiredAtExecution,slot:i,rawValue:h?G0e(h.values):void 0,displayValue:EB(m.label??m.value),exports:m,filter:e.input.filter,filterValue:h,missingRequiredValue:!!e.input.requiredAtExecution&&!h,...o&&(i!=null&&i.comparisonSelection)?{comparisonSelection:i.comparisonSelection}:{}}}const c=(a==null?void 0:a.kind)==="control"?a.value:void 0,u=q0e({input:e.input,value:c});return{id:e.input.id,kind:"control",label:e.input.label,variableName:e.input.variableName,requiredAtExecution:!!e.input.requiredAtExecution,slot:i,rawValue:c,displayValue:EB(u.label??u.value),exports:u,control:e.input.control,controlValue:c,missingRequiredValue:!!e.input.requiredAtExecution&&!L0e(c)}}function L0e(e){return e==null?!1:typeof e=="string"?e.trim().length>0:Array.isArray(e)?e.length>0:!0}function $0e({resolvedInputs:e,card:t}){const n=[],r=new Map,o=new Map,s={};for(const c of e){if(c.kind==="filter"){c.filter&&c.filterValue&&n.push(c.filterValue);continue}c.control&&(U0e(c)?o.set(c.control.id,c.control):r.set(c.control.id,c.control),c.controlValue!==void 0&&(s[c.control.id]=c.controlValue))}const i=new Set([...r.keys(),...o.keys()]),a=((t==null?void 0:t.controlBindings)||[]).filter(c=>i.has(c.controlId));return{activeFilters:n,controlDefinitions:Array.from(r.values()),cardControlDefinitions:Array.from(o.values()),controlBindings:a,controlValues:s}}function z0e(e){const t={},n={};for(const r of e)n[r.id]=r,t[r.variableName]=r;return{variablesByName:t,variablesById:n}}function B0e(e){var i,a,c,u;const t=(i=e.input.compatibility)==null?void 0:i.source,n=p.getDashboardInputRuntimeSlot(e.runtimeValues.dashboardInputValues,e.input,e.target),r=p.hydrateAuthoredDashboardInputSlot({dashboard:e.dashboard,input:e.input,runtimeValues:e.runtimeValues.dashboardInputValues,target:e.target,timezone:e.timezone});if((n==null?void 0:n.status)==="set"||(n==null?void 0:n.status)==="cleared")return r;if(e.input.kind==="filter"){const d=e.input.filter.id,f=t==="cardInlineFilter"?e.target.cardId?(c=(a=e.runtimeValues.inlineFilterValuesMap)==null?void 0:a[e.target.cardId])==null?void 0:c.find(m=>m.filterId===d):void 0:(u=e.runtimeValues.filterValues)==null?void 0:u.find(m=>m.filterId===d),h=p.isComparisonCapableDashboardDateInput(e.input)?(r==null?void 0:r.comparisonSelection)??(f?{mode:"off"}:void 0):void 0;if(f){const m=p.createFilterDashboardInputSlot(WY(e.input,f));return(m==null?void 0:m.status)==="set"?{...m,...h?{comparisonSelection:h}:{}}:h?{comparisonSelection:h}:void 0}return h?{comparisonSelection:h}:void 0}const o=e.input.control.id,s=V0e({source:t,target:e.target,runtimeValues:e.runtimeValues});if(s.values&&Object.prototype.hasOwnProperty.call(s.values,o))return p.createControlDashboardInputSlot(s.values[o]);if(!s.isExplicit)return t==="dashboardControl"?p.createControlDashboardInputSlot(p.resolveSavedDefaultValue(e.input.control,e.dashboard.defaultControlValues)):p.getBackingDefaultSlot(e.input,e.timezone)}function V0e({source:e,target:t,runtimeValues:n}){var r;return e==="cardControl"&&t.cardId?{values:(r=n.cardControlValuesMap)==null?void 0:r[t.cardId],isExplicit:!!(n.cardControlValuesMap&&Object.prototype.hasOwnProperty.call(n.cardControlValuesMap,t.cardId))}:{values:n.controlValues,isExplicit:n.controlValues!==void 0}}function WY(e,t){const n=t.filterId===e.filter.id?t:{...t,filterId:e.filter.id};if(p.isCompatibleFilterValue(e.filter,n))return p.normalizeDashboardDateComparisonFilterValue(e,n)}function H0e({input:e,filterValue:t,timezone:n}){const r=e.exports||xO(e.filter),o=(t==null?void 0:t.values)||[],s=p.getDataType(e.filter.dataType)==="date",i=o.map(X0e),a=s?i.length>1?`${i[0]} - ${i[1]}`:i[0]||"":i.join(", "),c={};for(const u of r)u==="start"?c.start=i[0]||null:u==="end"?c.end=i[1]||null:u==="range"?c.range=a||null:c[u]=a||null;return c}function q0e({input:e,value:t}){const n=e.exports||yO(e.control),r=Y0e(t),o=r.map(a=>Z0e(e.control,a)).join(", "),s=r.map(KY).join(", "),i={};for(const a of n)i[a]=a==="label"?o||null:s||null;return i}function U0e(e){return e.control?e.control.scope==="card"||e.id.startsWith("compat-card-control:"):!1}function W0e(e){const t=new Map;for(const n of e){if(fN(n))continue;const r=t.get(n.variableName);if(r)throw new Error(`Duplicate dashboard input variableName "${n.variableName}" for inputs "${r}" and "${n.id}" in the same resolved scope.`);t.set(n.variableName,n.id)}}function K0e(e,t){var r;if(!t)return;const n=(r=e.sheets)==null?void 0:r.find(o=>o.id===t);return(n==null?void 0:n.kind)==="document"?"document":"dashboard"}function G0e(e){return e.length>1?e:e[0]??null}function Y0e(e){return e==null?[]:Array.isArray(e)?e:[e]}function Z0e(e,t){var r;const n=KY(t);return e.source.kind==="manual"&&((r=e.source.options.find(o=>o.value===n))==null?void 0:r.label)||n}function KY(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e==null?"":JSON.stringify(e)}function X0e(e){return e instanceof Date?e.toISOString():typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e==null?"":JSON.stringify(e)}function EB(e){return e==null?"":String(e)}function dR({dashboard:e,dashboardInputValues:t,sheetId:n,cardId:r}){let o=p.compactDashboardInputValues(t||{});const s=J0e({dashboard:e,sheetId:n,cardId:r});if(s.status==="unresolved")return{};o=Q0e({dashboardInputValues:o,savedSheetId:n,cardId:r,targets:s.targets});for(const i of s.targets){const a=Rk(ab({dashboard:e,card:i.card}).allInputs).filter(c=>p.canAddressDashboardInputRuntimeSlot(c,i)&&Qh(c,i));for(const c of a){const u=p.getDashboardInputRuntimeSlot(o,c,i);if(!u||u.status===void 0){o=p.setDashboardInputRuntimeSlot(o,c,i,{status:"cleared",comparisonSelection:u==null?void 0:u.comparisonSelection});continue}u.status==="set"&&p.isComparisonCapableDashboardDateInput(c)&&!u.comparisonSelection&&(o=p.setDashboardInputRuntimeSlot(o,c,i,{...u,comparisonSelection:{mode:"off"}}))}}return p.compactDashboardInputValues(o)}function Q0e({dashboardInputValues:e,savedSheetId:t,cardId:n,targets:r}){var c,u,d,f;const o={},s=new Set(r.flatMap(h=>h.sheetId?[h.sheetId]:[])),i=new Set(r.flatMap(h=>h.cardId?[h.cardId]:[])),a=new Set(r.flatMap(h=>h.sectionId?[h.sectionId]:[]));if(e.shared&&(o.shared={...e.shared}),n){const h=r[0],m=(t?(c=e.bySheetId)==null?void 0:c[t]:void 0)??(h.sheetId?(u=e.bySheetId)==null?void 0:u[h.sheetId]:void 0);h.sheetId&&m&&(o.bySheetId={[h.sheetId]:{...m}});const g=h.cardId?(d=e.byCardId)==null?void 0:d[h.cardId]:void 0;h.cardId&&g&&(o.byCardId={[h.cardId]:{...g}});const b=Object.entries(e.byDocumentSectionId||{}),x=(h.sectionId?(f=e.byDocumentSectionId)==null?void 0:f[h.sectionId]:void 0)??(b.length===1?b[0][1]:void 0);return h.sectionId&&x&&(o.byDocumentSectionId={[h.sectionId]:{...x}}),p.compactDashboardInputValues(o)}return o.bySheetId=HT(e.bySheetId,s),o.byCardId=HT(e.byCardId,i),o.byDocumentSectionId=HT(e.byDocumentSectionId,a),p.compactDashboardInputValues(o)}function HT(e,t){if(!e)return;const n=Object.entries(e).filter(([r])=>t.has(r));return n.length>0?Object.fromEntries(n.map(([r,o])=>[r,{...o}])):void 0}function J0e({dashboard:e,sheetId:t,cardId:n}){var i;if(n){const a=eve(e,n);return a?{status:"resolved",targets:[a]}:{status:"unresolved",targetKind:"card"}}const r=(e.sheets||[]).filter(a=>!t||a.id===t);if(t&&r.length===0)return{status:"unresolved",targetKind:"sheet"};const o=r.map(a=>({sheetId:a.id,sheetKind:a.kind||"dashboard"})),s=new Set(r.map(a=>a.id));for(const a of p.getDashboardCardEntries(e))s.has(a.sheet.id)&&o.push({sheetId:a.sheet.id,cardId:a.card.id,card:a.card,sheetKind:a.sheet.kind||"dashboard"});for(const a of r)if(a.kind==="document")for(const c of((i=a.document)==null?void 0:i.sections)||[])o.push({sheetId:a.id,sectionId:c.id,...(c.type==="table"||c.type==="chart")&&{cardId:c.card.id,card:c.card},sheetKind:"document"});return{status:"resolved",targets:o.length>0?o:[{}]}}function eve(e,t){var r;const n=p.findCardLocationById(e,t);if(n)return{sheetId:n.sheet.id,cardId:n.card.id,card:n.card,sheetKind:n.sheet.kind||"dashboard"};for(const o of e.sheets||[])if(o.kind==="document"){for(const s of((r=o.document)==null?void 0:r.sections)||[])if((s.type==="table"||s.type==="chart")&&s.card.id===t)return{sheetId:o.id,sectionId:s.id,cardId:s.card.id,card:s.card,sheetKind:"document"}}}function GY({dashboardInputValues:e,dashboard:t,filterValues:n,sheetId:r,cardId:o,sectionId:s,sheetKind:i}){var u;if(!((u=t.inputs)!=null&&u.length))return e;const a=new Map(n.map(d=>[d.filterId,d]));let c=e||{};for(const d of t.inputs){if(d.kind!=="filter"||!Qh(d,{sheetId:r,cardId:o,sectionId:s,sheetKind:i}))continue;const f=a.get(d.filter.id),h=f?p.createFilterDashboardInputSlot(f):void 0,m=(h==null?void 0:h.status)==="set"?h:{status:"cleared"};c=p.setDashboardInputRuntimeValueAspect(c,d,{sheetId:r,cardId:o,sectionId:s},m)}return c}function ru({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,mode:s,runtimeValues:i,generatedAt:a,timezone:c}){const u=f1({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,mode:s,runtimeValues:i,timezone:c});return{context:u,snapshot:{...t?{sheetId:t}:{},...n!=null&&n.id?{cardId:n.id}:{},mode:s,dashboardInputValues:nve({inputs:u.inputs,context:u,sheetId:t,cardId:n==null?void 0:n.id,sectionId:r}),generatedAt:a,timezone:c}}}function YY({sectionIds:e,...t}){const n=new Set,r=o=>{for(const s of o.missingRequiredInputs)n.add(s.label)};r(f1(t));for(const o of e)r(f1({...t,sectionId:o}));for(const{sectionId:o,card:s}of XY(t.dashboard,t.sheetId,e))r(f1({...t,sectionId:o,card:s}));return Array.from(n)}function vO({sheetIds:e,sheetKind:t="dashboard",...n}){const r=e.map(a=>ru({...n,sheetId:a,sheetKind:t})),o=e.flatMap(a=>tve(n.dashboard,a).map(c=>ru({...n,sheetId:a,card:c,sheetKind:t}))),s=r[0]||o[0]||ru({...n,sheetKind:t}),i=QY(...r.map(a=>a.snapshot.dashboardInputValues),...o.map(a=>a.snapshot.dashboardInputValues));return{context:s.context,snapshot:{...e.length===1?{sheetId:e[0]}:{},mode:n.mode,dashboardInputValues:i,generatedAt:n.generatedAt,timezone:n.timezone}}}function tve(e,t){var i;const n=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),r=[],o=new Set,s=a=>{!(a!=null&&a.id)||o.has(a.id)||(o.add(a.id),r.push(a))};for(const a of(n==null?void 0:n.cards)||[])s(a);for(const a of(n==null?void 0:n.frames)||[])for(const c of(a==null?void 0:a.cards)||[])s(c);return r}function ZY({sectionIds:e,...t}){const n=ru(t),r=e.map(s=>ru({...t,sectionId:s})),o=XY(t.dashboard,t.sheetId,e).map(({sectionId:s,card:i})=>ru({...t,sectionId:s,card:i}));return{...n,snapshot:{...n.snapshot,dashboardInputValues:QY(n.snapshot.dashboardInputValues,...r.map(s=>s.snapshot.dashboardInputValues),...o.map(s=>s.snapshot.dashboardInputValues))}}}function XY(e,t,n){var i,a;const r=new Set(n),o=(i=e.sheets)==null?void 0:i.find(c=>c.id===t);return(((a=o==null?void 0:o.document)==null?void 0:a.sections)||[]).flatMap(c=>c.id&&r.has(c.id)&&c.card?[{sectionId:c.id,card:c.card}]:[])}function nve({inputs:e,context:t,sheetId:n,cardId:r,sectionId:o}){const s=new Map(t.resolvedInputs.map(a=>[a.id,a]));let i={};for(const a of e){const c=s.get(a.id),u=(c==null?void 0:c.slot)||{status:"cleared"};i=p.setDashboardInputRuntimeSlot(i,a,{sheetId:n,cardId:r,sectionId:o},u)}return p.compactDashboardInputValues(i)}function rve(e){return e==="document"||e==="visual"?"export":"print"}function f1({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,mode:s,runtimeValues:i,timezone:a}){return Yi({dashboard:e,sheetId:t,card:n,sectionId:r,sheetKind:o,runtimeValues:i,mode:rve(s),timezone:a})}function QY(...e){const t={};for(const n of e)n.shared&&(t.shared={...t.shared,...n.shared}),qT(t,"bySheetId",n.bySheetId),qT(t,"byCardId",n.byCardId),qT(t,"byDocumentSectionId",n.byDocumentSectionId);return p.compactDashboardInputValues(t)}function qT(e,t,n){if(n){e[t]||(e[t]={});for(const[r,o]of Object.entries(n))e[t][r]={...e[t][r],...o}}}function JY(e){var n;return typeof window>"u"||new URLSearchParams(window.location.search).get("isPdfRender")!=="true"?null:((n=lb(e))==null?void 0:n.reportContext)??null}function lb(e){if(typeof window>"u")return e?$t.parsePresentationExecutionSnapshot(e):null;const t=new URLSearchParams(window.location.search);if(t.get("isPdfRender")!=="true")return null;if(e)return $t.parsePresentationExecutionSnapshot(e);const n=t.get("presentationExecutionSnapshot");if(!n)return null;let r;try{r=JSON.parse(n)}catch{throw new $t.PresentationExecutionSnapshotError("Internal print presentation snapshot JSON is invalid.")}return $t.parsePresentationExecutionSnapshot(r)}function $v(){if(typeof window>"u")return;const e=new URLSearchParams(window.location.search).get("presentationAttachmentIndex");if(e===null)return;const t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error("Internal print presentation attachment index is invalid");return t}function ove(e){return e==="system"?window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":e}function sve(e,t){const n=ove(e);return n==="dark"?Jl({...t==null?void 0:t.default},{...t==null?void 0:t.dark}):t==null?void 0:t.default}function DB(e,t,n){return wye(sve(e,t),n)}function ive(e){return Ho.stableSerialize({hasExplicitDefaultControlValues:e!==void 0,values:e??null})}function ave(e,t){const{controlContractOverrides:n,cardId:r}=t;if(!n||(n.controlDefinitions!==void 0&&(e.controls=n.controlDefinitions),typeof r!="string"||r.trim().length===0))return e;const o=p.findCardById(e,r);return o&&(n.cardControlDefinitions!==void 0&&(o.controls=n.cardControlDefinitions),n.controlBindings!==void 0&&(o.controlBindings=n.controlBindings)),e}function lve(e,t){const n=v.useRef({key:t,value:e});return n.current.key!==t&&(n.current={key:t,value:e}),n.current.value}function cve({customStyle:e,currentTheme:t,onSave:n,onEvent:r,defaultFilterValues:o,defaultControlValues:s,controlContractOverrides:i,dashboardInputExecutionSnapshot:a,interactionExecutionSnapshot:c,presentationExecutionSnapshot:u,type:d,cardId:f,selectedSheetId:h,onFilterValuesChange:m}){var ie,we;const{authToken:g,tokenProps:b}=It(),x=g==null?void 0:g.accessToken,y=g==null?void 0:g.refreshToken,w=v.useMemo(()=>JY(u),[u]);o0e();const C=p.useDashboardStore(fe=>fe.selectedLensId),N=p.useDashboardStore(fe=>fe.relaodToken),{data:S,isLoading:j,isFetching:_,isError:k,refetch:T,dashboardIdToFetch:I}=Pv(),E=(ie=S==null?void 0:S.dashboard)==null?void 0:ie.id,{getDefaultSheetId:D,clearDefaultSheetId:R}=_Y(E),[A,F]=v.useState(o||[]),z=v.useRef(null),L=v.useRef(null),$=ive(s),H=uR(i),M=uR(i,{includePresentation:!0}),B=v.useRef(s);B.current=s;const W=v.useRef($);W.current=$;const P=lve(i,M),G=v.useRef(null),Z=v.useRef(!1),X=v.useRef({dashboardId:null,defaultControlValuesKey:$,controlContractOverridesKey:H}),{setTheme:Y}=oO(),{compiledAppearance:O}=p.useAppearance(),q=p.useDashboardStore(fe=>fe.dashboard.globalStyle),U=v.useMemo(()=>S!=null&&S.dashboard?_0e(ave(Ks(S.dashboard),{controlContractOverrides:P,cardId:f})):void 0,[S==null?void 0:S.dashboard,P,d,f]),{setDashboardWithFilterValues:V,hydrateRuntimeControlValues:K,setStyle:Q,setOnSaveFunction:se,setLenses:oe,setSelectedLensId:me,setInlineFilterValuesMap:le}=p.useDashboardActions();p.useDashboardStore(fe=>fe.actions.setCustomCards);const ue=p.useDashboardStore(fe=>fe.filterValues),ne=p.useDashboardStore(fe=>fe.actions.setThemeStyle),de=p.useDashboardStore(fe=>fe.actions.setDashboardTheme),Ce=p.useDashboardStore(fe=>fe.actions.setOnEvent);v.useEffect(()=>{const fe=L.current;fe&&fe!==I&&p.storeEvents.emit("dashboard:unload"),L.current=I},[I]),v.useEffect(()=>{N&&T()},[T,N]),v.useEffect(()=>{var ee;const fe=((ee=S==null?void 0:S.dashboard)==null?void 0:ee.id)||null,ae=z.current;fe&&fe!==ae&&p.storeEvents.emit("dashboard:load"),z.current=fe},[(we=S==null?void 0:S.dashboard)==null?void 0:we.id]),v.useEffect(()=>{de(O.mode)},[O.mode,de]),v.useEffect(()=>{t&&Y(t)},[t,Y]);const ce=v.useCallback(()=>{const fe=Ks(dt.DEFAULT_STYLE),ae=Jl(fe,q);if(e){const ee=Jl(ae,e),J=DB(O.mode,ee,O);ne(J),Q(ee)}else{const ee=DB(O.mode,ae,O);ne(ee),Q(dt.DEFAULT_STYLE)}},[O,e,q,ne,Q]);return v.useEffect(()=>{S&&S.dashboard&&ce()},[O.mode,e,q,ce,S]),v.useEffect(()=>{var ct,rt,Ct,Lt,vt,Tt;function fe(Me,Je){const kt=Me.filters||[],mt=[];for(const _t of Je){const Rt=kt.find(Pt=>Pt.id===_t.filterId);Rt&&mt.push({filterId:_t.filterId,name:Rt.column,operation:_t.operation,valueType:p.getFilterValueType(Rt),values:_t.values,dataType:Rt.dataType,fieldMeta:Rt.fieldMeta,semanticContext:Rt.semanticContext})}return mt}if(!S||!U)return;const ae=U,ee=p.useDashboardStore.getState(),J=ee.reportContextSessionAccessToken===x&&((ct=ee.dashboard)==null?void 0:ct.id)===U.id&&ee.reportContext!==null,re=w??S.initialReportContext,pe=(J?(rt=ee.reportContext)==null?void 0:rt.calendar.tz:void 0)??re.calendar.tz,{filterValues:Ee,defaultLensId:Te,lenses:ze}=S;function Pe(){if(Ee&&(Ee==null?void 0:Ee.length)>0)return Ee;const Je=[...p.buildFilterValuesFromDefaults(ae.filters,pe)];if(ae.defaultFilterValues&&ae.defaultFilterValues.length>0)for(const _t of ae.defaultFilterValues){const Rt=Je.findIndex(Pt=>Pt.filterId===_t.filterId);Rt>=0?Je[Rt]=_t:Je.push(_t)}const kt=fe(ae,A||[]),mt=[...Je];for(const _t of kt){const Rt=mt.findIndex(Pt=>Pt.filterId===_t.filterId);Rt>=0?mt[Rt]=_t:mt.push(_t)}return mt}const He=G.current===U.id&&((Ct=ee.dashboard)==null?void 0:Ct.id)===U.id,ye=Pe(),Ke=He?p.resolveSameDashboardFilterValues({previousFilters:(Lt=ee.dashboard)==null?void 0:Lt.filters,nextFilters:ae.filters,currentFilterValues:ee.filterValues,defaultFilterValues:ye}):ye,We=p.computeInlineFilterDefaults(ae,pe),Qe=He&&X.current.controlContractOverridesKey===H?p.flattenRuntimeControlValues({dashboardValues:ee.controlValues,cardValuesMap:ee.cardControlValuesMap}):B.current,xe=ee.selectedSheetId;let Ve=D(),Ae=xe;Ae&&((vt=U==null?void 0:U.sheets)!=null&&vt.some(Je=>Je.id===Ae)||(Ae=null)),Ve&&((Tt=U==null?void 0:U.sheets)!=null&&Tt.some(Je=>Je.id===Ve)||(R(),Ve=null));const ke=N0e({selectedSheetId:h,preservedSelectedSheetId:Ae,defaultSheetId:Ve,sheets:U==null?void 0:U.sheets}),Be=!!a,Ie=!!(C||S!=null&&S.defaultLensId),$e=!Be&&Z.current,st=a?dR({dashboard:ae,dashboardInputValues:a.dashboardInputValues,sheetId:a.sheetId,cardId:a.cardId}):(S==null?void 0:S.inputValues)!=null?dR({dashboard:ae,dashboardInputValues:S.inputValues.dashboardInputValues}):void 0;V(ae,Ke||[],Qe,{selectedSheetId:ke,reportContext:J?void 0:re,authToken:x?{accessToken:x,refreshToken:y}:void 0,...S!=null&&S.semanticExecutionPayload?{semanticExecutionPayload:S.semanticExecutionPayload}:{},...a?{dashboardInputValues:st,dashboardInputReferenceTime:a.generatedAt}:Ie?{dashboardInputValues:st||{},dashboardInputReferenceTime:(S==null?void 0:S.inputValues)!=null?S.inputValues.generatedAt:void 0}:$e?{dashboardInputValues:{},dashboardInputReferenceTime:void 0}:{}}),c&&p.useInteractionStore.setState({interactionStates:Ks(c)}),Z.current=Be,G.current=U.id,X.current.dashboardId!==U.id&&(X.current={dashboardId:U.id,defaultControlValuesKey:W.current,controlContractOverridesKey:H}),le(We),ze&&oe(ze),Te&&me(Te)},[S,C,oe,V,me,le,A,h,D,R,H,a,c,U,x,y,w]),v.useEffect(()=>{if(!(U!=null&&U.id))return;const fe=X.current;if(fe.dashboardId!==U.id){X.current={dashboardId:U.id,defaultControlValuesKey:$,controlContractOverridesKey:H};return}fe.defaultControlValuesKey===$&&fe.controlContractOverridesKey===H||(K(U,B.current),X.current={dashboardId:U.id,defaultControlValuesKey:$,controlContractOverridesKey:H})},[U,$,H,K]),v.useEffect(()=>{m&&ue&&m(ue)},[ue,m]),v.useEffect(()=>{n&&se(n),r&&Ce(r)},[n,se,r,Ce]),{isFetching:_,isLoading:j,isError:k,refetch:T}}const hN=te.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:p.cn("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));hN.displayName="Card";const wO=te.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:p.cn("flex flex-col space-y-1.5 p-6",e),...t}));wO.displayName="CardHeader";const cb=te.forwardRef(({className:e,...t},n)=>l.jsx("h3",{ref:n,className:p.cn("text-2xl font-semibold leading-none tracking-tight",e),...t}));cb.displayName="CardTitle";const uve=te.forwardRef(({className:e,...t},n)=>l.jsx("p",{ref:n,className:p.cn("text-sm text-muted-foreground",e),...t}));uve.displayName="CardDescription";const CO=te.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:p.cn("px-6 pt-0",e),...t}));CO.displayName="CardContent";const eZ=te.forwardRef(({className:e,...t},n)=>l.jsx("div",{ref:n,className:p.cn("flex items-center p-6 pt-0",e),...t}));eZ.displayName="CardFooter";/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -635,7 +635,7 @@ You can add a description to the \`${eg}\` by passing a \`${SQ}\` component as a
|
|
|
635
635
|
|
|
636
636
|
Alternatively, you can use your own component as a description by assigning it an \`id\` and passing the same value to the \`aria-describedby\` prop in \`${eg}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component.
|
|
637
637
|
|
|
638
|
-
For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return te.useEffect(()=>{var r;document.getElementById((r=e.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},ZSe=gQ,XSe=bQ,QSe=xQ,IQ=yQ,TQ=vQ,EQ=jQ,DQ=_Q,MQ=CQ,RQ=NQ;const ff=ZSe,JSe=XSe,e1e=QSe,AQ=te.forwardRef(({className:e,...t},n)=>l.jsx(IQ,{className:p.cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));AQ.displayName=IQ.displayName;const ku=te.forwardRef(({className:e,...t},n)=>l.jsxs(e1e,{children:[l.jsx(p.PortalScope,{children:l.jsx(AQ,{})}),l.jsx(p.PortalScope,{children:l.jsx(TQ,{ref:n,className:p.cn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})})]}));ku.displayName=TQ.displayName;const _u=({className:e,...t})=>l.jsx("div",{className:p.cn("flex flex-col space-y-1 text-center sm:text-left",e),...t});_u.displayName="AlertDialogHeader";const Iu=({className:e,...t})=>l.jsx("div",{className:p.cn("flex flex-col-reverse gap-1.5 sm:flex-row sm:justify-end sm:space-x-0",e),...t});Iu.displayName="AlertDialogFooter";const Tu=te.forwardRef(({className:e,...t},n)=>l.jsx(MQ,{ref:n,className:p.cn("text-[15px] font-semibold",e),...t}));Tu.displayName=MQ.displayName;const Eu=te.forwardRef(({className:e,...t},n)=>l.jsx(RQ,{ref:n,className:p.cn("text-[13px] leading-5 text-muted-foreground",e),...t}));Eu.displayName=RQ.displayName;const Du=te.forwardRef(({className:e,...t},n)=>l.jsx(EQ,{ref:n,className:p.cn(p.buttonVariants({size:"xs"}),e),...t}));Du.displayName=EQ.displayName;const Mu=te.forwardRef(({className:e,...t},n)=>l.jsx(DQ,{ref:n,className:p.cn(p.buttonVariants({variant:"outline",size:"xs"}),e),...t}));Mu.displayName=DQ.displayName;const t1e=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 o=`${e}/management/v1/unified-users`;return await p.getRequest(o,t,r)};function Wk(e={}){var s,i,a;const{authToken:t,tokenProps:n}=It(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),o=Un({queryKey:["unified-users",e],queryFn:()=>t1e(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(c,u)=>{const d=p.getRequestErrorStatus(u);return d===401||d===403?!1:c<2},retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((s=o.data)==null?void 0:s.users)||[],userContext:(i=o.data)==null?void 0:i.userContext,total:((a=o.data)==null?void 0:a.total)||0,isLoading:o.isLoading,isError:o.isError,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}const n1e=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 o=`${e}/management/v1/groups`;return await p.getRequest(o,t,r)},r1e=async(e,t,n)=>{const r=`${e}/management/v1/groups/${n}/members`;return await p.getRequest(r,t)};function XO(e={}){var s,i,a;const{authToken:t,tokenProps:n}=It(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),o=Un({queryKey:["groups",e],queryFn:()=>n1e(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(c,u)=>{const d=p.getRequestErrorStatus(u);return d===401||d===403?!1:c<2},retryDelay:c=>Math.min(1e3*2**c,3e4),staleTime:6e4});return{groups:((s=o.data)==null?void 0:s.groups)||[],total:((i=o.data)==null?void 0:i.total)||0,hasMore:((a=o.data)==null?void 0:a.hasMore)||!1,isLoading:o.isLoading,isError:o.isError,error:o.error,isFetching:o.isFetching,refetch:o.refetch}}function o1e(e){const{authToken:t,tokenProps:n}=It(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId);return Un({queryKey:["group-members",e],queryFn:()=>r1e(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r&&!!e,retry:1,staleTime:6e4})}function s1e(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=lo.DASHBOARD,userType:o,tenantId:s}=e,i=v.useMemo(()=>({search:t,active:!0,...o?{type:o}:{},...o==="tenant"&&s?{tenantId:s}:{}}),[t,o,s]),{users:a,isLoading:c,isError:u}=Wk(i),d=JCe(r,n);return{allUsers:a,isLoadingUsers:c,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function i1e({open:e,onOpenChange:t,title:n,subtitle:r,topContent:o,children:s}){return l.jsx(Mo,{open:e,onOpenChange:t,children:l.jsxs(go,{showCloseButton:!1,className:"z-[51] flex max-h-[80vh] w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:rounded-[6px]",children:[l.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(PZ,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx(bo,{className:"truncate text-[13px] font-medium text-foreground",title:n,children:n}),l.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:r})]}),l.jsx("button",{type:"button","aria-label":"Close",onClick:()=>t(!1),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(je.X,{className:"h-3.5 w-3.5"})})]}),l.jsx("div",{className:"relative z-20 shrink-0 border-b border-border/60",children:o}),l.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:s}),l.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border/60 bg-background px-4 py-2.5",children:l.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:()=>t(!1),children:"Close"})})]})})}function Kk(e){return e==="org_broadcast"||e==="all_tenants_broadcast"||e==="tenant_broadcast"}function a1e(e){const t=e.role==="VIEWER"?"view":"edit";switch(e.entity.type){case"org_broadcast":return`Anyone in your organization can ${t}`;case"all_tenants_broadcast":return`Anyone across all tenants can ${t}`;case"tenant_broadcast":return`Anyone in ${e.entity.tenantName??"this workspace"} can ${t}`;default:return""}}function l1e({shares:e,viewerType:t}){const n=e.filter(s=>Kk(s.entity.type)),r=n.length===0,o=t==="tenant"?"Restricted — only invited people and groups in your workspace have access":"Restricted — only the people, tenants, and groups below have access";return l.jsxs("div",{className:"flex items-start gap-2 border-b border-border/60 bg-muted/40 px-4 py-2",children:[r?l.jsx(Vv,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):l.jsx(Am,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("div",{className:"min-w-0 flex-1 text-[12px] text-foreground/80",children:r?l.jsx("span",{children:o}):n.map((s,i)=>l.jsxs("span",{children:[i>0?" · ":"",a1e(s)]},s.id))})]})}const g1={VIEWER:"Viewer",EDITOR:"Editor",CONTRIBUTOR:"Contributor"},c1e={VIEWER:"Can view and use",EDITOR:"Can edit, share, and delete",CONTRIBUTOR:"Can edit but not share or delete"},u1e={org_user:"ORG",tenant_user:"TENANT USER",tenant:"TENANT",org_group:"ORG GROUP",tenant_group:"TENANT GROUP"};function QO({type:e,viewerType:t}){if(t!=="organization")return null;const n=u1e[e];return n?l.jsx("span",{className:"rounded-[4px] bg-muted px-1 py-0.5 text-[9px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:n}):null}function x0({entity:e}){return Kk(e.type)?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-background text-foreground",children:l.jsx(Am,{className:"h-3 w-3"})}):e.type==="tenant"?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] border border-border bg-background text-muted-foreground",children:l.jsx(sZ,{className:"h-3 w-3"})}):e.type==="org_group"||e.type==="tenant_group"?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] border border-border/60 bg-muted text-muted-foreground",children:l.jsx(Pk,{className:"h-3 w-3"})}):l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted text-[11px] font-medium text-foreground",children:e.initial||"?"})}function xN({value:e,onChange:t,disabled:n,includeRemove:r,onRemove:o,displayLabelOverride:s,loading:i}){const a=n||i,c=l.jsxs("button",{type:"button",disabled:a,className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[12px] text-foreground hover:bg-muted disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:bg-transparent",children:[s??g1[e],i?l.jsx(p.LoaderCircle,{className:"h-3 w-3 animate-spin text-muted-foreground"}):l.jsx(je.ChevronDown,{className:p.cn("h-3 w-3 text-muted-foreground",n&&"invisible")})]});return a?c:l.jsxs(p.Popover,{modal:!0,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:c}),l.jsxs(p.PopoverContent,{align:"end",sideOffset:4,className:"z-[60] w-56 rounded-[6px] border border-border/60 bg-popover p-1 shadow-md",children:[Object.keys(g1).map(u=>l.jsx(d1e,{label:g1[u],description:c1e[u],selected:e===u,onSelect:()=>t(u)},u)),r&&o?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"my-1 h-px bg-border/60"}),l.jsxs("button",{type:"button",onClick:o,className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left text-[13px] text-destructive hover:bg-destructive/10",children:[l.jsx(el,{className:"h-3.5 w-3.5"}),"Remove access"]})]}):null]})]})}function d1e({label:e,description:t,selected:n,onSelect:r}){return l.jsxs("button",{type:"button",onClick:r,className:"flex w-full items-start justify-between gap-2 rounded-[5px] px-2 py-1.5 text-left text-[13px] hover:bg-muted",children:[l.jsxs("div",{children:[l.jsx("div",{className:"font-medium text-foreground",children:e}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:t})]}),n?l.jsx(p.Check,{className:"mt-0.5 h-3.5 w-3.5 text-foreground"}):null]})}const f1e=5;function h1e(e){const{directory:t,groupConfig:n,excludeIds:r,placeholder:o,invites:s,defaultRole:i,onAdd:a,onRemoveInvite:c,onChangeInviteRole:u,onChangeDefaultRole:d,onSubmit:f,isSubmitting:h,viewerType:m}=e,[g,b]=v.useState(""),[x,y]=v.useState(!1),[w,C]=v.useState("all"),[N,S]=v.useState(new Set),[j,_]=v.useState(null),k=v.useRef(null),T=v.useRef(null),I=v.useRef(null),E=g.trim(),D=E.length>0,R=v.useMemo(()=>{const Y=E.toLowerCase(),O=t.filter(q=>!r.has(q.id));return Y?O.filter(q=>q.name.toLowerCase().includes(Y)||q.sublabel.toLowerCase().includes(Y)||(q.tenantName??"").toLowerCase().includes(Y)):O},[E,r,t]),A=v.useMemo(()=>{if(w==="all")return R;const Y=n.find(O=>O.key===w);return Y?R.filter(O=>Y.types.includes(O.type)):R},[R,w,n]),F=v.useMemo(()=>t.filter(Y=>Kk(Y.type)&&!r.has(Y.id)),[t,r]),z=v.useMemo(()=>{const Y={all:R.length};for(const O of n)Y[O.key]=R.filter(q=>O.types.includes(q.type)).length;return Y},[R,n]),L=v.useMemo(()=>t.filter(O=>O.type==="tenant").map(O=>({tenant:O,userCount:t.filter(q=>q.type==="tenant_user"&&q.tenantName===O.name).length})),[t]),$=v.useMemo(()=>j?t.find(Y=>Y.id===j&&Y.type==="tenant")??null:null,[t,j]),H=v.useMemo(()=>{if(!$)return[];const Y=E.toLowerCase();return t.filter(O=>O.type!=="tenant_user"||O.tenantName!==$.name||r.has(O.id)?!1:Y?O.name.toLowerCase().includes(Y)||O.sublabel.toLowerCase().includes(Y):!0)},[t,$,E,r]);function M(Y){b(Y),Y.trim()!==E&&S(new Set)}function B(Y){C(Y),Y!==w&&S(new Set)}function W(Y){var O;a(Y),M(""),!(j&&Y.type==="tenant_user")&&(B("all"),S(new Set),_(null),(O=k.current)==null||O.focus())}function P(Y){_(Y),M(""),B("all"),S(new Set)}function G(){var Y;_(null),M(""),(Y=k.current)==null||Y.focus()}function Z(Y){var O;if(Y.key==="Backspace"&&g.length===0){if(j){G(),Y.preventDefault();return}s.length>0&&c(s[s.length-1].entity.id)}else Y.key==="Escape"&&((O=k.current)==null||O.blur())}function X(Y){S(O=>{const q=new Set(O);return q.has(Y)?q.delete(Y):q.add(Y),q})}return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(p.Popover,{open:x,onOpenChange:y,modal:!1,children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx(p.Anchor2,{asChild:!0,children:l.jsx("div",{ref:T,className:"flex-1",children:l.jsx(m1e,{ref:k,placeholder:$?`Filter ${$.name} users…`:o,query:g,onQueryChange:Y=>{M(Y),y(!0)},onFocus:()=>y(!0),onKeyDown:Z})})}),l.jsx(p1e,{value:i,onChange:d}),l.jsx(p.Button,{type:"button",size:"xs",onClick:f,disabled:s.length===0||h,children:h?"Sharing…":"Share"})]}),l.jsx(p.Portal$1,{children:l.jsx(p.PortalScope,{children:l.jsxs(p.Content2,{ref:I,align:"start",sideOffset:4,onOpenAutoFocus:Y=>Y.preventDefault(),onCloseAutoFocus:Y=>Y.preventDefault(),onPointerDownOutside:Y=>{var q;const O=Y.target;O instanceof Node&&((q=T.current)!=null&&q.contains(O))&&Y.preventDefault()},onInteractOutside:Y=>{var q;const O=Y.target;O instanceof Node&&((q=T.current)!=null&&q.contains(O))&&Y.preventDefault()},onWheel:Y=>Y.stopPropagation(),onTouchMove:Y=>Y.stopPropagation(),className:p.cn("pointer-events-auto z-[60] flex flex-col w-[var(--radix-popover-trigger-width)] min-w-[360px]","max-h-[min(360px,var(--radix-popover-content-available-height))]","overflow-hidden rounded-[6px] border border-border/60 bg-popover 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"),children:[$?l.jsx(g1e,{tenant:$,userCount:H.length,onBack:G}):n.length>1?l.jsx(b1e,{groupConfig:n,groupCounts:z,activeFilter:w,onChangeFilter:B}):null,l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain p-1",onWheel:Y=>Y.stopPropagation(),onTouchMove:Y=>Y.stopPropagation(),children:l.jsx(y1e,{drilledInTenant:$,drilledInTenantUsers:H,hasQuery:D,query:E,activeFilter:w,groupConfig:n,filteredMatches:A,broadcastItems:F,tenantsWithUserCounts:L,expandedGroups:N,directory:t,viewerType:m,onPick:W,onDrillInto:P,onToggleExpand:X})})]})})})]}),s.length>0&&l.jsx(w1e,{invites:s,viewerType:m,onChangeRole:u,onRemove:c})]})}const m1e=({ref:e,placeholder:t,query:n,onQueryChange:r,onFocus:o,onKeyDown:s})=>l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-input bg-background px-2 focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/10",onClick:()=>{var i;return(i=e.current)==null?void 0:i.focus()},children:[l.jsx(Ft.Search,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("input",{ref:e,type:"text",value:n,onChange:i=>r(i.target.value),onFocus:o,onKeyDown:s,placeholder:t,className:"h-full flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted-foreground"})]});function p1e({value:e,onChange:t}){return l.jsx("div",{className:"flex h-7 shrink-0 items-center rounded-[5px] border border-input bg-background px-1",children:l.jsx(xN,{value:e,onChange:t})})}function g1e({tenant:e,userCount:t,onBack:n}){return l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 border-b border-border/60 px-2 py-1.5",children:[l.jsxs("button",{type:"button",onClick:n,"aria-label":"Back",className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Mm,{className:"h-3 w-3"}),"Back"]}),l.jsx("span",{className:"text-muted-foreground/70",children:"·"}),l.jsx(sZ,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("span",{className:"text-[12px] font-medium text-foreground",children:e.name}),l.jsxs("span",{className:"text-[11px] text-muted-foreground/70",children:["· ",t," ",t===1?"user":"users"]})]})}function b1e({groupConfig:e,groupCounts:t,activeFilter:n,onChangeFilter:r}){return l.jsx("div",{className:"flex shrink-0 items-center gap-1 overflow-x-auto border-b border-border/60 bg-popover px-2 py-1.5",children:e.map(o=>{const s=t[o.key]??0;if(s===0)return null;const i=n===o.key;return l.jsx(x1e,{label:o.pillLabel,count:s,active:i,onClick:()=>r(i?"all":o.key)},o.key)})})}function x1e({label:e,count:t,active:n,onClick:r}){return l.jsxs("button",{type:"button",onClick:r,className:p.cn("inline-flex h-6 shrink-0 items-center gap-1 rounded-[4px] px-2 text-[11px] transition-colors",n?"bg-foreground text-background":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e,typeof t=="number"?l.jsx("span",{className:p.cn("tabular-nums",n?"text-background/70":"text-muted-foreground/70"),children:t}):null]})}function y1e(e){const{drilledInTenant:t,drilledInTenantUsers:n,hasQuery:r,query:o,activeFilter:s,groupConfig:i,filteredMatches:a,broadcastItems:c,tenantsWithUserCounts:u,expandedGroups:d,directory:f,viewerType:h,onPick:m,onDrillInto:g,onToggleExpand:b}=e;return t?l.jsxs(l.Fragment,{children:[l.jsxs("button",{type:"button",onClick:()=>m(t),className:"mb-2 flex w-full items-center gap-2 rounded-[5px] border border-dashed border-border/60 px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(x0,{entity:t}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"truncate text-[13px] text-foreground",children:["Share ",l.jsx("strong",{className:"font-medium",children:t.name})," ","as a whole tenant instead"]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:"Grants every user in the workspace, present and future"})]}),l.jsx(Ft.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]}),n.length===0?l.jsx("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:r?`No matches for "${o}" inside ${t.name}.`:`No users in ${t.name} to browse.`}):l.jsx(GT,{label:`Users in ${t.name}`,items:n,viewerType:h,onPick:m})]}):!r&&s==="tenant_users"&&u.length>0?l.jsxs("div",{children:[l.jsx("div",{className:"px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Browse by tenant"}),u.map(({tenant:x,userCount:y})=>l.jsxs("button",{type:"button",onClick:()=>g(x.id),className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(x0,{entity:x}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[13px] text-foreground",children:x.name}),l.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[y," ",y===1?"user":"users"]})]}),l.jsx(Ft.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]},x.id)),l.jsx("div",{className:"mt-1 border-t border-border/60 px-2 py-2 text-[11px] text-muted-foreground/80",children:"Click a tenant to filter to its users, or start typing to search across all tenants."})]}):!r&&s==="all"?l.jsxs(l.Fragment,{children:[c.length>0&&l.jsx(GT,{label:"General access",items:c,viewerType:h,onPick:m}),l.jsx("div",{className:"mt-1 border-t border-border/60 px-2 py-2 text-[11px] text-muted-foreground/80",children:"Type to search, or pick a category above to browse."})]}):a.length===0?l.jsx("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:r?`No matches for "${o}".`:"Nothing to browse in this category."}):l.jsx(l.Fragment,{children:i.map(x=>{if(s!=="all"&&s!==x.key)return null;const y=a.filter(S=>x.types.includes(S.type));if(y.length===0)return null;const w=d.has(x.key),C=s===x.key||w?y:y.slice(0,f1e),N=y.length-C.length;return x.key==="tenant_users"?l.jsx(v1e,{label:x.label,items:y,visible:C,hiddenCount:N,directory:f,viewerType:h,onPick:m,onDrillInto:g,onToggleExpand:()=>b(x.key)},x.key):l.jsx(GT,{label:x.label,count:y.length,items:C,viewerType:h,onPick:m,showMoreCount:N,onShowMore:()=>b(x.key)},x.key)})})}function v1e({label:e,items:t,visible:n,hiddenCount:r,directory:o,viewerType:s,onPick:i,onDrillInto:a,onToggleExpand:c}){const u=v.useMemo(()=>{const d=new Map;for(const f of n){const h=f.tenantName??"—";d.has(h)||d.set(h,[]),d.get(h).push(f)}return d},[n]);return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between px-2 pb-1 pt-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),t.length>n.length?l.jsxs("span",{className:"text-[10px] text-muted-foreground/70",children:[n.length,"/",t.length]}):null]}),Array.from(u.entries()).map(([d,f])=>{const h=o.find(m=>m.type==="tenant"&&m.name===d);return l.jsxs("div",{className:"mb-1",children:[l.jsxs("div",{className:"flex items-center justify-between px-2 py-0.5",children:[l.jsx("span",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground",children:d}),h?l.jsx("button",{type:"button",onClick:()=>a(h.id),className:"text-[10px] text-muted-foreground hover:text-foreground",children:"Browse all →"}):null]}),f.map(m=>l.jsx(PQ,{entity:m,viewerType:s,onPick:()=>i(m)},m.id))]},d)}),r>0?l.jsxs("button",{type:"button",onClick:c,className:"mt-0.5 flex w-full items-center gap-1 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Ft.ChevronRight,{className:"h-3 w-3"}),"Show ",r," more"]}):null]})}function GT({label:e,count:t,items:n,viewerType:r,onPick:o,showMoreCount:s,onShowMore:i}){return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between px-2 pb-1 pt-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),typeof t=="number"&&t>n.length?l.jsxs("span",{className:"text-[10px] text-muted-foreground/70",children:[n.length,"/",t]}):null]}),n.map(a=>l.jsx(PQ,{entity:a,viewerType:r,onPick:()=>o(a)},a.id)),s&&s>0&&i?l.jsxs("button",{type:"button",onClick:i,className:"mt-0.5 flex w-full items-center gap-1 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Ft.ChevronRight,{className:"h-3 w-3"}),"Show ",s," more"]}):null]})}function PQ({entity:e,viewerType:t,onPick:n}){return l.jsxs("button",{type:"button",onClick:n,className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(x0,{entity:e}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:e.name}),l.jsx(QO,{type:e.type,viewerType:t}),t==="organization"&&e.tenantName?l.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground/70",children:["· ",e.tenantName]}):null]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:e.sublabel})]})]})}function w1e({invites:e,viewerType:t,onChangeRole:n,onRemove:r}){return l.jsx("div",{className:"space-y-0.5 rounded-[5px] bg-muted/40 px-1 py-1",children:e.map(o=>l.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[l.jsx(x0,{entity:o.entity}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:o.entity.name}),l.jsx(QO,{type:o.entity.type,viewerType:t})]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t==="organization"&&o.entity.tenantName?`${o.entity.sublabel} · ${o.entity.tenantName}`:o.entity.sublabel||(Kk(o.entity.type)?`Will be granted as ${g1[o.role]}`:"")})]}),l.jsx(xN,{value:o.role,onChange:s=>n(o.entity.id,s)}),l.jsx("button",{type:"button",onClick:()=>r(o.entity.id),"aria-label":"Remove",className:"flex h-6 w-6 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(je.X,{className:"h-3.5 w-3.5"})})]},o.entity.id))})}function C1e({shares:e,sections:t,onChangeRole:n,onRemove:r,viewerType:o,pendingShareIds:s}){return l.jsx("div",{className:"space-y-3",children:t.map(i=>{const a=e.filter(c=>i.matches(c.entity));return a.length===0&&!i.emptyLabel?null:l.jsxs("section",{className:"space-y-0.5",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5 px-2 py-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[l.jsx("span",{children:i.label}),l.jsxs("span",{className:"text-muted-foreground/70",children:["· ",a.length]})]}),a.length===0?l.jsx("p",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:i.emptyLabel}):a.map(c=>l.jsx(S1e,{share:c,viewerType:o,loading:s.has(c.id),onChangeRole:u=>n(c,u),onRemove:()=>r(c)},c.id))]},i.label)})})}function S1e({share:e,viewerType:t,loading:n,onChangeRole:r,onRemove:o}){return l.jsxs("div",{className:"group flex items-center gap-2 rounded-[5px] px-2 py-1.5 hover:bg-muted/40",children:[l.jsx(x0,{entity:e.entity}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:e.entity.name}),e.isSelf?l.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(you)"}):l.jsx(QO,{type:e.entity.type,viewerType:t})]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t==="organization"&&e.entity.tenantName?`${e.entity.sublabel} · ${e.entity.tenantName}`:e.entity.sublabel})]}),e.isSelf?l.jsx(xN,{value:e.role,onChange:()=>{},disabled:!0,displayLabelOverride:"Owner"}):l.jsx(xN,{value:e.role,onChange:r,includeRemove:!0,onRemove:o,loading:n})]})}function $m(e){if(!e)return"?";const t=e.trim();return t?t.charAt(0).toUpperCase():"?"}function FQ(e){const t=e.type==="organization",n=e.name||e.email||"Unknown user";return{id:e.id,type:t?"org_user":"tenant_user",name:n,sublabel:e.email||"",initial:$m(n),tenantId:e.tenantId,tenantName:e.tenantName}}function OQ(e){return{id:e.id,type:e.type==="ORG_GROUP"?"org_group":"tenant_group",name:e.name,sublabel:e.memberCount!==void 0?`${e.memberCount} member${e.memberCount===1?"":"s"}`:e.description||"",initial:$m(e.name),tenantId:e.tenantId??void 0,tenantName:e.tenantName??void 0}}function N1e(e){return{id:e.id,type:"tenant",name:e.name,sublabel:"Tenant workspace",initial:$m(e.name),tenantId:e.id,tenantName:e.name}}const LQ={id:"__broadcast:org",type:"org_broadcast",name:"Everyone in the organization",sublabel:"Any user in your organization can open this dashboard",initial:""},$Q={id:"__broadcast:all-tenants",type:"all_tenants_broadcast",name:"Everyone across all tenants",sublabel:"Every tenant user in every tenant can open this dashboard",initial:""};function zQ(e){return{id:"__broadcast:tenant",type:"tenant_broadcast",name:e.tenantName?`Everyone in ${e.tenantName}`:"Everyone in your workspace",sublabel:"Anyone who can sign in to your workspace can open this dashboard",tenantId:e.tenantId,tenantName:e.tenantName,initial:""}}function j1e(e){return[LQ,$Q,...e.users.map(FQ),...e.tenants.map(N1e),...e.groups.map(OQ)]}function k1e(e){var n,r;return[zQ({tenantId:(n=e.currentUser)==null?void 0:n.tenantId,tenantName:(r=e.currentUser)==null?void 0:r.tenantName}),...e.users.filter(o=>o.type==="tenant").map(FQ),...e.groups.filter(o=>o.type==="TENANT_GROUP").map(OQ)]}function _1e({existingShares:e,userDirectory:t,groupDirectory:n,tenantDirectory:r,currentUser:o}){if(!(e!=null&&e.shares))return[];const s=new Map(t.map(f=>[f.id,f])),i=new Map(n.map(f=>[f.id,f])),a=new Map(r.map(f=>[f.id,f])),c=[];(e.shares.specificOrgUsers??[]).forEach(f=>c.push(I1e(f,s,o))),(e.shares.specificTenantUsers??[]).forEach(f=>c.push(T1e(f,s,o))),(e.shares.tenantWide??[]).forEach(f=>c.push(E1e(f,a)));const u=[...e.shares.specificGroups??[],...e.shares.groups??[]],d=new Set;if(u.forEach(f=>{d.has(f.id)||(d.add(f.id),c.push(D1e(f,i)))}),(o==null?void 0:o.type)==="organization"&&((e.shares.orgUsersOnly??[]).forEach(f=>c.push(M1e(f))),(e.shares.allTenantsOnly??[]).forEach(f=>c.push(R1e(f)))),(o==null?void 0:o.type)==="tenant"&&o.tenantId){const f=(e.shares.tenantWide??[]).find(h=>h.tenantId===o.tenantId);if(f){const h=c.findIndex(m=>m.id===f.id&&m.entity.type==="tenant");h>=0&&c.splice(h,1),c.push(A1e(f,o.tenantName))}}return(e.shares.allOrgGroups??[]).forEach(f=>c.push(P1e(f))),(e.shares.allTenantGroups??[]).forEach(f=>c.push(F1e(f))),c}function I1e(e,t,n){var i,a,c;const r=t.get(e.orgUserId),o=((i=e.user)==null?void 0:i.name)||(r==null?void 0:r.name)||((a=e.user)==null?void 0:a.email)||"Org user",s=((c=e.user)==null?void 0:c.email)||(r==null?void 0:r.email)||"";return{id:e.id,role:e.role,isSelf:(n==null?void 0:n.id)===e.orgUserId,entity:{id:e.orgUserId,type:"org_user",name:o,sublabel:s,initial:$m(o)}}}function T1e(e,t,n){var i,a,c,u,d;const r=t.get(e.tenantUserId),o=((i=e.user)==null?void 0:i.name)||(r==null?void 0:r.name)||((a=e.user)==null?void 0:a.email)||"Tenant user",s=((c=e.user)==null?void 0:c.email)||(r==null?void 0:r.email)||"";return{id:e.id,role:e.role,isSelf:(n==null?void 0:n.id)===e.tenantUserId,entity:{id:e.tenantUserId,type:"tenant_user",name:o,sublabel:s,initial:$m(o),tenantId:e.tenantId??((u=e.tenant)==null?void 0:u.id),tenantName:(d=e.tenant)==null?void 0:d.name}}}function E1e(e,t){var o;const n=e.tenantId?t.get(e.tenantId):void 0,r=((o=e.tenant)==null?void 0:o.name)||(n==null?void 0:n.name)||"Tenant";return{id:e.id,role:e.role,entity:{id:e.tenantId??e.id,type:"tenant",name:r,sublabel:"All users in this tenant",initial:$m(r),tenantId:e.tenantId,tenantName:r}}}function D1e(e,t){var a,c,u;const n=t.get(e.groupId),r=((a=e.group)==null?void 0:a.name)||(n==null?void 0:n.name)||"Group",s=(((c=e.group)==null?void 0:c.type)||(n==null?void 0:n.type))==="ORG_GROUP",i=((u=e.group)==null?void 0:u.memberCount)??(n==null?void 0:n.memberCount);return{id:e.id,role:e.role,entity:{id:e.groupId,type:s?"org_group":"tenant_group",name:r,sublabel:i!==void 0?`${i} member${i===1?"":"s"}`:"",initial:$m(r),tenantId:(n==null?void 0:n.tenantId)??void 0}}}function M1e(e){return{id:e.id,role:e.role,entity:{...LQ}}}function R1e(e){return{id:e.id,role:e.role,entity:{...$Q}}}function A1e(e,t){var r;const n=zQ({tenantId:e.tenantId,tenantName:t??((r=e.tenant)==null?void 0:r.name)});return{id:e.id,role:e.role,entity:n}}function P1e(e){return{id:e.id,role:e.role,entity:{id:`__all_org_groups:${e.id}`,type:"org_group",name:"All organization groups",sublabel:"Every org group",initial:"G"}}}function F1e(e){return{id:e.id,role:e.role,entity:{id:`__all_tenant_groups:${e.id}`,type:"tenant_group",name:"All tenant groups",sublabel:"Every tenant group",initial:"G"}}}function O1e(e,t){switch(e.type){case"org_user":return{scope:"specific_org_user",orgUserId:e.id,role:t};case"tenant_user":return{scope:"specific_tenant_user",tenantUserId:e.id,tenantId:e.tenantId,role:t};case"tenant":return{scope:"all_tenant_users",tenantId:e.id,role:t};case"org_group":case"tenant_group":return{scope:"group",groupId:e.id,role:t};case"org_broadcast":return{scope:"org_users_only",role:t};case"all_tenants_broadcast":return{scope:"all_tenants_only",role:t};case"tenant_broadcast":return{scope:"all_tenant_users",tenantId:e.tenantId,role:t}}}function L1e(e){return e.invites.length===0?null:{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:e.invites.map(t=>O1e(t.entity,t.role))}}}function $1e(e){return{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:[BQ(e.share,e.newRole,e.existingShares)]}}}function z1e(e){return{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:[BQ(e.share,e.share.role,e.existingShares)]}}}function BQ(e,t,n){if(e.entity.type==="org_broadcast")return{scope:"org_users_only",role:t};if(e.entity.type==="all_tenants_broadcast")return{scope:"all_tenants_only",role:t};if(e.entity.type==="tenant_broadcast")return{scope:"all_tenant_users",tenantId:e.entity.tenantId,role:t};if(e.entity.id.startsWith("__all_org_groups:"))return{scope:"all_org_groups",role:t};if(e.entity.id.startsWith("__all_tenant_groups:"))return{scope:"all_tenant_groups",role:t};switch(e.entity.type){case"org_user":{const r=((n==null?void 0:n.shares.specificOrgUsers)??[]).find(o=>o.orgUserId===e.entity.id);return{scope:"specific_org_user",orgUserId:(r==null?void 0:r.orgUserId)??e.entity.id,role:t}}case"tenant_user":{const r=((n==null?void 0:n.shares.specificTenantUsers)??[]).find(o=>o.tenantUserId===e.entity.id);return{scope:"specific_tenant_user",tenantUserId:(r==null?void 0:r.tenantUserId)??e.entity.id,tenantId:(r==null?void 0:r.tenantId)??e.entity.tenantId,role:t}}case"tenant":{const r=((n==null?void 0:n.shares.tenantWide)??[]).find(o=>o.tenantId===e.entity.id);return{scope:"all_tenant_users",tenantId:(r==null?void 0:r.tenantId)??e.entity.id,role:t}}case"org_group":case"tenant_group":{const o=[...(n==null?void 0:n.shares.specificGroups)??[],...(n==null?void 0:n.shares.groups)??[]].find(s=>s.groupId===e.entity.id);return{scope:"group",groupId:(o==null?void 0:o.groupId)??e.entity.id,role:t}}}}function $B(e){const{open:t,resource:n,resourceType:r,currentUser:o,config:s,onClose:i}=e,[a,c]=v.useState([]),[u,d]=v.useState("VIEWER"),[f,h]=v.useState(()=>new Set),[m,g]=v.useState(!1);function b($){h(H=>{const M=new Set(H);return M.add($),M})}function x($){h(H=>{const M=new Set(H);return M.delete($),M})}const y=Wk({type:s.unifiedUsersType,limit:50}),w=XO({type:s.groupsType,limit:50}),C=YCe({enabled:s.fetchTenants}),N=v.useMemo(()=>{if(!s.fetchTenants)return[];const $=C.data;return($==null?void 0:$.tenants)??[]},[s.fetchTenants,C.data]),{existingShares:S}=s1e({debouncedSearchQuery:"",resourceId:(n==null?void 0:n.id)||"",resourceType:r,userType:(o==null?void 0:o.type)??"tenant"}),j=VX(),_=HX(),k=v.useMemo(()=>s.buildDirectory({users:y.users,groups:w.groups,tenants:N,currentUser:o}),[s,y.users,w.groups,N,o]),T=v.useMemo(()=>_1e({existingShares:S,userDirectory:y.users,groupDirectory:w.groups,tenantDirectory:N,currentUser:o}),[S,y.users,w.groups,N,o]),I=v.useMemo(()=>new Set([...a.map($=>$.entity.id),...T.map($=>$.entity.id)]),[a,T]);function E($){c(H=>[...H,{entity:$,role:u}])}function D($){c(H=>H.filter(M=>M.entity.id!==$))}function R($,H){c(M=>M.map(B=>B.entity.id===$?{...B,role:H}:B))}function A(){const $=L1e({resourceType:r,resourceId:n.id,invites:a});$&&(g(!0),j.mutate($,{onSuccess:()=>c([]),onSettled:()=>g(!1)}))}function F($,H){const M=$1e({resourceType:r,resourceId:n.id,share:$,newRole:H,existingShares:S});b($.id),j.mutate(M,{onSettled:()=>x($.id)})}function z($){const H=z1e({resourceType:r,resourceId:n.id,share:$,existingShares:S});b($.id),_.mutate(H,{onSettled:()=>x($.id)})}const L=r==="visual"?"VISUAL":"DASHBOARD";return l.jsx(i1e,{open:t,onOpenChange:$=>{$||i()},title:`Share "${(n==null?void 0:n.title)??"resource"}"`,subtitle:L,topContent:l.jsxs(l.Fragment,{children:[l.jsx(l1e,{shares:T,viewerType:o==null?void 0:o.type}),l.jsx("div",{className:"px-4 py-3",children:l.jsx(h1e,{directory:k,groupConfig:s.groupConfig,excludeIds:I,placeholder:s.invitePlaceholder,invites:a,defaultRole:u,onChangeDefaultRole:d,onAdd:E,onRemoveInvite:D,onChangeInviteRole:R,onSubmit:A,isSubmitting:m,viewerType:o==null?void 0:o.type})})]}),children:l.jsx(C1e,{shares:T,sections:s.sections,onChangeRole:F,onRemove:z,viewerType:o==null?void 0:o.type,pendingShareIds:f})})}const B1e={buildDirectory:({users:e,groups:t,tenants:n})=>j1e({users:e,groups:t,tenants:n??[]}),groupConfig:[{key:"general",pillLabel:"General",label:"General access",types:["org_broadcast","all_tenants_broadcast"]},{key:"org_users",pillLabel:"People",label:"Org users",types:["org_user"]},{key:"tenants",pillLabel:"Tenants",label:"Tenants (whole workspace)",types:["tenant"]},{key:"tenant_users",pillLabel:"Tenant users",label:"Tenant users",types:["tenant_user"]},{key:"groups",pillLabel:"Groups",label:"Groups",types:["org_group","tenant_group"]}],sections:[{label:"General access",matches:e=>e.type==="org_broadcast"||e.type==="all_tenants_broadcast"},{label:"People with access",matches:e=>e.type==="org_user"||e.type==="tenant_user",emptyLabel:"No individual people have been added."},{label:"Tenants with access",matches:e=>e.type==="tenant"},{label:"Groups with access",matches:e=>e.type==="org_group"||e.type==="tenant_group"}],fetchTenants:!0,invitePlaceholder:"Add people, tenants, groups, or broadcast access…",unifiedUsersType:"all",groupsType:"all"};function V1e(e){return{buildDirectory:({users:t,groups:n,currentUser:r})=>k1e({users:t,groups:n,currentUser:r}),groupConfig:[{key:"general",pillLabel:"General",label:"General access",types:["tenant_broadcast"]},{key:"people",pillLabel:"People",label:"People in your workspace",types:["tenant_user"]},{key:"groups",pillLabel:"Groups",label:"Groups",types:["tenant_group"]}],sections:[{label:"General access",matches:t=>t.type==="tenant_broadcast"},{label:"People with access",matches:t=>t.type==="tenant_user",emptyLabel:"No teammates have been added yet."},{label:"Groups with access",matches:t=>t.type==="tenant_group"}],fetchTenants:!1,invitePlaceholder:"Add teammates, groups, or broadcast access…",unifiedUsersType:"tenant",groupsType:"TENANT_GROUP"}}function VQ({resource:e,resourceType:t,onClose:n}){const{currentUser:r}=ti();return(r==null?void 0:r.type)==="organization"?l.jsx($B,{open:!0,resource:e,resourceType:t,currentUser:r,config:B1e,onClose:n}):l.jsx($B,{open:!0,resource:e,resourceType:t,currentUser:r,config:V1e(),onClose:n})}const H1e=p.cva("flex w-full rounded-control border border-input bg-background placeholder:text-muted-foreground focus-visible:border-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",{variants:{size:{default:"min-h-[80px] px-3 py-2 text-sm",sm:"min-h-[60px] px-2.5 py-1.5 text-[13px]",xs:"min-h-[48px] px-2 py-1 text-[12px]"}},defaultVariants:{size:"default"}}),zm=te.forwardRef(({className:e,size:t,...n},r)=>l.jsx("textarea",{className:p.cn(H1e({size:t,className:e})),ref:r,...n}));zm.displayName="Textarea";function HQ({open:e,resourceLabel:t,initialTitle:n,initialDescription:r="",onClose:o,onSave:s,isSaving:i=!1}){const[a,c]=v.useState(n),[u,d]=v.useState(r??"");v.useEffect(()=>{e&&(c(n),d(r??""))},[e,n,r]);const f=h=>{h.preventDefault();const m=a.trim();m&&s({title:m,description:u.trim()})};return l.jsx(Mo,{open:e,onOpenChange:h=>h?null:o(),children:l.jsx(go,{className:"sm:max-w-md",children:l.jsxs("form",{onSubmit:f,className:"space-y-4",children:[l.jsxs(Is,{children:[l.jsxs(bo,{children:["Edit ",t]}),l.jsxs(Ro,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(p.Label,{htmlFor:"resource-title",children:"Title"}),l.jsx(p.Input,{id:"resource-title",value:a,onChange:h=>c(h.target.value),placeholder:`Enter ${t.toLowerCase()} title`,autoFocus:!0})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(p.Label,{htmlFor:"resource-description",children:"Description"}),l.jsx(zm,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),l.jsxs(tl,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[l.jsx(p.Button,{type:"button",variant:"outline",onClick:o,disabled:i,children:"Cancel"}),l.jsx(p.Button,{type:"submit",disabled:i||!a.trim(),children:i?"Saving...":"Save changes"})]})]})})})}const q1e=Object.freeze({hasAppearance:!1,containerStyle:Object.freeze({}),controlStyle:Object.freeze({}),chipStyle:Object.freeze({}),contentStyle:Object.freeze({})});function dc(e){const{compiledAppearance:t}=p.useAppearance();return v.useMemo(()=>U1e(t),[t,e])}function U1e(e,t){const n=e.scheme.components,r=n==null?void 0:n.interactive;n==null||n.pagination;const o=r;return qQ(o,{containerBackground:r==null?void 0:r.toolbarBackground,defaultStateBackground:o==null?void 0:o.background,selectedStateBackground:e.colorValues.accent})}function qQ(e,t={}){if(!e||Object.keys(e).length===0)return q1e;const n=zB(e,t),r=zB({...e,background:t.containerBackground},{includeRadiusVariables:t.includeRadiusVariables}),o=YT({...n,backgroundColor:e.background,color:e.foreground,borderColor:e.borderColor,borderRadius:e.borderRadius,boxShadow:e.shadow}),s=YT({...r,backgroundColor:t.containerBackground,color:e.foreground,borderColor:e.borderColor,borderRadius:e.borderRadius,boxShadow:e.shadow,padding:e.padding}),i=YT({...n,color:e.foreground,borderColor:e.borderColor,borderRadius:e.borderRadius,boxShadow:e.shadow});return{hasAppearance:!0,containerStyle:s,controlStyle:o,chipStyle:i,contentStyle:o}}function zB(e,t={}){const n={},r=fx(e.background),o=fx(t.defaultStateBackground),s=fx(t.selectedStateBackground),i=fx(e.foreground),a=fx(e.borderColor);if(r&&(n["--semaphor-background"]=r,n["--semaphor-card"]=r,n["--semaphor-popover"]=r),o&&(n["--semaphor-muted"]=o),s&&(n["--semaphor-accent"]=s),i&&(n["--semaphor-foreground"]=i,n["--semaphor-card-foreground"]=i,n["--semaphor-popover-foreground"]=i,n["--semaphor-muted-foreground"]=i),a&&(n["--semaphor-border"]=a,n["--semaphor-input"]=a),e.borderRadius!==void 0){const c=W1e(e.borderRadius);t.includeRadiusVariables!==!1&&(n["--semaphor-radius"]=c,n["--semaphor-control-radius"]=c)}return n}function fx(e){return e?Bxe.compileColorToHslTriplet(e):void 0}function W1e(e){return`${Number((e/16).toFixed(4))}rem`}function YT(e){const t=Object.entries(e).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}const K1e=Object.freeze({hasDashboardAppearance:!1,hasCardAppearance:!1,dashboardContainerStyle:Object.freeze({}),dashboardCanvasStyle:Object.freeze({}),gridStyle:Object.freeze({}),cardFrameStyle:Object.freeze({}),cardGutterStyle:Object.freeze({})});function Ru(){const{compiledAppearance:e}=p.useAppearance();return v.useMemo(()=>G1e(e),[e])}function G1e(e){var w,C,N,S,j,_,k,T,I,E,D,R;const t=(w=e.scheme.components)==null?void 0:w.dashboard,n=(C=e.scheme.components)==null?void 0:C.card,r=e.scheme.tokens,o=cf.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes[e.mode].tokens,s=qQ(n,{includeRadiusVariables:!1}),i=Y1e({appearance:t,colorTokens:r==null?void 0:r.color,defaultColorTokens:o==null?void 0:o.color}),a=Object.keys(i).length>0,c=(t==null?void 0:t.padding)??yC((N=r==null?void 0:r.spacing)==null?void 0:N.dashboardPadding,(S=o==null?void 0:o.spacing)==null?void 0:S.dashboardPadding),u=yC((j=r==null?void 0:r.spacing)==null?void 0:j.gridGap,(_=o==null?void 0:o.spacing)==null?void 0:_.gridGap),d=(n==null?void 0:n.padding)??yC((k=r==null?void 0:r.spacing)==null?void 0:k.cardPadding,(T=o==null?void 0:o.spacing)==null?void 0:T.cardPadding),f=(n==null?void 0:n.borderRadius)??yC((I=r==null?void 0:r.radius)==null?void 0:I.card,(E=o==null?void 0:o.radius)==null?void 0:E.card),h=(n==null?void 0:n.shadow)??Uf((D=r==null?void 0:r.shadow)==null?void 0:D.card,(R=o==null?void 0:o.shadow)==null?void 0:R.card);if(!a&&!s.hasAppearance&&c===void 0&&u===void 0&&d===void 0&&f===void 0&&h===void 0)return K1e;const m=BB(c),g=BB(u),b=yN({...s.controlStyle,borderRadius:f,boxShadow:h}),x=yN({paddingLeft:d,paddingRight:d}),y=f!==void 0?{"--placeholder-border-radius":`${f}px`}:{};return{hasDashboardAppearance:a||c!==void 0||u!==void 0,hasCardAppearance:s.hasAppearance||d!==void 0||f!==void 0||h!==void 0,dashboardContainerStyle:i,dashboardCanvasStyle:i,gridMargin:g,gridContainerPadding:m,gridStyle:y,cardFrameStyle:b,cardGutterStyle:x}}function Y1e({appearance:e,colorTokens:t,defaultColorTokens:n}){return!e||Object.keys(e).length===0?yN({backgroundColor:Uf(t==null?void 0:t.background,n==null?void 0:n.background),color:Uf(t==null?void 0:t.foreground,n==null?void 0:n.foreground),borderColor:Uf(t==null?void 0:t.border,n==null?void 0:n.border)}):yN({backgroundColor:e.background??Uf(t==null?void 0:t.background,n==null?void 0:n.background),color:e.foreground??Uf(t==null?void 0:t.foreground,n==null?void 0:n.foreground),borderColor:e.borderColor??Uf(t==null?void 0:t.border,n==null?void 0:n.border),borderRadius:e.borderRadius,boxShadow:e.shadow})}function BB(e){return e===void 0?void 0:[e,e]}function yC(e,t){return e!==void 0&&e!==t?e:void 0}function Uf(e,t){return e!==void 0&&e!==t?e:void 0}function yN(e){const t=Object.entries(e).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}function Z1e(e){return e||"none"}function X1e(e){if(!e||e.kind!=="semantic")return;const t=e.connectionId||"",n=Z1e(e.connectionType),r=e.label||e.datasetName,o={id:e.datasetId||e.datasetName,type:"dataset",datasetType:"physical",domainId:e.domainId,label:r,description:e.description,connectionId:t,connectionType:n,database:e.database,schema:e.schema,name:e.datasetName};return{connectionId:t,connectionType:n,mode:"semanticDomain",semanticDomainId:e.domainId,selectedEntities:[o]}}function Q1e(e){const t=X1e(e.dataset);if(!t)return;const n=`dashboard_${dt.v4()}`,r=dt.v4(),o=dt.v4(),s=dt.v4(),i={id:s,title:"Title",type:"bar",connectionId:t.connectionId,dataSource:t,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},sql:"",data:[]},a={id:o,cards:[i],activeCardId:s};return{id:n,title:e.title,description:e.description,aiContext:{selectedEntities:t.selectedEntities,mode:"fixed"},sheets:[{id:r,kind:"dashboard",title:"Sheet 1",frames:[a],layouts:qxe.createFrameLayouts({id:o,x:0,y:0,w:18,initialHeight:36,minH:10})}]}}function ZT(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function J1e(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function eNe(e){const t={projectId:e.dataApp.projectId,dataAppId:e.dataApp.id,versionId:e.runtime.versionId,version:e.runtime.version,apiBaseUrl:e.apiBaseUrl.replace(/\/api\/?$/,""),dataApiBaseUrl:e.apiBaseUrl,assetsBaseUrl:e.runtime.assetsBaseUrl,manifest:e.runtime.manifest,authToken:e.runtime.authToken},n=e.runtime.styleUrls.map(r=>`<link rel="stylesheet" crossorigin="anonymous" href="${ZT(r)}">`).join(`
|
|
638
|
+
For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return te.useEffect(()=>{var r;document.getElementById((r=e.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,e]),null},ZSe=gQ,XSe=bQ,QSe=xQ,IQ=yQ,TQ=vQ,EQ=jQ,DQ=_Q,MQ=CQ,RQ=NQ;const ff=ZSe,JSe=XSe,e1e=QSe,AQ=te.forwardRef(({className:e,...t},n)=>l.jsx(IQ,{className:p.cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));AQ.displayName=IQ.displayName;const ku=te.forwardRef(({className:e,...t},n)=>l.jsxs(e1e,{children:[l.jsx(p.PortalScope,{children:l.jsx(AQ,{})}),l.jsx(p.PortalScope,{children:l.jsx(TQ,{ref:n,className:p.cn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})})]}));ku.displayName=TQ.displayName;const _u=({className:e,...t})=>l.jsx("div",{className:p.cn("flex flex-col space-y-1 text-center sm:text-left",e),...t});_u.displayName="AlertDialogHeader";const Iu=({className:e,...t})=>l.jsx("div",{className:p.cn("flex flex-col-reverse gap-1.5 sm:flex-row sm:justify-end sm:space-x-0",e),...t});Iu.displayName="AlertDialogFooter";const Tu=te.forwardRef(({className:e,...t},n)=>l.jsx(MQ,{ref:n,className:p.cn("text-[15px] font-semibold",e),...t}));Tu.displayName=MQ.displayName;const Eu=te.forwardRef(({className:e,...t},n)=>l.jsx(RQ,{ref:n,className:p.cn("text-[13px] leading-5 text-muted-foreground",e),...t}));Eu.displayName=RQ.displayName;const Du=te.forwardRef(({className:e,...t},n)=>l.jsx(EQ,{ref:n,className:p.cn(p.buttonVariants({size:"xs"}),e),...t}));Du.displayName=EQ.displayName;const Mu=te.forwardRef(({className:e,...t},n)=>l.jsx(DQ,{ref:n,className:p.cn(p.buttonVariants({variant:"outline",size:"xs"}),e),...t}));Mu.displayName=DQ.displayName;const t1e=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 o=`${e}/management/v1/unified-users`;return await p.getRequest(o,t,r)};function Wk(e={}){var s,i,a;const{authToken:t,tokenProps:n}=It(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),o=Un({queryKey:["unified-users",e],queryFn:()=>t1e(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(c,u)=>{const d=p.getRequestErrorStatus(u);return d===401||d===403?!1:c<2},retryDelay:c=>Math.min(1e3*2**c,3e4)});return{users:((s=o.data)==null?void 0:s.users)||[],userContext:(i=o.data)==null?void 0:i.userContext,total:((a=o.data)==null?void 0:a.total)||0,isLoading:o.isLoading,isError:o.isError,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}const n1e=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 o=`${e}/management/v1/groups`;return await p.getRequest(o,t,r)},r1e=async(e,t,n)=>{const r=`${e}/management/v1/groups/${n}/members`;return await p.getRequest(r,t)};function XO(e={}){var s,i,a;const{authToken:t,tokenProps:n}=It(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId),o=Un({queryKey:["groups",e],queryFn:()=>n1e(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r,retry:(c,u)=>{const d=p.getRequestErrorStatus(u);return d===401||d===403?!1:c<2},retryDelay:c=>Math.min(1e3*2**c,3e4),staleTime:6e4});return{groups:((s=o.data)==null?void 0:s.groups)||[],total:((i=o.data)==null?void 0:i.total)||0,hasMore:((a=o.data)==null?void 0:a.hasMore)||!1,isLoading:o.isLoading,isError:o.isError,error:o.error,isFetching:o.isFetching,refetch:o.refetch}}function o1e(e){const{authToken:t,tokenProps:n}=It(),r=(n==null?void 0:n.endUserId)||(n==null?void 0:n.orgUserId);return Un({queryKey:["group-members",e],queryFn:()=>r1e(n.apiServiceUrl,(t==null?void 0:t.accessToken)||"",e),enabled:!!(t!=null&&t.accessToken)&&!!r&&!!e,retry:1,staleTime:6e4})}function s1e(e){const{debouncedSearchQuery:t,resourceId:n,resourceType:r=lo.DASHBOARD,userType:o,tenantId:s}=e,i=v.useMemo(()=>({search:t,active:!0,...o?{type:o}:{},...o==="tenant"&&s?{tenantId:s}:{}}),[t,o,s]),{users:a,isLoading:c,isError:u}=Wk(i),d=JCe(r,n);return{allUsers:a,isLoadingUsers:c,isErrorLoadingUsers:u,existingShares:d.data,isLoadingShares:d.isLoading,isErrorLoadingShares:d.isError,isFetchingShares:d.isFetching}}function i1e({open:e,onOpenChange:t,title:n,subtitle:r,topContent:o,children:s}){return l.jsx(Mo,{open:e,onOpenChange:t,children:l.jsxs(go,{showCloseButton:!1,className:"z-[51] flex max-h-[80vh] w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:rounded-[6px]",children:[l.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(PZ,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx(bo,{className:"truncate text-[13px] font-medium text-foreground",title:n,children:n}),l.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:r})]}),l.jsx("button",{type:"button","aria-label":"Close",onClick:()=>t(!1),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(je.X,{className:"h-3.5 w-3.5"})})]}),l.jsx("div",{className:"relative z-20 shrink-0 border-b border-border/60",children:o}),l.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-3",children:s}),l.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border/60 bg-background px-4 py-2.5",children:l.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:()=>t(!1),children:"Close"})})]})})}function Kk(e){return e==="org_broadcast"||e==="all_tenants_broadcast"||e==="tenant_broadcast"}function a1e(e){const t=e.role==="VIEWER"?"view":"edit";switch(e.entity.type){case"org_broadcast":return`Anyone in your organization can ${t}`;case"all_tenants_broadcast":return`Anyone across all tenants can ${t}`;case"tenant_broadcast":return`Anyone in ${e.entity.tenantName??"this workspace"} can ${t}`;default:return""}}function l1e({shares:e,viewerType:t}){const n=e.filter(s=>Kk(s.entity.type)),r=n.length===0,o=t==="tenant"?"Restricted — only invited people and groups in your workspace have access":"Restricted — only the people, tenants, and groups below have access";return l.jsxs("div",{className:"flex items-start gap-2 border-b border-border/60 bg-muted/40 px-4 py-2",children:[r?l.jsx(Vv,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):l.jsx(Am,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("div",{className:"min-w-0 flex-1 text-[12px] text-foreground/80",children:r?l.jsx("span",{children:o}):n.map((s,i)=>l.jsxs("span",{children:[i>0?" · ":"",a1e(s)]},s.id))})]})}const g1={VIEWER:"Viewer",EDITOR:"Editor",CONTRIBUTOR:"Contributor"},c1e={VIEWER:"Can view and use",EDITOR:"Can edit, share, and delete",CONTRIBUTOR:"Can edit but not share or delete"},u1e={org_user:"ORG",tenant_user:"TENANT USER",tenant:"TENANT",org_group:"ORG GROUP",tenant_group:"TENANT GROUP"};function QO({type:e,viewerType:t}){if(t!=="organization")return null;const n=u1e[e];return n?l.jsx("span",{className:"rounded-[4px] bg-muted px-1 py-0.5 text-[9px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:n}):null}function x0({entity:e}){return Kk(e.type)?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border bg-background text-foreground",children:l.jsx(Am,{className:"h-3 w-3"})}):e.type==="tenant"?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] border border-border bg-background text-muted-foreground",children:l.jsx(sZ,{className:"h-3 w-3"})}):e.type==="org_group"||e.type==="tenant_group"?l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] border border-border/60 bg-muted text-muted-foreground",children:l.jsx(Pk,{className:"h-3 w-3"})}):l.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-muted text-[11px] font-medium text-foreground",children:e.initial||"?"})}function xN({value:e,onChange:t,disabled:n,includeRemove:r,onRemove:o,displayLabelOverride:s,loading:i}){const a=n||i,c=l.jsxs("button",{type:"button",disabled:a,className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[12px] text-foreground hover:bg-muted disabled:cursor-not-allowed disabled:opacity-60 disabled:hover:bg-transparent",children:[s??g1[e],i?l.jsx(p.LoaderCircle,{className:"h-3 w-3 animate-spin text-muted-foreground"}):l.jsx(je.ChevronDown,{className:p.cn("h-3 w-3 text-muted-foreground",n&&"invisible")})]});return a?c:l.jsxs(p.Popover,{modal:!0,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:c}),l.jsxs(p.PopoverContent,{align:"end",sideOffset:4,className:"z-[60] w-56 rounded-[6px] border border-border/60 bg-popover p-1 shadow-md",children:[Object.keys(g1).map(u=>l.jsx(d1e,{label:g1[u],description:c1e[u],selected:e===u,onSelect:()=>t(u)},u)),r&&o?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"my-1 h-px bg-border/60"}),l.jsxs("button",{type:"button",onClick:o,className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left text-[13px] text-destructive hover:bg-destructive/10",children:[l.jsx(el,{className:"h-3.5 w-3.5"}),"Remove access"]})]}):null]})]})}function d1e({label:e,description:t,selected:n,onSelect:r}){return l.jsxs("button",{type:"button",onClick:r,className:"flex w-full items-start justify-between gap-2 rounded-[5px] px-2 py-1.5 text-left text-[13px] hover:bg-muted",children:[l.jsxs("div",{children:[l.jsx("div",{className:"font-medium text-foreground",children:e}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:t})]}),n?l.jsx(p.Check,{className:"mt-0.5 h-3.5 w-3.5 text-foreground"}):null]})}const f1e=5;function h1e(e){const{directory:t,groupConfig:n,excludeIds:r,placeholder:o,invites:s,defaultRole:i,onAdd:a,onRemoveInvite:c,onChangeInviteRole:u,onChangeDefaultRole:d,onSubmit:f,isSubmitting:h,viewerType:m}=e,[g,b]=v.useState(""),[x,y]=v.useState(!1),[w,C]=v.useState("all"),[N,S]=v.useState(new Set),[j,_]=v.useState(null),k=v.useRef(null),T=v.useRef(null),I=v.useRef(null),E=g.trim(),D=E.length>0,R=v.useMemo(()=>{const Y=E.toLowerCase(),O=t.filter(q=>!r.has(q.id));return Y?O.filter(q=>q.name.toLowerCase().includes(Y)||q.sublabel.toLowerCase().includes(Y)||(q.tenantName??"").toLowerCase().includes(Y)):O},[E,r,t]),A=v.useMemo(()=>{if(w==="all")return R;const Y=n.find(O=>O.key===w);return Y?R.filter(O=>Y.types.includes(O.type)):R},[R,w,n]),F=v.useMemo(()=>t.filter(Y=>Kk(Y.type)&&!r.has(Y.id)),[t,r]),z=v.useMemo(()=>{const Y={all:R.length};for(const O of n)Y[O.key]=R.filter(q=>O.types.includes(q.type)).length;return Y},[R,n]),L=v.useMemo(()=>t.filter(O=>O.type==="tenant").map(O=>({tenant:O,userCount:t.filter(q=>q.type==="tenant_user"&&q.tenantName===O.name).length})),[t]),$=v.useMemo(()=>j?t.find(Y=>Y.id===j&&Y.type==="tenant")??null:null,[t,j]),H=v.useMemo(()=>{if(!$)return[];const Y=E.toLowerCase();return t.filter(O=>O.type!=="tenant_user"||O.tenantName!==$.name||r.has(O.id)?!1:Y?O.name.toLowerCase().includes(Y)||O.sublabel.toLowerCase().includes(Y):!0)},[t,$,E,r]);function M(Y){b(Y),Y.trim()!==E&&S(new Set)}function B(Y){C(Y),Y!==w&&S(new Set)}function W(Y){var O;a(Y),M(""),!(j&&Y.type==="tenant_user")&&(B("all"),S(new Set),_(null),(O=k.current)==null||O.focus())}function P(Y){_(Y),M(""),B("all"),S(new Set)}function G(){var Y;_(null),M(""),(Y=k.current)==null||Y.focus()}function Z(Y){var O;if(Y.key==="Backspace"&&g.length===0){if(j){G(),Y.preventDefault();return}s.length>0&&c(s[s.length-1].entity.id)}else Y.key==="Escape"&&((O=k.current)==null||O.blur())}function X(Y){S(O=>{const q=new Set(O);return q.has(Y)?q.delete(Y):q.add(Y),q})}return l.jsxs("div",{className:"space-y-2",children:[l.jsxs(p.Popover,{open:x,onOpenChange:y,modal:!1,children:[l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsx(p.Anchor2,{asChild:!0,children:l.jsx("div",{ref:T,className:"flex-1",children:l.jsx(m1e,{ref:k,placeholder:$?`Filter ${$.name} users…`:o,query:g,onQueryChange:Y=>{M(Y),y(!0)},onFocus:()=>y(!0),onKeyDown:Z})})}),l.jsx(p1e,{value:i,onChange:d}),l.jsx(p.Button,{type:"button",size:"xs",onClick:f,disabled:s.length===0||h,children:h?"Sharing…":"Share"})]}),l.jsx(p.Portal$1,{children:l.jsx(p.PortalScope,{children:l.jsxs(p.Content2,{ref:I,align:"start",sideOffset:4,onOpenAutoFocus:Y=>Y.preventDefault(),onCloseAutoFocus:Y=>Y.preventDefault(),onPointerDownOutside:Y=>{var q;const O=Y.target;O instanceof Node&&((q=T.current)!=null&&q.contains(O))&&Y.preventDefault()},onInteractOutside:Y=>{var q;const O=Y.target;O instanceof Node&&((q=T.current)!=null&&q.contains(O))&&Y.preventDefault()},onWheel:Y=>Y.stopPropagation(),onTouchMove:Y=>Y.stopPropagation(),className:p.cn("pointer-events-auto z-[60] flex flex-col w-[var(--radix-popover-trigger-width)] min-w-[360px]","max-h-[min(360px,var(--radix-popover-content-available-height))]","overflow-hidden rounded-[6px] border border-border/60 bg-popover 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"),children:[$?l.jsx(g1e,{tenant:$,userCount:H.length,onBack:G}):n.length>1?l.jsx(b1e,{groupConfig:n,groupCounts:z,activeFilter:w,onChangeFilter:B}):null,l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain p-1",onWheel:Y=>Y.stopPropagation(),onTouchMove:Y=>Y.stopPropagation(),children:l.jsx(y1e,{drilledInTenant:$,drilledInTenantUsers:H,hasQuery:D,query:E,activeFilter:w,groupConfig:n,filteredMatches:A,broadcastItems:F,tenantsWithUserCounts:L,expandedGroups:N,directory:t,viewerType:m,onPick:W,onDrillInto:P,onToggleExpand:X})})]})})})]}),s.length>0&&l.jsx(w1e,{invites:s,viewerType:m,onChangeRole:u,onRemove:c})]})}const m1e=({ref:e,placeholder:t,query:n,onQueryChange:r,onFocus:o,onKeyDown:s})=>l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-[5px] border border-input bg-background px-2 focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/10",onClick:()=>{var i;return(i=e.current)==null?void 0:i.focus()},children:[l.jsx(Ft.Search,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("input",{ref:e,type:"text",value:n,onChange:i=>r(i.target.value),onFocus:o,onKeyDown:s,placeholder:t,className:"h-full flex-1 bg-transparent text-[13px] text-foreground outline-none placeholder:text-muted-foreground"})]});function p1e({value:e,onChange:t}){return l.jsx("div",{className:"flex h-7 shrink-0 items-center rounded-[5px] border border-input bg-background px-1",children:l.jsx(xN,{value:e,onChange:t})})}function g1e({tenant:e,userCount:t,onBack:n}){return l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 border-b border-border/60 px-2 py-1.5",children:[l.jsxs("button",{type:"button",onClick:n,"aria-label":"Back",className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[11px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Mm,{className:"h-3 w-3"}),"Back"]}),l.jsx("span",{className:"text-muted-foreground/70",children:"·"}),l.jsx(sZ,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("span",{className:"text-[12px] font-medium text-foreground",children:e.name}),l.jsxs("span",{className:"text-[11px] text-muted-foreground/70",children:["· ",t," ",t===1?"user":"users"]})]})}function b1e({groupConfig:e,groupCounts:t,activeFilter:n,onChangeFilter:r}){return l.jsx("div",{className:"flex shrink-0 items-center gap-1 overflow-x-auto border-b border-border/60 bg-popover px-2 py-1.5",children:e.map(o=>{const s=t[o.key]??0;if(s===0)return null;const i=n===o.key;return l.jsx(x1e,{label:o.pillLabel,count:s,active:i,onClick:()=>r(i?"all":o.key)},o.key)})})}function x1e({label:e,count:t,active:n,onClick:r}){return l.jsxs("button",{type:"button",onClick:r,className:p.cn("inline-flex h-6 shrink-0 items-center gap-1 rounded-[4px] px-2 text-[11px] transition-colors",n?"bg-foreground text-background":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[e,typeof t=="number"?l.jsx("span",{className:p.cn("tabular-nums",n?"text-background/70":"text-muted-foreground/70"),children:t}):null]})}function y1e(e){const{drilledInTenant:t,drilledInTenantUsers:n,hasQuery:r,query:o,activeFilter:s,groupConfig:i,filteredMatches:a,broadcastItems:c,tenantsWithUserCounts:u,expandedGroups:d,directory:f,viewerType:h,onPick:m,onDrillInto:g,onToggleExpand:b}=e;return t?l.jsxs(l.Fragment,{children:[l.jsxs("button",{type:"button",onClick:()=>m(t),className:"mb-2 flex w-full items-center gap-2 rounded-[5px] border border-dashed border-border/60 px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(x0,{entity:t}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"truncate text-[13px] text-foreground",children:["Share ",l.jsx("strong",{className:"font-medium",children:t.name})," ","as a whole tenant instead"]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:"Grants every user in the workspace, present and future"})]}),l.jsx(Ft.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]}),n.length===0?l.jsx("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:r?`No matches for "${o}" inside ${t.name}.`:`No users in ${t.name} to browse.`}):l.jsx(GT,{label:`Users in ${t.name}`,items:n,viewerType:h,onPick:m})]}):!r&&s==="tenant_users"&&u.length>0?l.jsxs("div",{children:[l.jsx("div",{className:"px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Browse by tenant"}),u.map(({tenant:x,userCount:y})=>l.jsxs("button",{type:"button",onClick:()=>g(x.id),className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(x0,{entity:x}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[13px] text-foreground",children:x.name}),l.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[y," ",y===1?"user":"users"]})]}),l.jsx(Ft.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]},x.id)),l.jsx("div",{className:"mt-1 border-t border-border/60 px-2 py-2 text-[11px] text-muted-foreground/80",children:"Click a tenant to filter to its users, or start typing to search across all tenants."})]}):!r&&s==="all"?l.jsxs(l.Fragment,{children:[c.length>0&&l.jsx(GT,{label:"General access",items:c,viewerType:h,onPick:m}),l.jsx("div",{className:"mt-1 border-t border-border/60 px-2 py-2 text-[11px] text-muted-foreground/80",children:"Type to search, or pick a category above to browse."})]}):a.length===0?l.jsx("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:r?`No matches for "${o}".`:"Nothing to browse in this category."}):l.jsx(l.Fragment,{children:i.map(x=>{if(s!=="all"&&s!==x.key)return null;const y=a.filter(S=>x.types.includes(S.type));if(y.length===0)return null;const w=d.has(x.key),C=s===x.key||w?y:y.slice(0,f1e),N=y.length-C.length;return x.key==="tenant_users"?l.jsx(v1e,{label:x.label,items:y,visible:C,hiddenCount:N,directory:f,viewerType:h,onPick:m,onDrillInto:g,onToggleExpand:()=>b(x.key)},x.key):l.jsx(GT,{label:x.label,count:y.length,items:C,viewerType:h,onPick:m,showMoreCount:N,onShowMore:()=>b(x.key)},x.key)})})}function v1e({label:e,items:t,visible:n,hiddenCount:r,directory:o,viewerType:s,onPick:i,onDrillInto:a,onToggleExpand:c}){const u=v.useMemo(()=>{const d=new Map;for(const f of n){const h=f.tenantName??"—";d.has(h)||d.set(h,[]),d.get(h).push(f)}return d},[n]);return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between px-2 pb-1 pt-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),t.length>n.length?l.jsxs("span",{className:"text-[10px] text-muted-foreground/70",children:[n.length,"/",t.length]}):null]}),Array.from(u.entries()).map(([d,f])=>{const h=o.find(m=>m.type==="tenant"&&m.name===d);return l.jsxs("div",{className:"mb-1",children:[l.jsxs("div",{className:"flex items-center justify-between px-2 py-0.5",children:[l.jsx("span",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground",children:d}),h?l.jsx("button",{type:"button",onClick:()=>a(h.id),className:"text-[10px] text-muted-foreground hover:text-foreground",children:"Browse all →"}):null]}),f.map(m=>l.jsx(PQ,{entity:m,viewerType:s,onPick:()=>i(m)},m.id))]},d)}),r>0?l.jsxs("button",{type:"button",onClick:c,className:"mt-0.5 flex w-full items-center gap-1 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Ft.ChevronRight,{className:"h-3 w-3"}),"Show ",r," more"]}):null]})}function GT({label:e,count:t,items:n,viewerType:r,onPick:o,showMoreCount:s,onShowMore:i}){return l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between px-2 pb-1 pt-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),typeof t=="number"&&t>n.length?l.jsxs("span",{className:"text-[10px] text-muted-foreground/70",children:[n.length,"/",t]}):null]}),n.map(a=>l.jsx(PQ,{entity:a,viewerType:r,onPick:()=>o(a)},a.id)),s&&s>0&&i?l.jsxs("button",{type:"button",onClick:i,className:"mt-0.5 flex w-full items-center gap-1 rounded-[5px] px-2 py-1.5 text-left text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground",children:[l.jsx(Ft.ChevronRight,{className:"h-3 w-3"}),"Show ",s," more"]}):null]})}function PQ({entity:e,viewerType:t,onPick:n}){return l.jsxs("button",{type:"button",onClick:n,className:"flex w-full items-center gap-2 rounded-[5px] px-2 py-1.5 text-left hover:bg-muted/60",children:[l.jsx(x0,{entity:e}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:e.name}),l.jsx(QO,{type:e.type,viewerType:t}),t==="organization"&&e.tenantName?l.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground/70",children:["· ",e.tenantName]}):null]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:e.sublabel})]})]})}function w1e({invites:e,viewerType:t,onChangeRole:n,onRemove:r}){return l.jsx("div",{className:"space-y-0.5 rounded-[5px] bg-muted/40 px-1 py-1",children:e.map(o=>l.jsxs("div",{className:"flex items-center gap-2 px-2 py-1",children:[l.jsx(x0,{entity:o.entity}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:o.entity.name}),l.jsx(QO,{type:o.entity.type,viewerType:t})]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t==="organization"&&o.entity.tenantName?`${o.entity.sublabel} · ${o.entity.tenantName}`:o.entity.sublabel||(Kk(o.entity.type)?`Will be granted as ${g1[o.role]}`:"")})]}),l.jsx(xN,{value:o.role,onChange:s=>n(o.entity.id,s)}),l.jsx("button",{type:"button",onClick:()=>r(o.entity.id),"aria-label":"Remove",className:"flex h-6 w-6 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(je.X,{className:"h-3.5 w-3.5"})})]},o.entity.id))})}function C1e({shares:e,sections:t,onChangeRole:n,onRemove:r,viewerType:o,pendingShareIds:s}){return l.jsx("div",{className:"space-y-3",children:t.map(i=>{const a=e.filter(c=>i.matches(c.entity));return a.length===0&&!i.emptyLabel?null:l.jsxs("section",{className:"space-y-0.5",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5 px-2 py-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:[l.jsx("span",{children:i.label}),l.jsxs("span",{className:"text-muted-foreground/70",children:["· ",a.length]})]}),a.length===0?l.jsx("p",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:i.emptyLabel}):a.map(c=>l.jsx(S1e,{share:c,viewerType:o,loading:s.has(c.id),onChangeRole:u=>n(c,u),onRemove:()=>r(c)},c.id))]},i.label)})})}function S1e({share:e,viewerType:t,loading:n,onChangeRole:r,onRemove:o}){return l.jsxs("div",{className:"group flex items-center gap-2 rounded-[5px] px-2 py-1.5 hover:bg-muted/40",children:[l.jsx(x0,{entity:e.entity}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-1.5 text-[13px] text-foreground",children:[l.jsx("span",{className:"truncate",children:e.entity.name}),e.isSelf?l.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(you)"}):l.jsx(QO,{type:e.entity.type,viewerType:t})]}),l.jsx("div",{className:"truncate text-[11px] text-muted-foreground",children:t==="organization"&&e.entity.tenantName?`${e.entity.sublabel} · ${e.entity.tenantName}`:e.entity.sublabel})]}),e.isSelf?l.jsx(xN,{value:e.role,onChange:()=>{},disabled:!0,displayLabelOverride:"Owner"}):l.jsx(xN,{value:e.role,onChange:r,includeRemove:!0,onRemove:o,loading:n})]})}function $m(e){if(!e)return"?";const t=e.trim();return t?t.charAt(0).toUpperCase():"?"}function FQ(e){const t=e.type==="organization",n=e.name||e.email||"Unknown user";return{id:e.id,type:t?"org_user":"tenant_user",name:n,sublabel:e.email||"",initial:$m(n),tenantId:e.tenantId,tenantName:e.tenantName}}function OQ(e){return{id:e.id,type:e.type==="ORG_GROUP"?"org_group":"tenant_group",name:e.name,sublabel:e.memberCount!==void 0?`${e.memberCount} member${e.memberCount===1?"":"s"}`:e.description||"",initial:$m(e.name),tenantId:e.tenantId??void 0,tenantName:e.tenantName??void 0}}function N1e(e){return{id:e.id,type:"tenant",name:e.name,sublabel:"Tenant workspace",initial:$m(e.name),tenantId:e.id,tenantName:e.name}}const LQ={id:"__broadcast:org",type:"org_broadcast",name:"Everyone in the organization",sublabel:"Any user in your organization can open this dashboard",initial:""},$Q={id:"__broadcast:all-tenants",type:"all_tenants_broadcast",name:"Everyone across all tenants",sublabel:"Every tenant user in every tenant can open this dashboard",initial:""};function zQ(e){return{id:"__broadcast:tenant",type:"tenant_broadcast",name:e.tenantName?`Everyone in ${e.tenantName}`:"Everyone in your workspace",sublabel:"Anyone who can sign in to your workspace can open this dashboard",tenantId:e.tenantId,tenantName:e.tenantName,initial:""}}function j1e(e){return[LQ,$Q,...e.users.map(FQ),...e.tenants.map(N1e),...e.groups.map(OQ)]}function k1e(e){var n,r;return[zQ({tenantId:(n=e.currentUser)==null?void 0:n.tenantId,tenantName:(r=e.currentUser)==null?void 0:r.tenantName}),...e.users.filter(o=>o.type==="tenant").map(FQ),...e.groups.filter(o=>o.type==="TENANT_GROUP").map(OQ)]}function _1e({existingShares:e,userDirectory:t,groupDirectory:n,tenantDirectory:r,currentUser:o}){if(!(e!=null&&e.shares))return[];const s=new Map(t.map(f=>[f.id,f])),i=new Map(n.map(f=>[f.id,f])),a=new Map(r.map(f=>[f.id,f])),c=[];(e.shares.specificOrgUsers??[]).forEach(f=>c.push(I1e(f,s,o))),(e.shares.specificTenantUsers??[]).forEach(f=>c.push(T1e(f,s,o))),(e.shares.tenantWide??[]).forEach(f=>c.push(E1e(f,a)));const u=[...e.shares.specificGroups??[],...e.shares.groups??[]],d=new Set;if(u.forEach(f=>{d.has(f.id)||(d.add(f.id),c.push(D1e(f,i)))}),(o==null?void 0:o.type)==="organization"&&((e.shares.orgUsersOnly??[]).forEach(f=>c.push(M1e(f))),(e.shares.allTenantsOnly??[]).forEach(f=>c.push(R1e(f)))),(o==null?void 0:o.type)==="tenant"&&o.tenantId){const f=(e.shares.tenantWide??[]).find(h=>h.tenantId===o.tenantId);if(f){const h=c.findIndex(m=>m.id===f.id&&m.entity.type==="tenant");h>=0&&c.splice(h,1),c.push(A1e(f,o.tenantName))}}return(e.shares.allOrgGroups??[]).forEach(f=>c.push(P1e(f))),(e.shares.allTenantGroups??[]).forEach(f=>c.push(F1e(f))),c}function I1e(e,t,n){var i,a,c;const r=t.get(e.orgUserId),o=((i=e.user)==null?void 0:i.name)||(r==null?void 0:r.name)||((a=e.user)==null?void 0:a.email)||"Org user",s=((c=e.user)==null?void 0:c.email)||(r==null?void 0:r.email)||"";return{id:e.id,role:e.role,isSelf:(n==null?void 0:n.id)===e.orgUserId,entity:{id:e.orgUserId,type:"org_user",name:o,sublabel:s,initial:$m(o)}}}function T1e(e,t,n){var i,a,c,u,d;const r=t.get(e.tenantUserId),o=((i=e.user)==null?void 0:i.name)||(r==null?void 0:r.name)||((a=e.user)==null?void 0:a.email)||"Tenant user",s=((c=e.user)==null?void 0:c.email)||(r==null?void 0:r.email)||"";return{id:e.id,role:e.role,isSelf:(n==null?void 0:n.id)===e.tenantUserId,entity:{id:e.tenantUserId,type:"tenant_user",name:o,sublabel:s,initial:$m(o),tenantId:e.tenantId??((u=e.tenant)==null?void 0:u.id),tenantName:(d=e.tenant)==null?void 0:d.name}}}function E1e(e,t){var o;const n=e.tenantId?t.get(e.tenantId):void 0,r=((o=e.tenant)==null?void 0:o.name)||(n==null?void 0:n.name)||"Tenant";return{id:e.id,role:e.role,entity:{id:e.tenantId??e.id,type:"tenant",name:r,sublabel:"All users in this tenant",initial:$m(r),tenantId:e.tenantId,tenantName:r}}}function D1e(e,t){var a,c,u;const n=t.get(e.groupId),r=((a=e.group)==null?void 0:a.name)||(n==null?void 0:n.name)||"Group",s=(((c=e.group)==null?void 0:c.type)||(n==null?void 0:n.type))==="ORG_GROUP",i=((u=e.group)==null?void 0:u.memberCount)??(n==null?void 0:n.memberCount);return{id:e.id,role:e.role,entity:{id:e.groupId,type:s?"org_group":"tenant_group",name:r,sublabel:i!==void 0?`${i} member${i===1?"":"s"}`:"",initial:$m(r),tenantId:(n==null?void 0:n.tenantId)??void 0}}}function M1e(e){return{id:e.id,role:e.role,entity:{...LQ}}}function R1e(e){return{id:e.id,role:e.role,entity:{...$Q}}}function A1e(e,t){var r;const n=zQ({tenantId:e.tenantId,tenantName:t??((r=e.tenant)==null?void 0:r.name)});return{id:e.id,role:e.role,entity:n}}function P1e(e){return{id:e.id,role:e.role,entity:{id:`__all_org_groups:${e.id}`,type:"org_group",name:"All organization groups",sublabel:"Every org group",initial:"G"}}}function F1e(e){return{id:e.id,role:e.role,entity:{id:`__all_tenant_groups:${e.id}`,type:"tenant_group",name:"All tenant groups",sublabel:"Every tenant group",initial:"G"}}}function O1e(e,t){switch(e.type){case"org_user":return{scope:"specific_org_user",orgUserId:e.id,role:t};case"tenant_user":return{scope:"specific_tenant_user",tenantUserId:e.id,tenantId:e.tenantId,role:t};case"tenant":return{scope:"all_tenant_users",tenantId:e.id,role:t};case"org_group":case"tenant_group":return{scope:"group",groupId:e.id,role:t};case"org_broadcast":return{scope:"org_users_only",role:t};case"all_tenants_broadcast":return{scope:"all_tenants_only",role:t};case"tenant_broadcast":return{scope:"all_tenant_users",tenantId:e.tenantId,role:t}}}function L1e(e){return e.invites.length===0?null:{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:e.invites.map(t=>O1e(t.entity,t.role))}}}function $1e(e){return{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:[BQ(e.share,e.newRole,e.existingShares)]}}}function z1e(e){return{resourceType:e.resourceType,resourceId:e.resourceId,data:{shares:[BQ(e.share,e.share.role,e.existingShares)]}}}function BQ(e,t,n){if(e.entity.type==="org_broadcast")return{scope:"org_users_only",role:t};if(e.entity.type==="all_tenants_broadcast")return{scope:"all_tenants_only",role:t};if(e.entity.type==="tenant_broadcast")return{scope:"all_tenant_users",tenantId:e.entity.tenantId,role:t};if(e.entity.id.startsWith("__all_org_groups:"))return{scope:"all_org_groups",role:t};if(e.entity.id.startsWith("__all_tenant_groups:"))return{scope:"all_tenant_groups",role:t};switch(e.entity.type){case"org_user":{const r=((n==null?void 0:n.shares.specificOrgUsers)??[]).find(o=>o.orgUserId===e.entity.id);return{scope:"specific_org_user",orgUserId:(r==null?void 0:r.orgUserId)??e.entity.id,role:t}}case"tenant_user":{const r=((n==null?void 0:n.shares.specificTenantUsers)??[]).find(o=>o.tenantUserId===e.entity.id);return{scope:"specific_tenant_user",tenantUserId:(r==null?void 0:r.tenantUserId)??e.entity.id,tenantId:(r==null?void 0:r.tenantId)??e.entity.tenantId,role:t}}case"tenant":{const r=((n==null?void 0:n.shares.tenantWide)??[]).find(o=>o.tenantId===e.entity.id);return{scope:"all_tenant_users",tenantId:(r==null?void 0:r.tenantId)??e.entity.id,role:t}}case"org_group":case"tenant_group":{const o=[...(n==null?void 0:n.shares.specificGroups)??[],...(n==null?void 0:n.shares.groups)??[]].find(s=>s.groupId===e.entity.id);return{scope:"group",groupId:(o==null?void 0:o.groupId)??e.entity.id,role:t}}}}function $B(e){const{open:t,resource:n,resourceType:r,currentUser:o,config:s,onClose:i}=e,[a,c]=v.useState([]),[u,d]=v.useState("VIEWER"),[f,h]=v.useState(()=>new Set),[m,g]=v.useState(!1);function b($){h(H=>{const M=new Set(H);return M.add($),M})}function x($){h(H=>{const M=new Set(H);return M.delete($),M})}const y=Wk({type:s.unifiedUsersType,limit:50}),w=XO({type:s.groupsType,limit:50}),C=YCe({enabled:s.fetchTenants}),N=v.useMemo(()=>{if(!s.fetchTenants)return[];const $=C.data;return($==null?void 0:$.tenants)??[]},[s.fetchTenants,C.data]),{existingShares:S}=s1e({debouncedSearchQuery:"",resourceId:(n==null?void 0:n.id)||"",resourceType:r,userType:(o==null?void 0:o.type)??"tenant"}),j=VX(),_=HX(),k=v.useMemo(()=>s.buildDirectory({users:y.users,groups:w.groups,tenants:N,currentUser:o}),[s,y.users,w.groups,N,o]),T=v.useMemo(()=>_1e({existingShares:S,userDirectory:y.users,groupDirectory:w.groups,tenantDirectory:N,currentUser:o}),[S,y.users,w.groups,N,o]),I=v.useMemo(()=>new Set([...a.map($=>$.entity.id),...T.map($=>$.entity.id)]),[a,T]);function E($){c(H=>[...H,{entity:$,role:u}])}function D($){c(H=>H.filter(M=>M.entity.id!==$))}function R($,H){c(M=>M.map(B=>B.entity.id===$?{...B,role:H}:B))}function A(){const $=L1e({resourceType:r,resourceId:n.id,invites:a});$&&(g(!0),j.mutate($,{onSuccess:()=>c([]),onSettled:()=>g(!1)}))}function F($,H){const M=$1e({resourceType:r,resourceId:n.id,share:$,newRole:H,existingShares:S});b($.id),j.mutate(M,{onSettled:()=>x($.id)})}function z($){const H=z1e({resourceType:r,resourceId:n.id,share:$,existingShares:S});b($.id),_.mutate(H,{onSettled:()=>x($.id)})}const L=r==="visual"?"VISUAL":"DASHBOARD";return l.jsx(i1e,{open:t,onOpenChange:$=>{$||i()},title:`Share "${(n==null?void 0:n.title)??"resource"}"`,subtitle:L,topContent:l.jsxs(l.Fragment,{children:[l.jsx(l1e,{shares:T,viewerType:o==null?void 0:o.type}),l.jsx("div",{className:"px-4 py-3",children:l.jsx(h1e,{directory:k,groupConfig:s.groupConfig,excludeIds:I,placeholder:s.invitePlaceholder,invites:a,defaultRole:u,onChangeDefaultRole:d,onAdd:E,onRemoveInvite:D,onChangeInviteRole:R,onSubmit:A,isSubmitting:m,viewerType:o==null?void 0:o.type})})]}),children:l.jsx(C1e,{shares:T,sections:s.sections,onChangeRole:F,onRemove:z,viewerType:o==null?void 0:o.type,pendingShareIds:f})})}const B1e={buildDirectory:({users:e,groups:t,tenants:n})=>j1e({users:e,groups:t,tenants:n??[]}),groupConfig:[{key:"general",pillLabel:"General",label:"General access",types:["org_broadcast","all_tenants_broadcast"]},{key:"org_users",pillLabel:"People",label:"Org users",types:["org_user"]},{key:"tenants",pillLabel:"Tenants",label:"Tenants (whole workspace)",types:["tenant"]},{key:"tenant_users",pillLabel:"Tenant users",label:"Tenant users",types:["tenant_user"]},{key:"groups",pillLabel:"Groups",label:"Groups",types:["org_group","tenant_group"]}],sections:[{label:"General access",matches:e=>e.type==="org_broadcast"||e.type==="all_tenants_broadcast"},{label:"People with access",matches:e=>e.type==="org_user"||e.type==="tenant_user",emptyLabel:"No individual people have been added."},{label:"Tenants with access",matches:e=>e.type==="tenant"},{label:"Groups with access",matches:e=>e.type==="org_group"||e.type==="tenant_group"}],fetchTenants:!0,invitePlaceholder:"Add people, tenants, groups, or broadcast access…",unifiedUsersType:"all",groupsType:"all"};function V1e(e){return{buildDirectory:({users:t,groups:n,currentUser:r})=>k1e({users:t,groups:n,currentUser:r}),groupConfig:[{key:"general",pillLabel:"General",label:"General access",types:["tenant_broadcast"]},{key:"people",pillLabel:"People",label:"People in your workspace",types:["tenant_user"]},{key:"groups",pillLabel:"Groups",label:"Groups",types:["tenant_group"]}],sections:[{label:"General access",matches:t=>t.type==="tenant_broadcast"},{label:"People with access",matches:t=>t.type==="tenant_user",emptyLabel:"No teammates have been added yet."},{label:"Groups with access",matches:t=>t.type==="tenant_group"}],fetchTenants:!1,invitePlaceholder:"Add teammates, groups, or broadcast access…",unifiedUsersType:"tenant",groupsType:"TENANT_GROUP"}}function VQ({resource:e,resourceType:t,onClose:n}){const{currentUser:r}=ti();return(r==null?void 0:r.type)==="organization"?l.jsx($B,{open:!0,resource:e,resourceType:t,currentUser:r,config:B1e,onClose:n}):l.jsx($B,{open:!0,resource:e,resourceType:t,currentUser:r,config:V1e(),onClose:n})}const H1e=p.cva("flex w-full rounded-control border border-input bg-background placeholder:text-[hsl(var(--semaphor-placeholder-foreground))] focus-visible:border-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",{variants:{size:{default:"min-h-[80px] px-3 py-2 text-sm",sm:"min-h-[60px] px-2.5 py-1.5 text-[13px]",xs:"min-h-[48px] px-2 py-1 text-[12px]"}},defaultVariants:{size:"default"}}),zm=te.forwardRef(({className:e,size:t,...n},r)=>l.jsx("textarea",{className:p.cn(H1e({size:t,className:e})),ref:r,...n}));zm.displayName="Textarea";function HQ({open:e,resourceLabel:t,initialTitle:n,initialDescription:r="",onClose:o,onSave:s,isSaving:i=!1}){const[a,c]=v.useState(n),[u,d]=v.useState(r??"");v.useEffect(()=>{e&&(c(n),d(r??""))},[e,n,r]);const f=h=>{h.preventDefault();const m=a.trim();m&&s({title:m,description:u.trim()})};return l.jsx(Mo,{open:e,onOpenChange:h=>h?null:o(),children:l.jsx(go,{className:"sm:max-w-md",children:l.jsxs("form",{onSubmit:f,className:"space-y-4",children:[l.jsxs(Is,{children:[l.jsxs(bo,{children:["Edit ",t]}),l.jsxs(Ro,{children:["Update the title and description for this ",t.toLowerCase(),"."]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(p.Label,{htmlFor:"resource-title",children:"Title"}),l.jsx(p.Input,{id:"resource-title",value:a,onChange:h=>c(h.target.value),placeholder:`Enter ${t.toLowerCase()} title`,autoFocus:!0})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(p.Label,{htmlFor:"resource-description",children:"Description"}),l.jsx(zm,{id:"resource-description",value:u,onChange:h=>d(h.target.value),placeholder:`Enter ${t.toLowerCase()} description (optional)`,rows:3})]}),l.jsxs(tl,{className:"mt-6 flex justify-end gap-2 sm:justify-end",children:[l.jsx(p.Button,{type:"button",variant:"outline",onClick:o,disabled:i,children:"Cancel"}),l.jsx(p.Button,{type:"submit",disabled:i||!a.trim(),children:i?"Saving...":"Save changes"})]})]})})})}const q1e=Object.freeze({hasAppearance:!1,containerStyle:Object.freeze({}),controlStyle:Object.freeze({}),chipStyle:Object.freeze({}),contentStyle:Object.freeze({})});function dc(e){const{compiledAppearance:t}=p.useAppearance();return v.useMemo(()=>U1e(t),[t,e])}function U1e(e,t){const n=e.scheme.components,r=n==null?void 0:n.interactive;n==null||n.pagination;const o=r;return qQ(o,{containerBackground:r==null?void 0:r.toolbarBackground,defaultStateBackground:o==null?void 0:o.background,selectedStateBackground:e.colorValues.accent})}function qQ(e,t={}){if(!e||Object.keys(e).length===0)return q1e;const n=zB(e,t),r=zB({...e,background:t.containerBackground},{includeRadiusVariables:t.includeRadiusVariables}),o=YT({...n,backgroundColor:e.background,color:e.foreground,borderColor:e.borderColor,borderRadius:e.borderRadius,boxShadow:e.shadow}),s=YT({...r,backgroundColor:t.containerBackground,color:e.foreground,borderColor:e.borderColor,borderRadius:e.borderRadius,boxShadow:e.shadow,padding:e.padding}),i=YT({...n,color:e.foreground,borderColor:e.borderColor,borderRadius:e.borderRadius,boxShadow:e.shadow});return{hasAppearance:!0,containerStyle:s,controlStyle:o,chipStyle:i,contentStyle:o}}function zB(e,t={}){const n={},r=fx(e.background),o=fx(t.defaultStateBackground),s=fx(t.selectedStateBackground),i=fx(e.foreground),a=fx(e.borderColor);if(r&&(n["--semaphor-background"]=r,n["--semaphor-card"]=r,n["--semaphor-popover"]=r),o&&(n["--semaphor-muted"]=o),s&&(n["--semaphor-accent"]=s),i&&(n["--semaphor-foreground"]=i,n["--semaphor-card-foreground"]=i,n["--semaphor-popover-foreground"]=i,n["--semaphor-muted-foreground"]=i),a&&(n["--semaphor-border"]=a,n["--semaphor-input"]=a),e.borderRadius!==void 0){const c=W1e(e.borderRadius);t.includeRadiusVariables!==!1&&(n["--semaphor-radius"]=c,n["--semaphor-control-radius"]=c)}return n}function fx(e){return e?Bxe.compileColorToHslTriplet(e):void 0}function W1e(e){return`${Number((e/16).toFixed(4))}rem`}function YT(e){const t=Object.entries(e).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}const K1e=Object.freeze({hasDashboardAppearance:!1,hasCardAppearance:!1,dashboardContainerStyle:Object.freeze({}),dashboardCanvasStyle:Object.freeze({}),gridStyle:Object.freeze({}),cardFrameStyle:Object.freeze({}),cardGutterStyle:Object.freeze({})});function Ru(){const{compiledAppearance:e}=p.useAppearance();return v.useMemo(()=>G1e(e),[e])}function G1e(e){var w,C,N,S,j,_,k,T,I,E,D,R;const t=(w=e.scheme.components)==null?void 0:w.dashboard,n=(C=e.scheme.components)==null?void 0:C.card,r=e.scheme.tokens,o=cf.SEMAPHOR_DEFAULT_APPEARANCE_SPEC.schemes[e.mode].tokens,s=qQ(n,{includeRadiusVariables:!1}),i=Y1e({appearance:t,colorTokens:r==null?void 0:r.color,defaultColorTokens:o==null?void 0:o.color}),a=Object.keys(i).length>0,c=(t==null?void 0:t.padding)??yC((N=r==null?void 0:r.spacing)==null?void 0:N.dashboardPadding,(S=o==null?void 0:o.spacing)==null?void 0:S.dashboardPadding),u=yC((j=r==null?void 0:r.spacing)==null?void 0:j.gridGap,(_=o==null?void 0:o.spacing)==null?void 0:_.gridGap),d=(n==null?void 0:n.padding)??yC((k=r==null?void 0:r.spacing)==null?void 0:k.cardPadding,(T=o==null?void 0:o.spacing)==null?void 0:T.cardPadding),f=(n==null?void 0:n.borderRadius)??yC((I=r==null?void 0:r.radius)==null?void 0:I.card,(E=o==null?void 0:o.radius)==null?void 0:E.card),h=(n==null?void 0:n.shadow)??Uf((D=r==null?void 0:r.shadow)==null?void 0:D.card,(R=o==null?void 0:o.shadow)==null?void 0:R.card);if(!a&&!s.hasAppearance&&c===void 0&&u===void 0&&d===void 0&&f===void 0&&h===void 0)return K1e;const m=BB(c),g=BB(u),b=yN({...s.controlStyle,borderRadius:f,boxShadow:h}),x=yN({paddingLeft:d,paddingRight:d}),y=f!==void 0?{"--placeholder-border-radius":`${f}px`}:{};return{hasDashboardAppearance:a||c!==void 0||u!==void 0,hasCardAppearance:s.hasAppearance||d!==void 0||f!==void 0||h!==void 0,dashboardContainerStyle:i,dashboardCanvasStyle:i,gridMargin:g,gridContainerPadding:m,gridStyle:y,cardFrameStyle:b,cardGutterStyle:x}}function Y1e({appearance:e,colorTokens:t,defaultColorTokens:n}){return!e||Object.keys(e).length===0?yN({backgroundColor:Uf(t==null?void 0:t.background,n==null?void 0:n.background),color:Uf(t==null?void 0:t.foreground,n==null?void 0:n.foreground),borderColor:Uf(t==null?void 0:t.border,n==null?void 0:n.border)}):yN({backgroundColor:e.background??Uf(t==null?void 0:t.background,n==null?void 0:n.background),color:e.foreground??Uf(t==null?void 0:t.foreground,n==null?void 0:n.foreground),borderColor:e.borderColor??Uf(t==null?void 0:t.border,n==null?void 0:n.border),borderRadius:e.borderRadius,boxShadow:e.shadow})}function BB(e){return e===void 0?void 0:[e,e]}function yC(e,t){return e!==void 0&&e!==t?e:void 0}function Uf(e,t){return e!==void 0&&e!==t?e:void 0}function yN(e){const t=Object.entries(e).filter(([,n])=>n!==void 0);return Object.fromEntries(t)}function Z1e(e){return e||"none"}function X1e(e){if(!e||e.kind!=="semantic")return;const t=e.connectionId||"",n=Z1e(e.connectionType),r=e.label||e.datasetName,o={id:e.datasetId||e.datasetName,type:"dataset",datasetType:"physical",domainId:e.domainId,label:r,description:e.description,connectionId:t,connectionType:n,database:e.database,schema:e.schema,name:e.datasetName};return{connectionId:t,connectionType:n,mode:"semanticDomain",semanticDomainId:e.domainId,selectedEntities:[o]}}function Q1e(e){const t=X1e(e.dataset);if(!t)return;const n=`dashboard_${dt.v4()}`,r=dt.v4(),o=dt.v4(),s=dt.v4(),i={id:s,title:"Title",type:"bar",connectionId:t.connectionId,dataSource:t,preferences:{onClickFilter:[{columnIndex:0,expression:""}]},sql:"",data:[]},a={id:o,cards:[i],activeCardId:s};return{id:n,title:e.title,description:e.description,aiContext:{selectedEntities:t.selectedEntities,mode:"fixed"},sheets:[{id:r,kind:"dashboard",title:"Sheet 1",frames:[a],layouts:qxe.createFrameLayouts({id:o,x:0,y:0,w:18,initialHeight:36,minH:10})}]}}function ZT(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function J1e(e){return JSON.stringify(e).replace(/</g,"\\u003c")}function eNe(e){const t={projectId:e.dataApp.projectId,dataAppId:e.dataApp.id,versionId:e.runtime.versionId,version:e.runtime.version,apiBaseUrl:e.apiBaseUrl.replace(/\/api\/?$/,""),dataApiBaseUrl:e.apiBaseUrl,assetsBaseUrl:e.runtime.assetsBaseUrl,manifest:e.runtime.manifest,authToken:e.runtime.authToken},n=e.runtime.styleUrls.map(r=>`<link rel="stylesheet" crossorigin="anonymous" href="${ZT(r)}">`).join(`
|
|
639
639
|
`);return`<!doctype html>
|
|
640
640
|
<html lang="en">
|
|
641
641
|
<head>
|
|
@@ -1290,7 +1290,7 @@ Include in the briefing:
|
|
|
1290
1290
|
To pick up a draggable item, press the space bar.
|
|
1291
1291
|
While dragging, use the arrow keys to move the item.
|
|
1292
1292
|
Press space again to drop the item in its new position, or press escape to cancel.
|
|
1293
|
-
`},Dut={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function Mut(e){let{announcements:t=Dut,container:n,hiddenTextDescribedById:r,screenReaderInstructions:o=Eut}=e;const{announce:s,announcement:i}=_ut(),a=Qw("DndLiveRegion"),[c,u]=v.useState(!1);if(v.useEffect(()=>{u(!0)},[]),Iut(v.useMemo(()=>({onDragStart(f){let{active:h}=f;s(t.onDragStart({active:h}))},onDragMove(f){let{active:h,over:m}=f;t.onDragMove&&s(t.onDragMove({active:h,over:m}))},onDragOver(f){let{active:h,over:m}=f;s(t.onDragOver({active:h,over:m}))},onDragEnd(f){let{active:h,over:m}=f;s(t.onDragEnd({active:h,over:m}))},onDragCancel(f){let{active:h,over:m}=f;s(t.onDragCancel({active:h,over:m}))}}),[s,t])),!c)return null;const d=v.createElement(v.Fragment,null,v.createElement(jut,{id:r,value:o.draggable}),v.createElement(kut,{id:a,announcement:i}));return n?br.createPortal(d,n):d}var ko;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(ko||(ko={}));function ok(){}function nb(e,t){return v.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function oT(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return v.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const al=Object.freeze({x:0,y:0});function Xfe(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function Rut(e,t){const n=rk(e);if(!n)return"0 0";const r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+"% "+r.y+"%"}function Qfe(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function Aut(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function FW(e){let{left:t,top:n,height:r,width:o}=e;return[{x:t,y:n},{x:t+o,y:n},{x:t,y:n+r},{x:t+o,y:n+r}]}function Jfe(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function OW(e,t,n){return t===void 0&&(t=e.left),n===void 0&&(n=e.top),{x:t+e.width*.5,y:n+e.height*.5}}const Jw=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const o=OW(t,t.left,t.top),s=[];for(const i of r){const{id:a}=i,c=n.get(a);if(c){const u=Xfe(OW(c),o);s.push({id:a,data:{droppableContainer:i,value:u}})}}return s.sort(Qfe)},Put=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const o=FW(t),s=[];for(const i of r){const{id:a}=i,c=n.get(a);if(c){const u=FW(c),d=o.reduce((h,m,g)=>h+Xfe(u[g],m),0),f=Number((d/4).toFixed(4));s.push({id:a,data:{droppableContainer:i,value:f}})}}return s.sort(Qfe)};function Fut(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),o=Math.min(t.left+t.width,e.left+e.width),s=Math.min(t.top+t.height,e.top+e.height),i=o-r,a=s-n;if(r<o&&n<s){const c=t.width*t.height,u=e.width*e.height,d=i*a,f=d/(c+u-d);return Number(f.toFixed(4))}return 0}const Out=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const o=[];for(const s of r){const{id:i}=s,a=n.get(i);if(a){const c=Fut(a,t);c>0&&o.push({id:i,data:{droppableContainer:s,value:c}})}}return o.sort(Aut)};function Lut(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function ehe(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:al}function $ut(e){return function(n){for(var r=arguments.length,o=new Array(r>1?r-1:0),s=1;s<r;s++)o[s-1]=arguments[s];return o.reduce((i,a)=>({...i,top:i.top+e*a.y,bottom:i.bottom+e*a.y,left:i.left+e*a.x,right:i.right+e*a.x}),{...n})}}const zut=$ut(1);function the(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function But(e,t,n){const r=the(t);if(!r)return e;const{scaleX:o,scaleY:s,x:i,y:a}=r,c=e.left-i-(1-o)*parseFloat(n),u=e.top-a-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),d=o?e.width/o:e.width,f=s?e.height/s:e.height;return{width:d,height:f,top:u,right:c+d,bottom:u+f,left:c}}const Vut={ignoreTransform:!1};function Qb(e,t){t===void 0&&(t=Vut);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:d}=ni(e).getComputedStyle(e);u&&(n=But(n,u,d))}const{top:r,left:o,width:s,height:i,bottom:a,right:c}=n;return{top:r,left:o,width:s,height:i,bottom:a,right:c}}function LW(e){return Qb(e,{ignoreTransform:!0})}function Hut(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function qut(e,t){return t===void 0&&(t=ni(e).getComputedStyle(e)),t.position==="fixed"}function Uut(e,t){t===void 0&&(t=ni(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{const s=t[o];return typeof s=="string"?n.test(s):!1})}function sT(e,t){const n=[];function r(o){if(t!=null&&n.length>=t||!o)return n;if(Rz(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!Zw(o)||Gfe(o)||n.includes(o))return n;const s=ni(e).getComputedStyle(o);return o!==e&&Uut(o,s)&&n.push(o),qut(o,s)?n:r(o.parentNode)}return e?r(e):n}function nhe(e){const[t]=sT(e,1);return t??null}function ZM(e){return!tT||!e?null:Zb(e)?e:Mz(e)?Rz(e)||e===Xb(e).scrollingElement?window:Zw(e)?e:null:null}function rhe(e){return Zb(e)?e.scrollX:e.scrollLeft}function ohe(e){return Zb(e)?e.scrollY:e.scrollTop}function vF(e){return{x:rhe(e),y:ohe(e)}}var Fo;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(Fo||(Fo={}));function she(e){return!tT||!e?!1:e===document.scrollingElement}function ihe(e){const t={x:0,y:0},n=she(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},o=e.scrollTop<=t.y,s=e.scrollLeft<=t.x,i=e.scrollTop>=r.y,a=e.scrollLeft>=r.x;return{isTop:o,isLeft:s,isBottom:i,isRight:a,maxScroll:r,minScroll:t}}const Wut={x:.2,y:.2};function Kut(e,t,n,r,o){let{top:s,left:i,right:a,bottom:c}=n;r===void 0&&(r=10),o===void 0&&(o=Wut);const{isTop:u,isBottom:d,isLeft:f,isRight:h}=ihe(e),m={x:0,y:0},g={x:0,y:0},b={height:t.height*o.y,width:t.width*o.x};return!u&&s<=t.top+b.height?(m.y=Fo.Backward,g.y=r*Math.abs((t.top+b.height-s)/b.height)):!d&&c>=t.bottom-b.height&&(m.y=Fo.Forward,g.y=r*Math.abs((t.bottom-b.height-c)/b.height)),!h&&a>=t.right-b.width?(m.x=Fo.Forward,g.x=r*Math.abs((t.right-b.width-a)/b.width)):!f&&i<=t.left+b.width&&(m.x=Fo.Backward,g.x=r*Math.abs((t.left+b.width-i)/b.width)),{direction:m,speed:g}}function Gut(e){if(e===document.scrollingElement){const{innerWidth:s,innerHeight:i}=window;return{top:0,left:0,right:s,bottom:i,width:s,height:i}}const{top:t,left:n,right:r,bottom:o}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:o,width:e.clientWidth,height:e.clientHeight}}function ahe(e){return e.reduce((t,n)=>dg(t,vF(n)),al)}function Yut(e){return e.reduce((t,n)=>t+rhe(n),0)}function Zut(e){return e.reduce((t,n)=>t+ohe(n),0)}function lhe(e,t){if(t===void 0&&(t=Qb),!e)return;const{top:n,left:r,bottom:o,right:s}=t(e);nhe(e)&&(o<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const Xut=[["x",["left","right"],Yut],["y",["top","bottom"],Zut]];class Az{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=sT(n),o=ahe(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[s,i,a]of Xut)for(const c of i)Object.defineProperty(this,c,{get:()=>{const u=a(r),d=o[s]-u;return this.rect[c]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class s0{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var o;(o=this.target)==null||o.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function Qut(e){const{EventTarget:t}=ni(e);return e instanceof t?e:Xb(e)}function XM(e,t){const n=Math.abs(e.x),r=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var aa;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(aa||(aa={}));function $W(e){e.preventDefault()}function Jut(e){e.stopPropagation()}var Fn;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(Fn||(Fn={}));const che={start:[Fn.Space,Fn.Enter],cancel:[Fn.Esc],end:[Fn.Space,Fn.Enter,Fn.Tab]},edt=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Fn.Right:return{...n,x:n.x+25};case Fn.Left:return{...n,x:n.x-25};case Fn.Down:return{...n,y:n.y+25};case Fn.Up:return{...n,y:n.y-25}}};class eC{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new s0(Xb(n)),this.windowListeners=new s0(ni(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(aa.Resize,this.handleCancel),this.windowListeners.add(aa.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(aa.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&lhe(r),n(al)}handleKeyDown(t){if(rT(t)){const{active:n,context:r,options:o}=this.props,{keyboardCodes:s=che,coordinateGetter:i=edt,scrollBehavior:a="smooth"}=o,{code:c}=t;if(s.end.includes(c)){this.handleEnd(t);return}if(s.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:al;this.referenceCoordinates||(this.referenceCoordinates=d);const f=i(t,{active:n,context:r.current,currentCoordinates:d});if(f){const h=uv(f,d),m={x:0,y:0},{scrollableAncestors:g}=r.current;for(const b of g){const x=t.code,{isTop:y,isRight:w,isLeft:C,isBottom:N,maxScroll:S,minScroll:j}=ihe(b),_=Gut(b),k={x:Math.min(x===Fn.Right?_.right-_.width/2:_.right,Math.max(x===Fn.Right?_.left:_.left+_.width/2,f.x)),y:Math.min(x===Fn.Down?_.bottom-_.height/2:_.bottom,Math.max(x===Fn.Down?_.top:_.top+_.height/2,f.y))},T=x===Fn.Right&&!w||x===Fn.Left&&!C,I=x===Fn.Down&&!N||x===Fn.Up&&!y;if(T&&k.x!==f.x){const E=b.scrollLeft+h.x,D=x===Fn.Right&&E<=S.x||x===Fn.Left&&E>=j.x;if(D&&!h.y){b.scrollTo({left:E,behavior:a});return}D?m.x=b.scrollLeft-E:m.x=x===Fn.Right?b.scrollLeft-S.x:b.scrollLeft-j.x,m.x&&b.scrollBy({left:-m.x,behavior:a});break}else if(I&&k.y!==f.y){const E=b.scrollTop+h.y,D=x===Fn.Down&&E<=S.y||x===Fn.Up&&E>=j.y;if(D&&!h.x){b.scrollTo({top:E,behavior:a});return}D?m.y=b.scrollTop-E:m.y=x===Fn.Down?b.scrollTop-S.y:b.scrollTop-j.y,m.y&&b.scrollBy({top:-m.y,behavior:a});break}}this.handleMove(t,dg(uv(f,this.referenceCoordinates),m))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}eC.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=che,onActivation:o}=t,{active:s}=n;const{code:i}=e.nativeEvent;if(r.start.includes(i)){const a=s.activatorNode.current;return a&&e.target!==a?!1:(e.preventDefault(),o==null||o({event:e.nativeEvent}),!0)}return!1}}];function zW(e){return!!(e&&"distance"in e)}function BW(e){return!!(e&&"delay"in e)}class Pz{constructor(t,n,r){var o;r===void 0&&(r=Qut(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:s}=t,{target:i}=s;this.props=t,this.events=n,this.document=Xb(i),this.documentListeners=new s0(this.document),this.listeners=new s0(r),this.windowListeners=new s0(ni(i)),this.initialCoordinates=(o=rk(s))!=null?o:al,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(aa.Resize,this.handleCancel),this.windowListeners.add(aa.DragStart,$W),this.windowListeners.add(aa.VisibilityChange,this.handleCancel),this.windowListeners.add(aa.ContextMenu,$W),this.documentListeners.add(aa.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(BW(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(zW(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:o}=this.props;o(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(aa.Click,Jut,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(aa.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:o,props:s}=this,{onMove:i,options:{activationConstraint:a}}=s;if(!o)return;const c=(n=rk(t))!=null?n:al,u=uv(o,c);if(!r&&a){if(zW(a)){if(a.tolerance!=null&&XM(u,a.tolerance))return this.handleCancel();if(XM(u,a.distance))return this.handleStart()}if(BW(a)&&XM(u,a.tolerance))return this.handleCancel();this.handlePending(a,u);return}t.cancelable&&t.preventDefault(),i(c)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Fn.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const tdt={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Jb extends Pz{constructor(t){const{event:n}=t,r=Xb(n.target);super(t,tdt,r)}}Jb.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const ndt={move:{name:"mousemove"},end:{name:"mouseup"}};var wF;(function(e){e[e.RightClick=2]="RightClick"})(wF||(wF={}));class rdt extends Pz{constructor(t){super(t,ndt,Xb(t.event.target))}}rdt.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===wF.RightClick?!1:(r==null||r({event:n}),!0)}}];const QM={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class odt extends Pz{constructor(t){super(t,QM)}static setup(){return window.addEventListener(QM.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(QM.move.name,t)};function t(){}}}odt.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:o}=n;return o.length>1?!1:(r==null||r({event:n}),!0)}}];var i0;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(i0||(i0={}));var sk;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(sk||(sk={}));function sdt(e){let{acceleration:t,activator:n=i0.Pointer,canScroll:r,draggingRect:o,enabled:s,interval:i=5,order:a=sk.TreeOrder,pointerCoordinates:c,scrollableAncestors:u,scrollableAncestorRects:d,delta:f,threshold:h}=e;const m=adt({delta:f,disabled:!s}),[g,b]=vut(),x=v.useRef({x:0,y:0}),y=v.useRef({x:0,y:0}),w=v.useMemo(()=>{switch(n){case i0.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case i0.DraggableRect:return o}},[n,o,c]),C=v.useRef(null),N=v.useCallback(()=>{const j=C.current;if(!j)return;const _=x.current.x*y.current.x,k=x.current.y*y.current.y;j.scrollBy(_,k)},[]),S=v.useMemo(()=>a===sk.TreeOrder?[...u].reverse():u,[a,u]);v.useEffect(()=>{if(!s||!u.length||!w){b();return}for(const j of S){if((r==null?void 0:r(j))===!1)continue;const _=u.indexOf(j),k=d[_];if(!k)continue;const{direction:T,speed:I}=Kut(j,k,w,t,h);for(const E of["x","y"])m[E][T[E]]||(I[E]=0,T[E]=0);if(I.x>0||I.y>0){b(),C.current=j,g(N,i),x.current=I,y.current=T;return}}x.current={x:0,y:0},y.current={x:0,y:0},b()},[t,N,r,b,s,i,JSON.stringify(w),JSON.stringify(m),g,u,S,d,JSON.stringify(h)])}const idt={x:{[Fo.Backward]:!1,[Fo.Forward]:!1},y:{[Fo.Backward]:!1,[Fo.Forward]:!1}};function adt(e){let{delta:t,disabled:n}=e;const r=nk(t);return Xw(o=>{if(n||!r||!o)return idt;const s={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[Fo.Backward]:o.x[Fo.Backward]||s.x===-1,[Fo.Forward]:o.x[Fo.Forward]||s.x===1},y:{[Fo.Backward]:o.y[Fo.Backward]||s.y===-1,[Fo.Forward]:o.y[Fo.Forward]||s.y===1}}},[n,t,r])}function ldt(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return Xw(o=>{var s;return t==null?null:(s=r??o)!=null?s:null},[r,t])}function cdt(e,t){return v.useMemo(()=>e.reduce((n,r)=>{const{sensor:o}=r,s=o.activators.map(i=>({eventName:i.eventName,handler:t(i.handler,r)}));return[...n,...s]},[]),[e,t])}var dv;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(dv||(dv={}));var CF;(function(e){e.Optimized="optimized"})(CF||(CF={}));const VW=new Map;function udt(e,t){let{dragging:n,dependencies:r,config:o}=t;const[s,i]=v.useState(null),{frequency:a,measure:c,strategy:u}=o,d=v.useRef(e),f=x(),h=cv(f),m=v.useCallback(function(y){y===void 0&&(y=[]),!h.current&&i(w=>w===null?y:w.concat(y.filter(C=>!w.includes(C))))},[h]),g=v.useRef(null),b=Xw(y=>{if(f&&!n)return VW;if(!y||y===VW||d.current!==e||s!=null){const w=new Map;for(let C of e){if(!C)continue;if(s&&s.length>0&&!s.includes(C.id)&&C.rect.current){w.set(C.id,C.rect.current);continue}const N=C.node.current,S=N?new Az(c(N),N):null;C.rect.current=S,S&&w.set(C.id,S)}return w}return y},[e,s,n,f,c]);return v.useEffect(()=>{d.current=e},[e]),v.useEffect(()=>{f||m()},[n,f]),v.useEffect(()=>{s&&s.length>0&&i(null)},[JSON.stringify(s)]),v.useEffect(()=>{f||typeof a!="number"||g.current!==null||(g.current=setTimeout(()=>{m(),g.current=null},a))},[a,f,m,...r]),{droppableRects:b,measureDroppableContainers:m,measuringScheduled:s!=null};function x(){switch(u){case dv.Always:return!1;case dv.BeforeDragging:return n;default:return!n}}}function Fz(e,t){return Xw(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function ddt(e,t){return Fz(e,t)}function fdt(e){let{callback:t,disabled:n}=e;const r=nT(t),o=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return v.useEffect(()=>()=>o==null?void 0:o.disconnect(),[o]),o}function iT(e){let{callback:t,disabled:n}=e;const r=nT(t),o=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return v.useEffect(()=>()=>o==null?void 0:o.disconnect(),[o]),o}function hdt(e){return new Az(Qb(e),e)}function HW(e,t,n){t===void 0&&(t=hdt);const[r,o]=v.useState(null);function s(){o(c=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=c??n)!=null?u:null}const d=t(e);return JSON.stringify(c)===JSON.stringify(d)?c:d})}const i=fdt({callback(c){if(e)for(const u of c){const{type:d,target:f}=u;if(d==="childList"&&f instanceof HTMLElement&&f.contains(e)){s();break}}}}),a=iT({callback:s});return il(()=>{s(),e?(a==null||a.observe(e),i==null||i.observe(document.body,{childList:!0,subtree:!0})):(a==null||a.disconnect(),i==null||i.disconnect())},[e]),r}function mdt(e){const t=Fz(e);return ehe(e,t)}const qW=[];function pdt(e){const t=v.useRef(e),n=Xw(r=>e?r&&r!==qW&&e&&t.current&&e.parentNode===t.current.parentNode?r:sT(e):qW,[e]);return v.useEffect(()=>{t.current=e},[e]),n}function gdt(e){const[t,n]=v.useState(null),r=v.useRef(e),o=v.useCallback(s=>{const i=ZM(s.target);i&&n(a=>a?(a.set(i,vF(i)),new Map(a)):null)},[]);return v.useEffect(()=>{const s=r.current;if(e!==s){i(s);const a=e.map(c=>{const u=ZM(c);return u?(u.addEventListener("scroll",o,{passive:!0}),[u,vF(u)]):null}).filter(c=>c!=null);n(a.length?new Map(a):null),r.current=e}return()=>{i(e),i(s)};function i(a){a.forEach(c=>{const u=ZM(c);u==null||u.removeEventListener("scroll",o)})}},[o,e]),v.useMemo(()=>e.length?t?Array.from(t.values()).reduce((s,i)=>dg(s,i),al):ahe(e):al,[e,t])}function UW(e,t){t===void 0&&(t=[]);const n=v.useRef(null);return v.useEffect(()=>{n.current=null},t),v.useEffect(()=>{const r=e!==al;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?uv(e,n.current):al}function bdt(e){v.useEffect(()=>{if(!tT)return;const t=e.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n==null||n()}},e.map(t=>{let{sensor:n}=t;return n}))}function xdt(e,t){return v.useMemo(()=>e.reduce((n,r)=>{let{eventName:o,handler:s}=r;return n[o]=i=>{s(i,t)},n},{}),[e,t])}function uhe(e){return v.useMemo(()=>e?Hut(e):null,[e])}const WW=[];function ydt(e,t){t===void 0&&(t=Qb);const[n]=e,r=uhe(n?ni(n):null),[o,s]=v.useState(WW);function i(){s(()=>e.length?e.map(c=>she(c)?r:new Az(t(c),c)):WW)}const a=iT({callback:i});return il(()=>{a==null||a.disconnect(),i(),e.forEach(c=>a==null?void 0:a.observe(c))},[e]),o}function dhe(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Zw(t)?t:e}function vdt(e){let{measure:t}=e;const[n,r]=v.useState(null),o=v.useCallback(u=>{for(const{target:d}of u)if(Zw(d)){r(f=>{const h=t(d);return f?{...f,width:h.width,height:h.height}:h});break}},[t]),s=iT({callback:o}),i=v.useCallback(u=>{const d=dhe(u);s==null||s.disconnect(),d&&(s==null||s.observe(d)),r(d?t(d):null)},[t,s]),[a,c]=tk(i);return v.useMemo(()=>({nodeRef:a,rect:n,setRef:c}),[n,a,c])}const wdt=[{sensor:Jb,options:{}},{sensor:eC,options:{}}],Cdt={current:{}},Y1={draggable:{measure:LW},droppable:{measure:LW,strategy:dv.WhileDragging,frequency:CF.Optimized},dragOverlay:{measure:Qb}};class a0 extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const Sdt={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new a0,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ok},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Y1,measureDroppableContainers:ok,windowRect:null,measuringScheduled:!1},fhe={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:ok,draggableNodes:new Map,over:null,measureDroppableContainers:ok},tC=v.createContext(fhe),hhe=v.createContext(Sdt);function Ndt(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new a0}}}function jdt(e,t){switch(t.type){case ko.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case ko.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case ko.DragEnd:case ko.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ko.RegisterDroppable:{const{element:n}=t,{id:r}=n,o=new a0(e.droppable.containers);return o.set(r,n),{...e,droppable:{...e.droppable,containers:o}}}case ko.SetDroppableDisabled:{const{id:n,key:r,disabled:o}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const i=new a0(e.droppable.containers);return i.set(n,{...s,disabled:o}),{...e,droppable:{...e.droppable,containers:i}}}case ko.UnregisterDroppable:{const{id:n,key:r}=t,o=e.droppable.containers.get(n);if(!o||r!==o.key)return e;const s=new a0(e.droppable.containers);return s.delete(n),{...e,droppable:{...e.droppable,containers:s}}}default:return e}}function kdt(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:o}=v.useContext(tC),s=nk(r),i=nk(n==null?void 0:n.id);return v.useEffect(()=>{if(!t&&!r&&s&&i!=null){if(!rT(s)||document.activeElement===s.target)return;const a=o.get(i);if(!a)return;const{activatorNode:c,node:u}=a;if(!c.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[c.current,u.current]){if(!d)continue;const f=Sut(d);if(f){f.focus();break}}})}},[r,t,o,i,s]),null}function mhe(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((o,s)=>s({transform:o,...r}),n):n}function _dt(e){return v.useMemo(()=>({draggable:{...Y1.draggable,...e==null?void 0:e.draggable},droppable:{...Y1.droppable,...e==null?void 0:e.droppable},dragOverlay:{...Y1.dragOverlay,...e==null?void 0:e.dragOverlay}}),[e==null?void 0:e.draggable,e==null?void 0:e.droppable,e==null?void 0:e.dragOverlay])}function Idt(e){let{activeNode:t,measure:n,initialRect:r,config:o=!0}=e;const s=v.useRef(!1),{x:i,y:a}=typeof o=="boolean"?{x:o,y:o}:o;il(()=>{if(!i&&!a||!t){s.current=!1;return}if(s.current||!r)return;const u=t==null?void 0:t.node.current;if(!u||u.isConnected===!1)return;const d=n(u),f=ehe(d,r);if(i||(f.x=0),a||(f.y=0),s.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const h=nhe(u);h&&h.scrollBy({top:f.y,left:f.x})}},[t,i,a,r,n])}const aT=v.createContext({...al,scaleX:1,scaleY:1});var rd;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(rd||(rd={}));const nC=v.memo(function(t){var n,r,o,s;let{id:i,accessibility:a,autoScroll:c=!0,children:u,sensors:d=wdt,collisionDetection:f=Out,measuring:h,modifiers:m,...g}=t;const b=v.useReducer(jdt,void 0,Ndt),[x,y]=b,[w,C]=Tut(),[N,S]=v.useState(rd.Uninitialized),j=N===rd.Initialized,{draggable:{active:_,nodes:k,translate:T},droppable:{containers:I}}=x,E=_!=null?k.get(_):null,D=v.useRef({initial:null,translated:null}),R=v.useMemo(()=>{var Ae;return _!=null?{id:_,data:(Ae=E==null?void 0:E.data)!=null?Ae:Cdt,rect:D}:null},[_,E]),A=v.useRef(null),[F,z]=v.useState(null),[L,$]=v.useState(null),H=cv(g,Object.values(g)),M=Qw("DndDescribedBy",i),B=v.useMemo(()=>I.getEnabled(),[I]),W=_dt(h),{droppableRects:P,measureDroppableContainers:G,measuringScheduled:Z}=udt(B,{dragging:j,dependencies:[T.x,T.y],config:W.droppable}),X=ldt(k,_),Y=v.useMemo(()=>L?rk(L):null,[L]),O=Ve(),q=ddt(X,W.draggable.measure);Idt({activeNode:_!=null?k.get(_):null,config:O.layoutShiftCompensation,initialRect:q,measure:W.draggable.measure});const U=HW(X,W.draggable.measure,q),V=HW(X?X.parentElement:null),K=v.useRef({activatorEvent:null,active:null,activeNode:X,collisionRect:null,collisions:null,droppableRects:P,draggableNodes:k,draggingNode:null,draggingNodeRect:null,droppableContainers:I,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Q=I.getNodeFor((n=K.current.over)==null?void 0:n.id),se=vdt({measure:W.dragOverlay.measure}),oe=(r=se.nodeRef.current)!=null?r:X,me=j?(o=se.rect)!=null?o:U:null,le=!!(se.nodeRef.current&&se.rect),ue=mdt(le?null:U),ne=uhe(oe?ni(oe):null),de=pdt(j?Q??X:null),Ce=ydt(de),ce=mhe(m,{transform:{x:T.x-ue.x,y:T.y-ue.y,scaleX:1,scaleY:1},activatorEvent:L,active:R,activeNodeRect:U,containerNodeRect:V,draggingNodeRect:me,over:K.current.over,overlayNodeRect:se.rect,scrollableAncestors:de,scrollableAncestorRects:Ce,windowRect:ne}),ie=Y?dg(Y,T):null,we=gdt(de),fe=UW(we),ae=UW(we,[U]),ee=dg(ce,fe),J=me?zut(me,ce):null,re=R&&J?f({active:R,collisionRect:J,droppableRects:P,droppableContainers:B,pointerCoordinates:ie}):null,pe=Jfe(re,"id"),[Ee,Te]=v.useState(null),ze=le?ce:dg(ce,ae),Pe=Lut(ze,(s=Ee==null?void 0:Ee.rect)!=null?s:null,U),He=v.useRef(null),ye=v.useCallback((Ae,ke)=>{let{sensor:Be,options:Ie}=ke;if(A.current==null)return;const $e=k.get(A.current);if(!$e)return;const st=Ae.nativeEvent,ct=new Be({active:A.current,activeNode:$e,event:st,options:Ie,context:K,onAbort(Ct){if(!k.get(Ct))return;const{onDragAbort:vt}=H.current,Tt={id:Ct};vt==null||vt(Tt),w({type:"onDragAbort",event:Tt})},onPending(Ct,Lt,vt,Tt){if(!k.get(Ct))return;const{onDragPending:Je}=H.current,kt={id:Ct,constraint:Lt,initialCoordinates:vt,offset:Tt};Je==null||Je(kt),w({type:"onDragPending",event:kt})},onStart(Ct){const Lt=A.current;if(Lt==null)return;const vt=k.get(Lt);if(!vt)return;const{onDragStart:Tt}=H.current,Me={activatorEvent:st,active:{id:Lt,data:vt.data,rect:D}};br.unstable_batchedUpdates(()=>{Tt==null||Tt(Me),S(rd.Initializing),y({type:ko.DragStart,initialCoordinates:Ct,active:Lt}),w({type:"onDragStart",event:Me}),z(He.current),$(st)})},onMove(Ct){y({type:ko.DragMove,coordinates:Ct})},onEnd:rt(ko.DragEnd),onCancel:rt(ko.DragCancel)});He.current=ct;function rt(Ct){return async function(){const{active:vt,collisions:Tt,over:Me,scrollAdjustedTranslate:Je}=K.current;let kt=null;if(vt&&Je){const{cancelDrop:mt}=H.current;kt={activatorEvent:st,active:vt,collisions:Tt,delta:Je,over:Me},Ct===ko.DragEnd&&typeof mt=="function"&&await Promise.resolve(mt(kt))&&(Ct=ko.DragCancel)}A.current=null,br.unstable_batchedUpdates(()=>{y({type:Ct}),S(rd.Uninitialized),Te(null),z(null),$(null),He.current=null;const mt=Ct===ko.DragEnd?"onDragEnd":"onDragCancel";if(kt){const _t=H.current[mt];_t==null||_t(kt),w({type:mt,event:kt})}})}}},[k]),Ke=v.useCallback((Ae,ke)=>(Be,Ie)=>{const $e=Be.nativeEvent,st=k.get(Ie);if(A.current!==null||!st||$e.dndKit||$e.defaultPrevented)return;const ct={active:st};Ae(Be,ke.options,ct)===!0&&($e.dndKit={capturedBy:ke.sensor},A.current=Ie,ye(Be,ke))},[k,ye]),We=cdt(d,Ke);bdt(d),il(()=>{U&&N===rd.Initializing&&S(rd.Initialized)},[U,N]),v.useEffect(()=>{const{onDragMove:Ae}=H.current,{active:ke,activatorEvent:Be,collisions:Ie,over:$e}=K.current;if(!ke||!Be)return;const st={active:ke,activatorEvent:Be,collisions:Ie,delta:{x:ee.x,y:ee.y},over:$e};br.unstable_batchedUpdates(()=>{Ae==null||Ae(st),w({type:"onDragMove",event:st})})},[ee.x,ee.y]),v.useEffect(()=>{const{active:Ae,activatorEvent:ke,collisions:Be,droppableContainers:Ie,scrollAdjustedTranslate:$e}=K.current;if(!Ae||A.current==null||!ke||!$e)return;const{onDragOver:st}=H.current,ct=Ie.get(pe),rt=ct&&ct.rect.current?{id:ct.id,rect:ct.rect.current,data:ct.data,disabled:ct.disabled}:null,Ct={active:Ae,activatorEvent:ke,collisions:Be,delta:{x:$e.x,y:$e.y},over:rt};br.unstable_batchedUpdates(()=>{Te(rt),st==null||st(Ct),w({type:"onDragOver",event:Ct})})},[pe]),il(()=>{K.current={activatorEvent:L,active:R,activeNode:X,collisionRect:J,collisions:re,droppableRects:P,draggableNodes:k,draggingNode:oe,draggingNodeRect:me,droppableContainers:I,over:Ee,scrollableAncestors:de,scrollAdjustedTranslate:ee},D.current={initial:me,translated:J}},[R,X,re,J,k,oe,me,P,I,Ee,de,ee]),sdt({...O,delta:T,draggingRect:J,pointerCoordinates:ie,scrollableAncestors:de,scrollableAncestorRects:Ce});const Qe=v.useMemo(()=>({active:R,activeNode:X,activeNodeRect:U,activatorEvent:L,collisions:re,containerNodeRect:V,dragOverlay:se,draggableNodes:k,droppableContainers:I,droppableRects:P,over:Ee,measureDroppableContainers:G,scrollableAncestors:de,scrollableAncestorRects:Ce,measuringConfiguration:W,measuringScheduled:Z,windowRect:ne}),[R,X,U,L,re,V,se,k,I,P,Ee,G,de,Ce,W,Z,ne]),xe=v.useMemo(()=>({activatorEvent:L,activators:We,active:R,activeNodeRect:U,ariaDescribedById:{draggable:M},dispatch:y,draggableNodes:k,over:Ee,measureDroppableContainers:G}),[L,We,R,U,y,M,k,Ee,G]);return v.createElement(Zfe.Provider,{value:C},v.createElement(tC.Provider,{value:xe},v.createElement(hhe.Provider,{value:Qe},v.createElement(aT.Provider,{value:Pe},u)),v.createElement(kdt,{disabled:(a==null?void 0:a.restoreFocus)===!1})),v.createElement(Mut,{...a,hiddenTextDescribedById:M}));function Ve(){const Ae=(F==null?void 0:F.autoScrollEnabled)===!1,ke=typeof c=="object"?c.enabled===!1:c===!1,Be=j&&!Ae&&!ke;return typeof c=="object"?{...c,enabled:Be}:{enabled:Be}}}),Tdt=v.createContext(null),KW="button",Edt="Draggable";function Ddt(e){let{id:t,data:n,disabled:r=!1,attributes:o}=e;const s=Qw(Edt),{activators:i,activatorEvent:a,active:c,activeNodeRect:u,ariaDescribedById:d,draggableNodes:f,over:h}=v.useContext(tC),{role:m=KW,roleDescription:g="draggable",tabIndex:b=0}=o??{},x=(c==null?void 0:c.id)===t,y=v.useContext(x?aT:Tdt),[w,C]=tk(),[N,S]=tk(),j=xdt(i,t),_=cv(n);il(()=>(f.set(t,{id:t,key:s,node:w,activatorNode:N,data:_}),()=>{const T=f.get(t);T&&T.key===s&&f.delete(t)}),[f,t]);const k=v.useMemo(()=>({role:m,tabIndex:b,"aria-disabled":r,"aria-pressed":x&&m===KW?!0:void 0,"aria-roledescription":g,"aria-describedby":d.draggable}),[r,m,b,x,g,d.draggable]);return{active:c,activatorEvent:a,activeNodeRect:u,attributes:k,isDragging:x,listeners:r?void 0:j,node:w,over:h,setNodeRef:C,setActivatorNodeRef:S,transform:y}}function phe(){return v.useContext(hhe)}const Mdt="Droppable",Rdt={timeout:25};function ghe(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:o}=e;const s=Qw(Mdt),{active:i,dispatch:a,over:c,measureDroppableContainers:u}=v.useContext(tC),d=v.useRef({disabled:n}),f=v.useRef(!1),h=v.useRef(null),m=v.useRef(null),{disabled:g,updateMeasurementsFor:b,timeout:x}={...Rdt,...o},y=cv(b??r),w=v.useCallback(()=>{if(!f.current){f.current=!0;return}m.current!=null&&clearTimeout(m.current),m.current=setTimeout(()=>{u(Array.isArray(y.current)?y.current:[y.current]),m.current=null},x)},[x]),C=iT({callback:w,disabled:g||!i}),N=v.useCallback((k,T)=>{C&&(T&&(C.unobserve(T),f.current=!1),k&&C.observe(k))},[C]),[S,j]=tk(N),_=cv(t);return v.useEffect(()=>{!C||!S.current||(C.disconnect(),f.current=!1,C.observe(S.current))},[S,C]),v.useEffect(()=>(a({type:ko.RegisterDroppable,element:{id:r,key:s,disabled:n,node:S,rect:h,data:_}}),()=>a({type:ko.UnregisterDroppable,key:s,id:r})),[r]),v.useEffect(()=>{n!==d.current.disabled&&(a({type:ko.SetDroppableDisabled,id:r,key:s,disabled:n}),d.current.disabled=n)},[r,s,n,a]),{active:i,rect:h,isOver:(c==null?void 0:c.id)===r,node:S,over:c,setNodeRef:j}}function Adt(e){let{animation:t,children:n}=e;const[r,o]=v.useState(null),[s,i]=v.useState(null),a=nk(n);return!n&&!r&&a&&o(a),il(()=>{if(!s)return;const c=r==null?void 0:r.key,u=r==null?void 0:r.props.id;if(c==null||u==null){o(null);return}Promise.resolve(t(u,s)).then(()=>{o(null)})},[t,r,s]),v.createElement(v.Fragment,null,n,r?v.cloneElement(r,{ref:i}):null)}const Pdt={x:0,y:0,scaleX:1,scaleY:1};function Fdt(e){let{children:t}=e;return v.createElement(tC.Provider,{value:fhe},v.createElement(aT.Provider,{value:Pdt},t))}const Odt={position:"fixed",touchAction:"none"},Ldt=e=>rT(e)?"transform 250ms ease":void 0,$dt=v.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:o,children:s,className:i,rect:a,style:c,transform:u,transition:d=Ldt}=e;if(!a)return null;const f=o?u:{...u,scaleX:1,scaleY:1},h={...Odt,width:a.width,height:a.height,top:a.top,left:a.left,transform:Ki.Transform.toString(f),transformOrigin:o&&r?Rut(r,a):void 0,transition:typeof d=="function"?d(r):d,...c};return v.createElement(n,{className:i,style:h,ref:t},s)}),zdt=e=>t=>{let{active:n,dragOverlay:r}=t;const o={},{styles:s,className:i}=e;if(s!=null&&s.active)for(const[a,c]of Object.entries(s.active))c!==void 0&&(o[a]=n.node.style.getPropertyValue(a),n.node.style.setProperty(a,c));if(s!=null&&s.dragOverlay)for(const[a,c]of Object.entries(s.dragOverlay))c!==void 0&&r.node.style.setProperty(a,c);return i!=null&&i.active&&n.node.classList.add(i.active),i!=null&&i.dragOverlay&&r.node.classList.add(i.dragOverlay),function(){for(const[c,u]of Object.entries(o))n.node.style.setProperty(c,u);i!=null&&i.active&&n.node.classList.remove(i.active)}},Bdt=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Ki.Transform.toString(t)},{transform:Ki.Transform.toString(n)}]},Vdt={duration:250,easing:"ease",keyframes:Bdt,sideEffects:zdt({styles:{active:{opacity:"0"}}})};function Hdt(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:o}=e;return nT((s,i)=>{if(t===null)return;const a=n.get(s);if(!a)return;const c=a.node.current;if(!c)return;const u=dhe(i);if(!u)return;const{transform:d}=ni(i).getComputedStyle(i),f=the(d);if(!f)return;const h=typeof t=="function"?t:qdt(t);return lhe(c,o.draggable.measure),h({active:{id:s,data:a.data,node:c,rect:o.draggable.measure(c)},draggableNodes:n,dragOverlay:{node:i,rect:o.dragOverlay.measure(u)},droppableContainers:r,measuringConfiguration:o,transform:f})})}function qdt(e){const{duration:t,easing:n,sideEffects:r,keyframes:o}={...Vdt,...e};return s=>{let{active:i,dragOverlay:a,transform:c,...u}=s;if(!t)return;const d={x:a.rect.left-i.rect.left,y:a.rect.top-i.rect.top},f={scaleX:c.scaleX!==1?i.rect.width*c.scaleX/a.rect.width:1,scaleY:c.scaleY!==1?i.rect.height*c.scaleY/a.rect.height:1},h={x:c.x-d.x,y:c.y-d.y,...f},m=o({...u,active:i,dragOverlay:a,transform:{initial:c,final:h}}),[g]=m,b=m[m.length-1];if(JSON.stringify(g)===JSON.stringify(b))return;const x=r==null?void 0:r({active:i,dragOverlay:a,...u}),y=a.node.animate(m,{duration:t,easing:n,fill:"forwards"});return new Promise(w=>{y.onfinish=()=>{x==null||x(),w()}})}}let GW=0;function Udt(e){return v.useMemo(()=>{if(e!=null)return GW++,GW},[e])}const bhe=v.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:o,transition:s,modifiers:i,wrapperElement:a="div",className:c,zIndex:u=999}=e;const{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:m,draggableNodes:g,droppableContainers:b,dragOverlay:x,over:y,measuringConfiguration:w,scrollableAncestors:C,scrollableAncestorRects:N,windowRect:S}=phe(),j=v.useContext(aT),_=Udt(f==null?void 0:f.id),k=mhe(i,{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:m,draggingNodeRect:x.rect,over:y,overlayNodeRect:x.rect,scrollableAncestors:C,scrollableAncestorRects:N,transform:j,windowRect:S}),T=Fz(h),I=Hdt({config:r,draggableNodes:g,droppableContainers:b,measuringConfiguration:w}),E=T?x.setRef:void 0;return v.createElement(Fdt,null,v.createElement(Adt,{animation:I},f&&_?v.createElement($dt,{key:_,id:f.id,ref:E,as:a,activatorEvent:d,adjustScale:t,className:c,transition:s,rect:T,style:{zIndex:u,...o},transform:k},n):null))});function ex(e,t,n){const r=e.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function Wdt(e,t){return e.reduce((n,r,o)=>{const s=t.get(r);return s&&(n[o]=s),n},Array(e.length))}function KS(e){return e!==null&&e>=0}function Kdt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Gdt(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const GS={scaleX:1,scaleY:1},Oz=e=>{var t;let{rects:n,activeNodeRect:r,activeIndex:o,overIndex:s,index:i}=e;const a=(t=n[o])!=null?t:r;if(!a)return null;const c=Ydt(n,i,o);if(i===o){const u=n[s];return u?{x:o<s?u.left+u.width-(a.left+a.width):u.left-a.left,y:0,...GS}:null}return i>o&&i<=s?{x:-a.width-c,y:0,...GS}:i<o&&i>=s?{x:a.width+c,y:0,...GS}:{x:0,y:0,...GS}};function Ydt(e,t,n){const r=e[t],o=e[t-1],s=e[t+1];return!r||!o&&!s?0:n<t?o?r.left-(o.left+o.width):s.left-(r.left+r.width):s?s.left-(r.left+r.width):r.left-(o.left+o.width)}const xhe=e=>{let{rects:t,activeIndex:n,overIndex:r,index:o}=e;const s=ex(t,r,n),i=t[o],a=s[o];return!a||!i?null:{x:a.left-i.left,y:a.top-i.top,scaleX:a.width/i.width,scaleY:a.height/i.height}},YS={scaleX:1,scaleY:1},Lz=e=>{var t;let{activeIndex:n,activeNodeRect:r,index:o,rects:s,overIndex:i}=e;const a=(t=s[n])!=null?t:r;if(!a)return null;if(o===n){const u=s[i];return u?{x:0,y:n<i?u.top+u.height-(a.top+a.height):u.top-a.top,...YS}:null}const c=Zdt(s,o,n);return o>n&&o<=i?{x:0,y:-a.height-c,...YS}:o<n&&o>=i?{x:0,y:a.height+c,...YS}:{x:0,y:0,...YS}};function Zdt(e,t,n){const r=e[t],o=e[t-1],s=e[t+1];return r?n<t?o?r.top-(o.top+o.height):s?s.top-(r.top+r.height):0:s?s.top-(r.top+r.height):o?r.top-(o.top+o.height):0:0}const yhe="Sortable",vhe=v.createContext({activeIndex:-1,containerId:yhe,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:xhe,disabled:{draggable:!1,droppable:!1}});function rC(e){let{children:t,id:n,items:r,strategy:o=xhe,disabled:s=!1}=e;const{active:i,dragOverlay:a,droppableRects:c,over:u,measureDroppableContainers:d}=phe(),f=Qw(yhe,n),h=a.rect!==null,m=v.useMemo(()=>r.map(j=>typeof j=="object"&&"id"in j?j.id:j),[r]),g=i!=null,b=i?m.indexOf(i.id):-1,x=u?m.indexOf(u.id):-1,y=v.useRef(m),w=!Kdt(m,y.current),C=x!==-1&&b===-1||w,N=Gdt(s);il(()=>{w&&g&&d(m)},[w,m,g,d]),v.useEffect(()=>{y.current=m},[m]);const S=v.useMemo(()=>({activeIndex:b,containerId:f,disabled:N,disableTransforms:C,items:m,overIndex:x,useDragOverlay:h,sortedRects:Wdt(m,c),strategy:o}),[b,f,N.draggable,N.droppable,C,m,x,c,h,o]);return v.createElement(vhe.Provider,{value:S},t)}const Xdt=e=>{let{id:t,items:n,activeIndex:r,overIndex:o}=e;return ex(n,r,o).indexOf(t)},Qdt=e=>{let{containerId:t,isSorting:n,wasDragging:r,index:o,items:s,newIndex:i,previousItems:a,previousContainerId:c,transition:u}=e;return!u||!r||a!==s&&o===i?!1:n?!0:i!==o&&t===c},Jdt={duration:200,easing:"ease"},whe="transform",eft=Ki.Transition.toString({property:whe,duration:0,easing:"linear"}),tft={roleDescription:"sortable"};function nft(e){let{disabled:t,index:n,node:r,rect:o}=e;const[s,i]=v.useState(null),a=v.useRef(n);return il(()=>{if(!t&&n!==a.current&&r.current){const c=o.current;if(c){const u=Qb(r.current,{ignoreTransform:!0}),d={x:c.left-u.left,y:c.top-u.top,scaleX:c.width/u.width,scaleY:c.height/u.height};(d.x||d.y)&&i(d)}}n!==a.current&&(a.current=n)},[t,n,r,o]),v.useEffect(()=>{s&&i(null)},[s]),s}function tx(e){let{animateLayoutChanges:t=Qdt,attributes:n,disabled:r,data:o,getNewIndex:s=Xdt,id:i,strategy:a,resizeObserverConfig:c,transition:u=Jdt}=e;const{items:d,containerId:f,activeIndex:h,disabled:m,disableTransforms:g,sortedRects:b,overIndex:x,useDragOverlay:y,strategy:w}=v.useContext(vhe),C=rft(r,m),N=d.indexOf(i),S=v.useMemo(()=>({sortable:{containerId:f,index:N,items:d},...o}),[f,o,N,d]),j=v.useMemo(()=>d.slice(d.indexOf(i)),[d,i]),{rect:_,node:k,isOver:T,setNodeRef:I}=ghe({id:i,data:S,disabled:C.droppable,resizeObserverConfig:{updateMeasurementsFor:j,...c}}),{active:E,activatorEvent:D,activeNodeRect:R,attributes:A,setNodeRef:F,listeners:z,isDragging:L,over:$,setActivatorNodeRef:H,transform:M}=Ddt({id:i,data:S,attributes:{...tft,...n},disabled:C.draggable}),B=yut(I,F),W=!!E,P=W&&!g&&KS(h)&&KS(x),G=!y&&L,Z=G&&P?M:null,Y=P?Z??(a??w)({rects:b,activeNodeRect:R,activeIndex:h,overIndex:x,index:N}):null,O=KS(h)&&KS(x)?s({id:i,items:d,activeIndex:h,overIndex:x}):N,q=E==null?void 0:E.id,U=v.useRef({activeId:q,items:d,newIndex:O,containerId:f}),V=d!==U.current.items,K=t({active:E,containerId:f,isDragging:L,isSorting:W,id:i,index:N,items:d,newIndex:U.current.newIndex,previousItems:U.current.items,previousContainerId:U.current.containerId,transition:u,wasDragging:U.current.activeId!=null}),Q=nft({disabled:!K,index:N,node:k,rect:_});return v.useEffect(()=>{W&&U.current.newIndex!==O&&(U.current.newIndex=O),f!==U.current.containerId&&(U.current.containerId=f),d!==U.current.items&&(U.current.items=d)},[W,O,f,d]),v.useEffect(()=>{if(q===U.current.activeId)return;if(q!=null&&U.current.activeId==null){U.current.activeId=q;return}const oe=setTimeout(()=>{U.current.activeId=q},50);return()=>clearTimeout(oe)},[q]),{active:E,activeIndex:h,attributes:A,data:S,rect:_,index:N,newIndex:O,items:d,isOver:T,isSorting:W,isDragging:L,listeners:z,node:k,overIndex:x,over:$,setNodeRef:B,setActivatorNodeRef:H,setDroppableNodeRef:I,setDraggableNodeRef:F,transform:Q??Y,transition:se()};function se(){if(Q||V&&U.current.newIndex===N)return eft;if(!(G&&!rT(D)||!u)&&(W||K))return Ki.Transition.toString({...u,property:whe})}}function rft(e,t){var n,r;return typeof e=="boolean"?{draggable:e,droppable:!1}:{draggable:(n=e==null?void 0:e.draggable)!=null?n:t.draggable,droppable:(r=e==null?void 0:e.droppable)!=null?r:t.droppable}}function ik(e){if(!e)return!1;const t=e.data.current;return!!(t&&"sortable"in t&&typeof t.sortable=="object"&&"containerId"in t.sortable&&"items"in t.sortable&&"index"in t.sortable)}const oft=[Fn.Down,Fn.Right,Fn.Up,Fn.Left],$z=(e,t)=>{let{context:{active:n,collisionRect:r,droppableRects:o,droppableContainers:s,over:i,scrollableAncestors:a}}=t;if(oft.includes(e.code)){if(e.preventDefault(),!n||!r)return;const c=[];s.getEnabled().forEach(f=>{if(!f||f!=null&&f.disabled)return;const h=o.get(f.id);if(h)switch(e.code){case Fn.Down:r.top<h.top&&c.push(f);break;case Fn.Up:r.top>h.top&&c.push(f);break;case Fn.Left:r.left>h.left&&c.push(f);break;case Fn.Right:r.left<h.left&&c.push(f);break}});const u=Put({collisionRect:r,droppableRects:o,droppableContainers:c});let d=Jfe(u,"id");if(d===(i==null?void 0:i.id)&&u.length>1&&(d=u[1].id),d!=null){const f=s.get(n.id),h=s.get(d),m=h?o.get(h.id):null,g=h==null?void 0:h.node.current;if(g&&m&&f&&h){const x=sT(g).some((j,_)=>a[_]!==j),y=Che(f,h),w=sft(f,h),C=x||!y?{x:0,y:0}:{x:w?r.width-m.width:0,y:w?r.height-m.height:0},N={x:m.left,y:m.top};return C.x&&C.y?N:uv(N,C)}}}};function Che(e,t){return!ik(e)||!ik(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function sft(e,t){return!ik(e)||!ik(t)||!Che(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function ift(e,t,n){const[r,o]=v.useState(null),[s,i]=v.useState(""),a=()=>{const g={id:`hierarchy_${Date.now()}`,label:s||"New Hierarchy",type:"static",steps:[],default:!1};t([...e,g]),i(""),o(g.id)},c=g=>{t(e.filter(b=>b.id!==g))},u=(g,b)=>{t(e.map(x=>x.id===g?{...x,...b}:x))};return{editingHierarchy:r,setEditingHierarchy:o,newHierarchyName:s,setNewHierarchyName:i,createNewHierarchy:a,deleteHierarchy:c,updateHierarchy:u,addStepToHierarchy:(g,b)=>{const x=n.find(C=>C.id===b);if(!x)return;const y={field:x,mode:"drillDown",label:`Drill to ${x.label}`,retainFilters:!0,preferredChartType:"bar"},w=e.find(C=>C.id===g);w&&u(g,{steps:[...w.steps,y]})},removeStepFromHierarchy:(g,b)=>{const x=e.find(y=>y.id===g);if(x){const y=[...x.steps];y.splice(b,1),u(g,{steps:y})}},updateStep:(g,b,x)=>{const y=e.find(w=>w.id===g);if(y){const w=y.steps.map((C,N)=>N===b?{...C,...x}:C);u(g,{steps:w})}},setDefaultHierarchy:g=>{t(e.map(b=>({...b,default:b.id===g})))}}}const JM="text-[13px] font-medium";function aft({step:e,hierarchyId:t,stepIndex:n,onUpdateStep:r,open:o,onOpenChange:s,trigger:i}){const a=v.useId();return l.jsxs(p.Popover,{open:o,onOpenChange:s,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:i}),l.jsx(p.PopoverContent,{className:"z-50 w-80 p-3",align:"start",children:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:JM,children:"Chart type"}),l.jsxs(p.Select,{value:e.preferredChartType||"bar",onValueChange:c=>{r(t,n,{preferredChartType:c})},children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"bar",children:"Bar chart"}),l.jsx(p.SelectItem,{value:"pie",children:"Pie chart"}),l.jsx(p.SelectItem,{value:"line",children:"Line chart"}),l.jsx(p.SelectItem,{value:"donut",children:"Donut chart"}),l.jsx(p.SelectItem,{value:"table",children:"Table"}),l.jsx(p.SelectItem,{value:"metric",children:"Metric"})]})]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:JM,children:"Step label"}),l.jsx(p.Input,{size:"sm",value:e.label||"",onChange:c=>r(t,n,{label:c.target.value}),placeholder:"Custom drill label"})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:JM,children:"Breadcrumb label template"}),l.jsx(p.Input,{size:"sm",value:e.breadcrumbLabelTemplate||"",onChange:c=>r(t,n,{breadcrumbLabelTemplate:c.target.value}),placeholder:"e.g., 'Region: {{value}}'"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Tn,{id:a,checked:e.retainFilters!==!1,onCheckedChange:c=>r(t,n,{retainFilters:c===!0})}),l.jsx(p.Label,{htmlFor:a,className:"cursor-pointer text-[13px] font-normal",children:"Retain filters when drilling"})]}),l.jsx("div",{className:"flex justify-end",children:l.jsx(p.Button,{size:"xs",variant:"outline",onClick:()=>s(!1),children:"Done"})})]})})]})}const lft="whitespace-nowrap rounded-[4px] border border-border/70 bg-muted/40 px-1 py-px font-mono text-[10px] text-muted-foreground";function cft({field:e,step:t,stepIndex:n,hierarchyId:r,onUpdateStep:o,onRemoveStep:s}){const[i,a]=v.useState(!1),{attributes:c,listeners:u,setNodeRef:d,transform:f,transition:h,isDragging:m}=tx({id:`${r}-${e.id}-${n}`,disabled:!1}),g={transform:Ki.Transform.toString(f),transition:h,opacity:m?.8:1,zIndex:m?1e3:1};return l.jsx("div",{ref:d,style:g,className:`relative ${i?"z-[9998]":""}`,...c,children:l.jsx(aft,{step:t,hierarchyId:r,stepIndex:n,onUpdateStep:o,open:i,onOpenChange:a,trigger:l.jsxs("div",{className:p.cn("flex h-7 cursor-pointer items-center gap-1.5 rounded-control border border-input bg-background px-2 transition-colors hover:bg-muted/60",m&&"border-ring"),...u,onClick:b=>{b.stopPropagation(),a(x=>!x)},children:[l.jsxs("div",{className:"pointer-events-none flex items-center gap-1.5",children:[l.jsx("span",{className:"whitespace-nowrap text-[12px] font-medium",children:e.label}),t.preferredChartType&&t.preferredChartType!=="bar"&&l.jsx("span",{className:lft,children:t.preferredChartType}),t.linkedInsightId&&l.jsx(aZ,{className:"h-3 w-3 text-muted-foreground","aria-label":"Linked insight"})]}),l.jsx("button",{type:"button","aria-label":`Remove ${e.label} from hierarchy`,className:"pointer-events-auto text-muted-foreground hover:text-destructive",onClick:b=>{b.stopPropagation(),s(r,n)},children:l.jsx(je.X,{className:"h-3 w-3"})})]})})})}function uft(e){return{sensors:oT(nb(Jb,{activationConstraint:{distance:5}}),nb(eC,{coordinateGetter:$z})),handleStepDragEnd:(r,o)=>{const{active:s,over:i}=r;if(!i||s.id===i.id)return;const a=s.id.replace(`${o.id}-`,""),c=i.id.replace(`${o.id}-`,""),u=o.steps.findIndex(f=>f.field.id===a),d=o.steps.findIndex(f=>f.field.id===c);if(u!==-1&&d!==-1&&u!==d){const f=ex(o.steps,u,d);e(o.id,{steps:f})}}}}function dft({hierarchy:e,onUpdateStep:t,onRemoveStep:n,onUpdateHierarchy:r}){const{sensors:o}=uft(r),[s,i]=v.useState(null),a=e.steps.filter(h=>h&&h.field&&h.field.id),u=a.map(h=>h.field).map((h,m)=>`${e.id}-${h.id}-${m}`),d=h=>{const m=h.active.id,g=Number.parseInt(m.split("-").pop()||"0"),b=a[g],x=b==null?void 0:b.field;i(x||null)},f=h=>{i(null);const{active:m,over:g}=h;if(!g||m.id===g.id)return;const b=Number.parseInt(m.id.split("-").pop()||"0"),x=Number.parseInt(g.id.split("-").pop()||"0");if(b!==x&&b<a.length&&x<a.length){const y=[...e.steps],[w]=y.splice(b,1);y.splice(x,0,w),r(e.id,{steps:y})}};return a.length===0?l.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:l.jsx("div",{className:"rounded-card border border-border/60 bg-muted/30 px-2.5 py-2 text-[12px] text-muted-foreground",children:"No drill steps configured. Add steps to create a drill hierarchy."})}):l.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:l.jsxs(nC,{sensors:o,collisionDetection:Jw,onDragStart:d,onDragEnd:f,children:[l.jsx(rC,{items:u,strategy:Oz,children:l.jsx("div",{className:"flex flex-wrap items-center gap-2",style:{minHeight:"40px"},children:a.map((h,m)=>{if(!h||!h.field||!h.field.id)return null;const g=[];m>0&&g.push(l.jsx(Ft.ChevronRight,{className:"pointer-events-none h-3.5 w-3.5 text-muted-foreground/70"},`arrow-${m}`));const b=m===0,x=m===a.length-1;return g.push(l.jsx(cft,{field:h.field,step:h,stepIndex:m,hierarchyId:e.id,onUpdateStep:t,onRemoveStep:n,isFirstField:b,isLastField:x},`field-${h.field.id}-${m}`)),g})})}),typeof window<"u"&&br.createPortal(l.jsx(Kb,{children:l.jsx(bhe,{style:{zIndex:9999},children:s?l.jsx("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-ring bg-background px-2",children:l.jsx("span",{className:"whitespace-nowrap text-[12px] font-medium",children:s.label})}):null})}),document.body)]})})}var YW=1,fft=.9,hft=.8,mft=.17,e2=.1,t2=.999,pft=.9999,gft=.99,bft=/[\\\/_+.#"@\[\(\{&]/,xft=/[\\\/_+.#"@\[\(\{&]/g,yft=/[\s-]/,She=/[\s-]/g;function SF(e,t,n,r,o,s,i){if(s===t.length)return o===e.length?YW:gft;var a=`${o},${s}`;if(i[a]!==void 0)return i[a];for(var c=r.charAt(s),u=n.indexOf(c,o),d=0,f,h,m,g;u>=0;)f=SF(e,t,n,r,u+1,s+1,i),f>d&&(u===o?f*=YW:bft.test(e.charAt(u-1))?(f*=hft,m=e.slice(o,u-1).match(xft),m&&o>0&&(f*=Math.pow(t2,m.length))):yft.test(e.charAt(u-1))?(f*=fft,g=e.slice(o,u-1).match(She),g&&o>0&&(f*=Math.pow(t2,g.length))):(f*=mft,o>0&&(f*=Math.pow(t2,u-o))),e.charAt(u)!==t.charAt(s)&&(f*=pft)),(f<e2&&n.charAt(u-1)===r.charAt(s+1)||r.charAt(s+1)===r.charAt(s)&&n.charAt(u-1)!==r.charAt(s))&&(h=SF(e,t,n,r,u+1,s+2,i),h*e2>f&&(f=h*e2)),f>d&&(d=f),u=n.indexOf(c,u+1);return i[a]=d,d}function ZW(e){return e.toLowerCase().replace(She," ")}function vft(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,SF(e,t,ZW(e),ZW(t),0,0,{})}var Hx='[cmdk-group=""]',n2='[cmdk-group-items=""]',wft='[cmdk-group-heading=""]',Nhe='[cmdk-item=""]',XW=`${Nhe}:not([aria-disabled="true"])`,NF="cmdk-item-select",Op="data-value",Cft=(e,t,n)=>vft(e,t,n),jhe=te.createContext(void 0),oC=()=>te.useContext(jhe),khe=te.createContext(void 0),zz=()=>te.useContext(khe),_he=te.createContext(void 0),Ihe=te.forwardRef((e,t)=>{let n=Lp(()=>{var W,P;return{search:"",value:(P=(W=e.value)!=null?W:e.defaultValue)!=null?P:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Lp(()=>new Set),o=Lp(()=>new Map),s=Lp(()=>new Map),i=Lp(()=>new Set),a=The(e),{label:c,children:u,value:d,onValueChange:f,filter:h,shouldFilter:m,loop:g,disablePointerSelection:b=!1,vimBindings:x=!0,...y}=e,w=p.useId(),C=p.useId(),N=p.useId(),S=te.useRef(null),j=Rft();Im(()=>{if(d!==void 0){let W=d.trim();n.current.value=W,_.emit()}},[d]),Im(()=>{j(6,R)},[]);let _=te.useMemo(()=>({subscribe:W=>(i.current.add(W),()=>i.current.delete(W)),snapshot:()=>n.current,setState:(W,P,G)=>{var Z,X,Y,O;if(!Object.is(n.current[W],P)){if(n.current[W]=P,W==="search")D(),I(),j(1,E);else if(W==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let q=document.getElementById(N);q?q.focus():(Z=document.getElementById(w))==null||Z.focus()}if(j(7,()=>{var q;n.current.selectedItemId=(q=A())==null?void 0:q.id,_.emit()}),G||j(5,R),((X=a.current)==null?void 0:X.value)!==void 0){let q=P??"";(O=(Y=a.current).onValueChange)==null||O.call(Y,q);return}}_.emit()}},emit:()=>{i.current.forEach(W=>W())}}),[]),k=te.useMemo(()=>({value:(W,P,G)=>{var Z;P!==((Z=s.current.get(W))==null?void 0:Z.value)&&(s.current.set(W,{value:P,keywords:G}),n.current.filtered.items.set(W,T(P,G)),j(2,()=>{I(),_.emit()}))},item:(W,P)=>(r.current.add(W),P&&(o.current.has(P)?o.current.get(P).add(W):o.current.set(P,new Set([W]))),j(3,()=>{D(),I(),n.current.value||E(),_.emit()}),()=>{s.current.delete(W),r.current.delete(W),n.current.filtered.items.delete(W);let G=A();j(4,()=>{D(),(G==null?void 0:G.getAttribute("id"))===W&&E(),_.emit()})}),group:W=>(o.current.has(W)||o.current.set(W,new Set),()=>{s.current.delete(W),o.current.delete(W)}),filter:()=>a.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:w,inputId:N,labelId:C,listInnerRef:S}),[]);function T(W,P){var G,Z;let X=(Z=(G=a.current)==null?void 0:G.filter)!=null?Z:Cft;return W?X(W,n.current.search,P):0}function I(){if(!n.current.search||a.current.shouldFilter===!1)return;let W=n.current.filtered.items,P=[];n.current.filtered.groups.forEach(Z=>{let X=o.current.get(Z),Y=0;X.forEach(O=>{let q=W.get(O);Y=Math.max(q,Y)}),P.push([Z,Y])});let G=S.current;F().sort((Z,X)=>{var Y,O;let q=Z.getAttribute("id"),U=X.getAttribute("id");return((Y=W.get(U))!=null?Y:0)-((O=W.get(q))!=null?O:0)}).forEach(Z=>{let X=Z.closest(n2);X?X.appendChild(Z.parentElement===X?Z:Z.closest(`${n2} > *`)):G.appendChild(Z.parentElement===G?Z:Z.closest(`${n2} > *`))}),P.sort((Z,X)=>X[1]-Z[1]).forEach(Z=>{var X;let Y=(X=S.current)==null?void 0:X.querySelector(`${Hx}[${Op}="${encodeURIComponent(Z[0])}"]`);Y==null||Y.parentElement.appendChild(Y)})}function E(){let W=F().find(G=>G.getAttribute("aria-disabled")!=="true"),P=W==null?void 0:W.getAttribute(Op);_.setState("value",P||void 0)}function D(){var W,P,G,Z;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let X=0;for(let Y of r.current){let O=(P=(W=s.current.get(Y))==null?void 0:W.value)!=null?P:"",q=(Z=(G=s.current.get(Y))==null?void 0:G.keywords)!=null?Z:[],U=T(O,q);n.current.filtered.items.set(Y,U),U>0&&X++}for(let[Y,O]of o.current)for(let q of O)if(n.current.filtered.items.get(q)>0){n.current.filtered.groups.add(Y);break}n.current.filtered.count=X}function R(){var W,P,G;let Z=A();Z&&(((W=Z.parentElement)==null?void 0:W.firstChild)===Z&&((G=(P=Z.closest(Hx))==null?void 0:P.querySelector(wft))==null||G.scrollIntoView({block:"nearest"})),Z.scrollIntoView({block:"nearest"}))}function A(){var W;return(W=S.current)==null?void 0:W.querySelector(`${Nhe}[aria-selected="true"]`)}function F(){var W;return Array.from(((W=S.current)==null?void 0:W.querySelectorAll(XW))||[])}function z(W){let P=F()[W];P&&_.setState("value",P.getAttribute(Op))}function L(W){var P;let G=A(),Z=F(),X=Z.findIndex(O=>O===G),Y=Z[X+W];(P=a.current)!=null&&P.loop&&(Y=X+W<0?Z[Z.length-1]:X+W===Z.length?Z[0]:Z[X+W]),Y&&_.setState("value",Y.getAttribute(Op))}function $(W){let P=A(),G=P==null?void 0:P.closest(Hx),Z;for(;G&&!Z;)G=W>0?Dft(G,Hx):Mft(G,Hx),Z=G==null?void 0:G.querySelector(XW);Z?_.setState("value",Z.getAttribute(Op)):L(W)}let H=()=>z(F().length-1),M=W=>{W.preventDefault(),W.metaKey?H():W.altKey?$(1):L(1)},B=W=>{W.preventDefault(),W.metaKey?z(0):W.altKey?$(-1):L(-1)};return te.createElement(p.Primitive.div,{ref:t,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:W=>{var P;(P=y.onKeyDown)==null||P.call(y,W);let G=W.nativeEvent.isComposing||W.keyCode===229;if(!(W.defaultPrevented||G))switch(W.key){case"n":case"j":{x&&W.ctrlKey&&M(W);break}case"ArrowDown":{M(W);break}case"p":case"k":{x&&W.ctrlKey&&B(W);break}case"ArrowUp":{B(W);break}case"Home":{W.preventDefault(),z(0);break}case"End":{W.preventDefault(),H();break}case"Enter":{W.preventDefault();let Z=A();if(Z){let X=new Event(NF);Z.dispatchEvent(X)}}}}},te.createElement("label",{"cmdk-label":"",htmlFor:k.inputId,id:k.labelId,style:Pft},c),lT(e,W=>te.createElement(khe.Provider,{value:_},te.createElement(jhe.Provider,{value:k},W))))}),Sft=te.forwardRef((e,t)=>{var n,r;let o=p.useId(),s=te.useRef(null),i=te.useContext(_he),a=oC(),c=The(e),u=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;Im(()=>{if(!u)return a.item(o,i==null?void 0:i.id)},[u]);let d=Ehe(o,s,[e.value,e.children,s],e.keywords),f=zz(),h=nf(j=>j.value&&j.value===d.current),m=nf(j=>u||a.filter()===!1?!0:j.search?j.filtered.items.get(o)>0:!0);te.useEffect(()=>{let j=s.current;if(!(!j||e.disabled))return j.addEventListener(NF,g),()=>j.removeEventListener(NF,g)},[m,e.onSelect,e.disabled]);function g(){var j,_;b(),(_=(j=c.current).onSelect)==null||_.call(j,d.current)}function b(){f.setState("value",d.current,!0)}if(!m)return null;let{disabled:x,value:y,onSelect:w,forceMount:C,keywords:N,...S}=e;return te.createElement(p.Primitive.div,{ref:p.composeRefs(s,t),...S,id:o,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!h,"data-disabled":!!x,"data-selected":!!h,onPointerMove:x||a.getDisablePointerSelection()?void 0:b,onClick:x?void 0:g},e.children)}),Nft=te.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:o,...s}=e,i=p.useId(),a=te.useRef(null),c=te.useRef(null),u=p.useId(),d=oC(),f=nf(m=>o||d.filter()===!1?!0:m.search?m.filtered.groups.has(i):!0);Im(()=>d.group(i),[]),Ehe(i,a,[e.value,e.heading,c]);let h=te.useMemo(()=>({id:i,forceMount:o}),[o]);return te.createElement(p.Primitive.div,{ref:p.composeRefs(a,t),...s,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&te.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:u},n),lT(e,m=>te.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?u:void 0},te.createElement(_he.Provider,{value:h},m))))}),jft=te.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,o=te.useRef(null),s=nf(i=>!i.search);return!n&&!s?null:te.createElement(p.Primitive.div,{ref:p.composeRefs(o,t),...r,"cmdk-separator":"",role:"separator"})}),kft=te.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,o=e.value!=null,s=zz(),i=nf(u=>u.search),a=nf(u=>u.selectedItemId),c=oC();return te.useEffect(()=>{e.value!=null&&s.setState("search",e.value)},[e.value]),te.createElement(p.Primitive.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":a,id:c.inputId,type:"text",value:o?e.value:i,onChange:u=>{o||s.setState("search",u.target.value),n==null||n(u.target.value)}})}),_ft=te.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...o}=e,s=te.useRef(null),i=te.useRef(null),a=nf(u=>u.selectedItemId),c=oC();return te.useEffect(()=>{if(i.current&&s.current){let u=i.current,d=s.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=u.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return h.observe(u),()=>{cancelAnimationFrame(f),h.unobserve(u)}}},[]),te.createElement(p.Primitive.div,{ref:p.composeRefs(s,t),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:c.listId},lT(e,u=>te.createElement("div",{ref:p.composeRefs(i,c.listInnerRef),"cmdk-list-sizer":""},u)))}),Ift=te.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:o,contentClassName:s,container:i,...a}=e;return te.createElement(Hk,{open:n,onOpenChange:r},te.createElement(qk,{container:i},te.createElement(db,{"cmdk-overlay":"",className:o}),te.createElement(fb,{"aria-label":e.label,"cmdk-dialog":"",className:s},te.createElement(Ihe,{ref:t,...a}))))}),Tft=te.forwardRef((e,t)=>nf(n=>n.filtered.count===0)?te.createElement(p.Primitive.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),Eft=te.forwardRef((e,t)=>{let{progress:n,children:r,label:o="Loading...",...s}=e;return te.createElement(p.Primitive.div,{ref:t,...s,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},lT(e,i=>te.createElement("div",{"aria-hidden":!0},i)))}),ri=Object.assign(Ihe,{List:_ft,Item:Sft,Input:kft,Group:Nft,Separator:jft,Dialog:Ift,Empty:Tft,Loading:Eft});function Dft(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function Mft(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function The(e){let t=te.useRef(e);return Im(()=>{t.current=e}),t}var Im=typeof window>"u"?te.useEffect:te.useLayoutEffect;function Lp(e){let t=te.useRef();return t.current===void 0&&(t.current=e()),t}function nf(e){let t=zz(),n=()=>e(t.snapshot());return te.useSyncExternalStore(t.subscribe,n,n)}function Ehe(e,t,n,r=[]){let o=te.useRef(),s=oC();return Im(()=>{var i;let a=(()=>{var u;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(u=d.current.textContent)==null?void 0:u.trim():o.current}})(),c=r.map(u=>u.trim());s.value(e,a,c),(i=t.current)==null||i.setAttribute(Op,a),o.current=a}),o}var Rft=()=>{let[e,t]=te.useState(),n=Lp(()=>new Map);return Im(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,o)=>{n.current.set(r,o),t({})}};function Aft(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function lT({asChild:e,children:t},n){return e&&te.isValidElement(t)?te.cloneElement(Aft(t),{ref:t.ref},n(t.props.children)):n(t)}var Pft={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const cT=te.forwardRef(({className:e,...t},n)=>l.jsx(ri,{ref:n,className:p.cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));cT.displayName=ri.displayName;const Bz=te.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[l.jsx(Ft.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(ri.Input,{ref:n,className:p.cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Bz.displayName=ri.Input.displayName;const uT=te.forwardRef(({className:e,...t},n)=>l.jsx(ri.List,{ref:n,className:p.cn("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));uT.displayName=ri.List.displayName;const dT=te.forwardRef((e,t)=>l.jsx(ri.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));dT.displayName=ri.Empty.displayName;const fT=te.forwardRef(({className:e,...t},n)=>l.jsx(ri.Group,{ref:n,className:p.cn("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));fT.displayName=ri.Group.displayName;const Dhe=te.forwardRef(({className:e,...t},n)=>l.jsx(ri.Separator,{ref:n,className:p.cn("-mx-1 h-px bg-border",e),...t}));Dhe.displayName=ri.Separator.displayName;const hT=te.forwardRef(({className:e,...t},n)=>l.jsx(ri.Item,{ref:n,className:p.cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",e),...t}));hT.displayName=ri.Item.displayName;const Fft=["[&_[cmdk-input-wrapper]]:px-2","[&_[cmdk-input-wrapper]_svg]:h-3.5","[&_[cmdk-input-wrapper]_svg]:w-3.5","[&_[cmdk-input]]:h-8","[&_[cmdk-input]]:py-0","[&_[cmdk-input]]:text-[13px]","[&_[cmdk-item]]:rounded-control","[&_[cmdk-item]]:px-2","[&_[cmdk-item]]:py-1.5","[&_[cmdk-item]]:text-[13px]","[&_[cmdk-empty]]:py-4","[&_[cmdk-empty]]:text-[12px]","[&_[cmdk-empty]]:text-muted-foreground"].join(" ");function Oft({hierarchy:e,sampleFieldReferences:t,onUpdateHierarchy:n,onDeleteHierarchy:r,onUpdateStep:o,onRemoveStep:s,onAddStep:i}){const[a,c]=v.useState(!1),{attributes:u,listeners:d,setNodeRef:f,transform:h,transition:m}=tx({id:e.id,disabled:!1}),g={transform:Ki.Transform.toString(h),transition:m},b=e.steps.filter(x=>x.field).map(x=>x.field.id);return l.jsxs("div",{ref:f,style:g,className:"hierarchy-container relative rounded-card border border-border bg-background p-3 transition-colors hover:border-border/80",children:[l.jsxs("div",{className:"mb-3 flex cursor-move items-center justify-between",...u,...d,children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("div",{onPointerDown:x=>x.stopPropagation(),onClick:x=>x.stopPropagation(),onKeyDown:x=>x.stopPropagation(),children:l.jsx(xi,{value:e.label||"",onSave:x=>{n(e.id,{label:x})},placeholder:"Hierarchy name",displayClassName:"text-[13px] font-medium",inputClassName:"text-[13px] font-medium"})})}),l.jsx("div",{className:"flex items-center gap-1",children:l.jsx(p.Button,{size:"xs",variant:"ghost","aria-label":"Delete hierarchy",className:"h-7 w-7 p-0 text-muted-foreground hover:text-destructive",onClick:x=>{x.stopPropagation(),r(e.id)},onPointerDown:x=>x.stopPropagation(),children:l.jsx(el,{className:"h-3.5 w-3.5"})})})]}),l.jsx(dft,{hierarchy:e,onUpdateStep:o,onRemoveStep:s,onUpdateHierarchy:n}),l.jsx("div",{className:"mt-3 border-t border-border/60 pt-3","data-hierarchy-editing":!0,children:a?l.jsxs(cT,{className:p.cn("rounded-card border border-border",Fft),children:[l.jsx(Bz,{placeholder:"Search fields…"}),l.jsxs(uT,{className:"max-h-40",children:[l.jsx(dT,{children:"No field found."}),l.jsx(fT,{children:t.filter(x=>!b.includes(x.id)).map(x=>l.jsx(hT,{value:x.label,onSelect:()=>{i(e.id,x.id),c(!1)},children:x.label},x.id))})]})]}):l.jsxs(p.Button,{type:"button",variant:"outline",size:"xs",onClick:x=>{x.preventDefault(),x.stopPropagation(),c(!0)},children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Add step"]})})]})}function Lft({open:e,onOpenChange:t,drillHierarchies:n,onUpdateHierarchies:r,availableFields:o}){const[s,i]=v.useState(n);v.useEffect(()=>{e&&i(n)},[e,n]);const a=v.useMemo(()=>o.filter(w=>p.getDataType(w.dataType)==="string"),[o]),c=oT(nb(Jb),nb(eC,{coordinateGetter:$z})),{createNewHierarchy:u,deleteHierarchy:d,updateHierarchy:f,addStepToHierarchy:h,removeStepFromHierarchy:m,updateStep:g,setDefaultHierarchy:b}=ift(s,i,a),x=w=>{const{active:C,over:N}=w;if(C.id!==(N==null?void 0:N.id)){const S=s.findIndex(_=>_.id===C.id),j=s.findIndex(_=>_.id===(N==null?void 0:N.id));i(ex(s,S,j))}},y=w=>{w||r(s),t(w)};return l.jsx(Mo,{modal:!0,open:e,onOpenChange:y,children:l.jsx(go,{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden p-0",onInteractOutside:w=>w.preventDefault(),onEscapeKeyDown:w=>w.preventDefault(),children:l.jsx(p.FocusScope,{trapped:!1,children:l.jsxs("div",{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden",children:[l.jsxs(Is,{className:"space-y-1 border-b border-border px-5 pb-3.5 pt-4 text-left",children:[l.jsx(bo,{className:"text-[15px] font-semibold tracking-tight",children:"Manage drill hierarchies"}),l.jsx(Ro,{className:"text-[12px] leading-[1.5] text-muted-foreground",children:"Create multiple drill paths for different analysis scenarios."})]}),l.jsx(p.ScrollArea,{className:"flex-1 px-5",children:l.jsxs("div",{className:"space-y-4 py-4",children:[s.length>0&&l.jsx("div",{className:"flex justify-end",children:l.jsxs(p.Button,{type:"button",size:"xs",onClick:w=>{w.preventDefault(),w.stopPropagation(),u()},children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Add hierarchy"]})}),s.length>0?l.jsx(nC,{sensors:c,collisionDetection:Jw,onDragEnd:x,children:l.jsx(rC,{items:s.map(w=>w.id),strategy:Lz,children:l.jsx("div",{className:"space-y-4",children:s.map(w=>l.jsx(Oft,{hierarchy:w,sampleFieldReferences:a,onUpdateHierarchy:f,onDeleteHierarchy:d,onSetDefaultHierarchy:b,onUpdateStep:g,onRemoveStep:m,onAddStep:h},w.id))})})}):l.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-center",children:[l.jsx(Pm,{className:"h-8 w-8 text-muted-foreground/40",strokeWidth:1.5}),l.jsxs("div",{className:"max-w-[360px] space-y-1",children:[l.jsx("p",{className:"text-[14px] font-medium",children:"No hierarchies yet"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Create your first hierarchy to enable drill-down interactions."})]}),l.jsxs(p.Button,{type:"button",size:"xs",variant:"outline",onClick:w=>{w.preventDefault(),w.stopPropagation(),u()},children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Create hierarchy"]})]})]})}),l.jsx("div",{className:"flex justify-end gap-1.5 border-t border-border px-5 py-3",children:l.jsx(p.Button,{size:"xs",onClick:()=>y(!1),children:"Done"})})]})})})})}const $ft="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function QW({hierarchy:e,selected:t,path:n,onSelect:r}){return l.jsxs("button",{type:"button",onClick:()=>r(e.id),className:p.cn("flex w-full flex-col items-start gap-0.5 rounded-control px-2 py-1.5 text-left transition-colors hover:bg-muted/60",t&&"bg-accent"),children:[l.jsx("span",{className:"w-full truncate text-[13px] font-medium",children:e.label||"Unnamed hierarchy"}),l.jsx("span",{className:"w-full truncate text-[12px] text-muted-foreground",children:n})]})}function zft({interaction:e,onUpdate:t,card:n,availableFields:r,onUpdateHierarchies:o,onManageHierarchies:s}){var E;const[i,a]=v.useState(!1),[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,m]=v.useState(!1),[g,b]=v.useState({}),x=v.useMemo(()=>{var D;return((D=n.interactionConfig)==null?void 0:D.drillHierarchies)||[]},[(E=n.interactionConfig)==null?void 0:E.drillHierarchies]),y=v.useMemo(()=>{var F,z;const D=[],R=e.trigger;if(!R)return D;let A;if(R.type==="attribute"){const L=r.find(H=>H.id===R.field.id);L&&(L.dataType==="date"||L.dataType==="timestamp")&&(A=L)}else if(R.type==="metric"){const L=(z=(F=n.config)==null?void 0:F.groupByColumns)==null?void 0:z.find($=>$.dataType==="date"||$.dataType==="timestamp");L&&(A=L)}if(A&&p.shouldAutoGenerateDateHierarchy(A,x)){const L=p.generateDateHierarchy(A);D.push(L)}return D},[r,x,e.trigger,n.config]),w=v.useMemo(()=>[...x,...y],[x,y]),C=w.find(D=>D.id===e.hierarchyId);te.useEffect(()=>{i&&C&&C.type==="date"?f(C.id):i||f(null)},[i,C]);const N=D=>{if(y.some(A=>A.id===D)&&o){const A=y.find(F=>F.id===D);A&&o([...x,A])}t({...e,hierarchyId:D}),a(!1)},S=()=>{a(!1),u(!0),s&&s()},j=D=>{o&&o(D)},_=D=>D.steps.map(A=>A.field.label||A.field.name).join(" → "),k=D=>D&&D.charAt(0).toUpperCase()+D.slice(1),T=(D,R,A)=>{var M,B;const F=(M=D.steps[R])==null?void 0:M.field;if(!(F!=null&&F.granularity))return;const z=qc.getTemporalBucketAuthoringOptions(F.granularity).find(W=>W.value==="custom"),L=g[R]||(((B=z==null?void 0:z.format)==null?void 0:B.presentation.mode)==="pattern"?z.format.presentation.pattern:"");b(W=>{const P={...W};return A==="custom"?P[R]=L:delete P[R],P});const $=[...D.steps];$[R]={...$[R],field:{...$[R].field,format:qc.resolveTemporalBucketAuthoringFormat(F.granularity,A,L),dateFormat:void 0,customFormat:void 0}};const H={...D,steps:$};if(o){const W=x.findIndex(P=>P.id===D.id);if(W>=0){const P=[...x];P[W]=H,o(P)}else o([...x,H])}},I=(D,R,A)=>{var $;b(H=>({...H,[R]:A}));const F=($=D.steps[R])==null?void 0:$.field;if(!(F!=null&&F.granularity))return;const z=[...D.steps];z[R]={...z[R],field:{...z[R].field,format:qc.resolveTemporalBucketAuthoringFormat(F.granularity,"custom",A),dateFormat:void 0,customFormat:void 0}};const L={...D,steps:z};if(o){const H=x.findIndex(M=>M.id===D.id);if(H>=0){const M=[...x];M[H]=L,o(M)}else o([...x,L])}};return l.jsxs("div",{className:"space-y-4",children:[l.jsx(Ys,{label:"Choose hierarchy",description:"Select which hierarchy to drill through when this interaction triggers",children:w.length>0?l.jsxs(l.Fragment,{children:[l.jsxs(p.Popover,{open:i,onOpenChange:a,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsxs(p.Button,{variant:"outline",role:"combobox",className:"h-auto w-full justify-between px-2.5 py-1.5",children:[l.jsx("div",{className:"flex min-w-0 flex-1 flex-col items-start gap-0.5 text-left",children:C?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"w-full truncate text-[13px] font-medium",children:C.label||"Unnamed hierarchy"}),l.jsx("span",{className:"w-full truncate text-[12px] font-normal text-muted-foreground",children:_(C)})]}):l.jsx("span",{className:"text-[13px] font-normal text-muted-foreground",children:"Select hierarchy…"})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[C&&C.type==="date"&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Customize date formats",className:"inline-flex h-6 w-6 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:D=>{D.stopPropagation(),m(!h)},onKeyDown:D=>{D.key!=="Enter"&&D.key!==" "||(D.preventDefault(),D.stopPropagation(),m(!h))},children:l.jsx(EO,{className:"h-3.5 w-3.5"})}),l.jsx(Ft.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]})]})}),l.jsxs(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:[l.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b border-border px-3",children:[l.jsx("span",{className:"text-[13px] font-medium",children:"Select hierarchy"}),l.jsxs(p.Button,{variant:"ghost",size:"xs",onClick:S,children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Create new"]})]}),l.jsxs("div",{className:"p-1.5",children:[y.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Auto-generated"}),y.map(D=>l.jsx(QW,{hierarchy:D,selected:e.hierarchyId===D.id,path:_(D),onSelect:N},D.id))]}),x.length>0&&l.jsxs(l.Fragment,{children:[y.length>0&&l.jsx("div",{className:"my-1.5 border-t border-border/60"}),x.map(D=>l.jsx(QW,{hierarchy:D,selected:e.hierarchyId===D.id,path:_(D),onSelect:N},D.id))]})]})]})]}),C&&C.type==="date"&&h&&l.jsxs("div",{className:"mt-3 space-y-3 rounded-card border border-border/60 p-3",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Customize date formats"}),l.jsx(p.Button,{variant:"ghost",size:"xs",className:"h-6",onClick:()=>m(!1),children:"Close"})]}),C.steps.map((D,R)=>{const A=D.field.granularity;if(!A)return null;const F=p.readTemporalBucketAuthoringSelection({fieldId:D.field.id,dataType:D.field.dataType,granularity:A,format:D.field.format,dateFormat:D.field.dateFormat,customFormat:D.field.customFormat,semanticTemporalPresentation:D.field.semanticTemporalPresentation}),z=qc.getTemporalBucketAuthoringOptions(A,F.format),L=g[R]!==void 0?"custom":F.value;return l.jsxs("div",{className:"space-y-1",children:[l.jsx(p.Label,{className:$ft,children:D.field.label||k(A)}),l.jsxs(p.Select,{value:L,onValueChange:$=>{T(C,R,$)},children:[l.jsx(p.SelectTrigger,{size:"xs",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:z.map($=>l.jsx(p.SelectItem,{value:$.value,className:"text-[12px]",children:$.label},$.value))})]}),L==="custom"&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx(p.Input,{size:"xs",placeholder:"Enter custom format (e.g., YYYY-MM-DD)",value:g[R]??F.customPattern??"",onChange:$=>{I(C,R,$.target.value)}}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Common tokens: YYYY (year), MM (month), DD (day), HH (hour), mm (minute)"})]})]},R)})]})]}):l.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[l.jsx(Pm,{className:"h-8 w-8 text-muted-foreground/40",strokeWidth:1.5}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-[13px] font-medium",children:"No hierarchies yet"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Create one to define your drill path."})]}),l.jsxs(p.Button,{variant:"outline",size:"xs",onClick:S,children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Create hierarchy"]})]})}),l.jsx(Lft,{open:c,onOpenChange:u,drillHierarchies:x,onUpdateHierarchies:j,availableFields:r})]})}function Bft({fields:e,selectedFieldIds:t,onSelectionChange:n,searchPlaceholder:r="Search fields…",className:o=""}){const[s,i]=v.useState(""),a=e.filter(d=>d.label.toLowerCase().includes(s.toLowerCase())||d.qualifiedEntityName&&d.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),c=()=>{const d=[...new Set([...t,...a.map(f=>f.id)])];n(d)},u=()=>{const d=a.map(f=>f.id);n(t.filter(f=>!d.includes(f)))};return l.jsxs("div",{className:p.cn("space-y-2",o),children:[l.jsx(p.Input,{size:"sm",placeholder:r,value:s,onChange:d=>i(d.target.value)}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Button,{size:"xs",variant:"ghost",onClick:c,children:"Select all"}),l.jsx(p.Button,{size:"xs",variant:"ghost",onClick:u,children:"Clear"}),l.jsxs("span",{className:"ml-auto text-[11px] tabular-nums text-muted-foreground",children:[t.length," of ",e.length," selected"]})]}),l.jsx("div",{className:"grid max-h-32 grid-cols-2 overflow-y-auto rounded-card border border-border/60",children:a.map(d=>l.jsxs("label",{className:"flex cursor-pointer items-center gap-2 px-2 py-1.5 text-[12px] transition-colors hover:bg-muted/50",children:[l.jsx(Tn,{checked:t.includes(d.id),onCheckedChange:f=>{n(f?[...t,d.id]:t.filter(h=>h!==d.id))}}),l.jsx("span",{className:"truncate",children:d.label})]},d.id))}),s&&a.length===0&&l.jsxs("div",{className:"py-4 text-center text-[12px] text-muted-foreground",children:['No fields found matching "',s,'"']})]})}const Vft=e=>["string","boolean"].includes(p.getDataType(e.dataType));function Hft({interaction:e,availableFields:t,onUpdate:n}){var i;const r=t.filter(Vft),o=((i=e.availableFields)==null?void 0:i.map(a=>a.id))||[],s=a=>{const c=r.filter(u=>a.includes(u.id));n({...e,availableFields:c})};return l.jsx("div",{className:"space-y-4",children:l.jsxs(Ys,{label:"Available dimensions",description:"Choose which fields users can explore dynamically",children:[l.jsx(Bft,{fields:r,selectedFieldIds:o,onSelectionChange:s,searchPlaceholder:"Search fields…"}),o.length===0&&l.jsxs("p",{className:"flex items-center gap-1.5 text-[12px] text-muted-foreground",children:[l.jsx(Ca,{className:"h-3.5 w-3.5 shrink-0"}),"Select at least one field to finish this interaction"]})]})})}function qft({value:e,onChange:t}){const[n,r]=v.useState(!1),[o,s]=v.useState(""),[i,a]=v.useState("all"),{currentUser:c}=ti(),{data:u,isLoading:d}=UO(lo.DASHBOARD,o),f=(u==null?void 0:u.dashboards)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(c==null?void 0:c.id):!0),m=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),s("")};return l.jsxs(p.Popover,{open:n,onOpenChange:r,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsx(p.Button,{variant:"outline",size:"sm",className:p.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:m?l.jsx("span",{className:"truncate",children:m.title}):"Choose dashboard…"})}),l.jsx(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:l.jsxs(p.Tabs,{value:i,onValueChange:b=>a(b),children:[l.jsx("div",{className:"border-b border-border p-2",children:l.jsxs("div",{className:"relative",children:[l.jsx(Ft.Search,{className:"absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),l.jsx(p.Input,{size:"sm",placeholder:"Search all dashboards…",value:o,onChange:b=>s(b.target.value),className:"pl-7"})]})}),l.jsxs(p.TabsList,{variant:"underline",className:"px-3",children:[l.jsx(p.TabsTrigger,{variant:"underline",value:"me",children:"Created by me"}),l.jsx(p.TabsTrigger,{variant:"underline",value:"all",children:"All"})]}),l.jsx(p.TabsContent,{value:i,className:"mt-0",children:l.jsx(p.ScrollArea,{className:"h-[300px]",children:d?l.jsx("div",{className:"p-8 text-center text-[13px] text-muted-foreground",children:"Loading dashboards…"}):h.length===0?l.jsx("div",{className:"p-8 text-center text-[13px] text-muted-foreground",children:o?`No dashboards found matching "${o}"`:i==="me"?"No dashboards created by you":"No dashboards available"}):l.jsx("div",{className:"p-1.5",children:h.map(b=>l.jsxs("button",{onClick:()=>g(b),className:p.cn("flex w-full items-start gap-2 rounded-control px-2 py-1.5 text-left transition-colors hover:bg-muted/60",e===b.id&&"bg-accent"),children:[l.jsx(em,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[13px] font-medium",children:b.title}),l.jsx("div",{className:"mt-0.5 text-[11px] uppercase tracking-[0.04em] text-muted-foreground",children:Uft(b.createdAt)})]})]},b.id))})})})]})})]})}function Uft(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear()){const i=t.getHours(),a=t.getMinutes(),c=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${c}`}const o=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),s=t.getDate();return`${o} ${s}`}const Wft=[{value:"interactionFilters",label:"Interaction filters",description:"Pass only the clicked element as a filter"},{value:"full",label:"All filters",description:"Pass current dashboard filters + clicked element"},{value:"none",label:"None",description:"Navigate without passing any filters"}];function Kft({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs(Ys,{label:"Target dashboard",description:"Select which dashboard to navigate to when this interaction triggers",children:[l.jsx(qft,{value:e.targetDashboardId,onChange:(n,r)=>{const o={...e,targetDashboardId:n};!e.label&&r&&(o.label=r),t(o)}}),!e.targetDashboardId&&l.jsxs("p",{className:"flex items-center gap-1.5 text-[12px] text-muted-foreground",children:[l.jsx(Ca,{className:"h-3.5 w-3.5 shrink-0"}),"Select a target dashboard to finish this interaction"]})]}),l.jsx(Ys,{label:"Propagate filters",description:"Choose what filters to pass to the target dashboard",children:l.jsxs(p.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsxs(p.SelectValue,{placeholder:"Choose context mode…",children:[e.contextMode==="interactionFilters"&&"Interaction filters",(e.contextMode==="full"||!e.contextMode)&&"All filters",e.contextMode==="none"&&"None"]})}),l.jsx(p.SelectContent,{children:Wft.map(n=>l.jsx(p.SelectItem,{value:n.value,className:lv,children:l.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-[13px] font-medium leading-[1.35]",children:n.label}),l.jsx("span",{className:"text-[12px] leading-[1.35] text-muted-foreground",children:n.description})]})},n.value))})]})}),l.jsx(Ys,{label:"Menu label",description:"How this interaction appears when multiple actions are available",children:l.jsx(p.Input,{size:"sm",value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:op(e.mode)})})]})}function Gft({value:e,onChange:t}){const[n,r]=v.useState(!1),[o,s]=v.useState(""),[i,a]=v.useState("all"),{currentUser:c}=ti(),{data:u,isLoading:d}=UO(lo.VISUAL,o),f=(u==null?void 0:u.visuals)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(c==null?void 0:c.id):!0),m=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),s("")};return l.jsxs(p.Popover,{open:n,onOpenChange:r,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsx(p.Button,{variant:"outline",size:"sm",className:p.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:m?l.jsx("span",{className:"truncate",children:m.title}):"Choose insight…"})}),l.jsx(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:l.jsxs(p.Tabs,{value:i,onValueChange:b=>a(b),children:[l.jsx("div",{className:"border-b border-border p-2",children:l.jsxs("div",{className:"relative",children:[l.jsx(Ft.Search,{className:"absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),l.jsx(p.Input,{size:"sm",placeholder:"Search all insights…",value:o,onChange:b=>s(b.target.value),className:"pl-7"})]})}),l.jsxs(p.TabsList,{variant:"underline",className:"px-3",children:[l.jsx(p.TabsTrigger,{variant:"underline",value:"me",children:"Created by me"}),l.jsx(p.TabsTrigger,{variant:"underline",value:"all",children:"All"})]}),l.jsx(p.TabsContent,{value:i,className:"mt-0",children:l.jsx(p.ScrollArea,{className:"h-[300px]",children:d?l.jsx("div",{className:"p-8 text-center text-[13px] text-muted-foreground",children:"Loading insights…"}):h.length===0?l.jsx("div",{className:"p-8 text-center text-[13px] text-muted-foreground",children:o?`No insights found matching "${o}"`:i==="me"?"No insights created by you":"No insights available"}):l.jsx("div",{className:"p-1.5",children:h.map(b=>l.jsxs("button",{onClick:()=>g(b),className:p.cn("flex w-full items-start gap-2 rounded-control px-2 py-1.5 text-left transition-colors hover:bg-muted/60",e===b.id&&"bg-accent"),children:[l.jsx(p.ChartColumn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[13px] font-medium",children:b.title}),l.jsx("div",{className:"mt-0.5 text-[11px] uppercase tracking-[0.04em] text-muted-foreground",children:Yft(b.createdAt)})]})]},b.id))})})})]})})]})}function Yft(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear()){const i=t.getHours(),a=t.getMinutes(),c=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${c}`}const o=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),s=t.getDate();return`${o} ${s}`}const Zft=[{value:"interactionFilters",label:"Interaction filters",description:"Pass only the clicked element as a filter"},{value:"full",label:"All filters",description:"Pass all current filters and selections"},{value:"none",label:"None",description:"Open insight without any filters"}];function Xft({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs(Ys,{label:"Target insight",description:"Select the saved insight to navigate to",children:[l.jsx(Gft,{value:e.targetInsightId,onChange:(n,r)=>{const o={...e,targetInsightId:n};!e.label&&r&&(o.label=r),t(o)}}),!e.targetInsightId&&l.jsxs("p",{className:"flex items-center gap-1.5 text-[12px] text-muted-foreground",children:[l.jsx(Ca,{className:"h-3.5 w-3.5 shrink-0"}),"Select a target insight to finish this interaction"]})]}),l.jsx(Ys,{label:"Propagate filters",description:"Choose what filters to pass to the insight",children:l.jsxs(p.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsxs(p.SelectValue,{placeholder:"Choose context mode…",children:[e.contextMode==="interactionFilters"&&"Interaction filters",(e.contextMode==="full"||!e.contextMode)&&"All filters",e.contextMode==="none"&&"None"]})}),l.jsx(p.SelectContent,{children:Zft.map(n=>l.jsx(p.SelectItem,{value:n.value,className:lv,children:l.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-[13px] font-medium leading-[1.35]",children:n.label}),l.jsx("span",{className:"text-[12px] leading-[1.35] text-muted-foreground",children:n.description})]})},n.value))})]})}),l.jsx(Ys,{label:"Display mode",description:"Choose how the insight should be displayed",children:l.jsxs(p.Select,{value:e.displayMode||"modal",onValueChange:n=>t({...e,displayMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsx(p.SelectValue,{placeholder:"Choose display mode…"})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"modal",children:"Open in modal"}),l.jsx(p.SelectItem,{value:"replace-card",children:"Replace the card"})]})]})}),l.jsx(Ys,{label:"Menu label",description:"How this interaction appears when multiple actions are available",children:l.jsx(p.Input,{size:"sm",value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:op(e.mode)})})]})}function Qft(e){return e.filter(t=>t.role==="groupby"||t.role==="pivotby").map(t=>({id:t.name,label:t.label||t.name,category:"attribute",field:t}))}function Jft(){return[{id:"card_id",label:"Card ID",category:"identifier"},{id:"frame_id",label:"Frame ID",category:"identifier"},{id:"sheet_id",label:"Sheet ID",category:"identifier"}]}function eht(e,t){const n=`{{${t}}}`;return e.includes(n)}function tht(e,t){return t.filter(n=>eht(e,n.id))}function nht(e,t,n){const r=`{{${t}}}`,o=e.slice(0,n)+r+e.slice(n),s=n+r.length;return{newTemplate:o,newCursorPosition:s}}function rht(e,t){let n=e;return t.forEach(r=>{const o=`{{${r.id}}}`;let s;if(r.category==="identifier")s=`${r.id.toUpperCase()}-abc123`;else{const i=r.label.toLowerCase();i.includes("name")?s="Example Name":i.includes("region")||i.includes("location")?s="California":i.includes("id")?s="ID-12345":i.includes("category")?s="Category A":s="Sample Value"}n=n.replace(new RegExp(o,"g"),s)}),n}const r2="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function oht({open:e,onOpenChange:t,interaction:n,availableFields:r,onSave:o}){const[s,i]=v.useState(n.urlTemplate||""),[a,c]=v.useState(0),[u,d]=v.useState(n.encodeParameters!==!1),[f,h]=v.useState(n.label||""),m=v.useRef(null);v.useEffect(()=>{e&&(i(n.urlTemplate||""),d(n.encodeParameters!==!1),h(n.label||""),c(0))},[e,n.urlTemplate,n.encodeParameters,n.label]);const g=Qft(r),b=Jft(),x=[...g,...b],y=tht(s,x),w=p.validateURLTemplate(s),C=s&&w.valid?rht(s,y):"",N=I=>{i(I.target.value),c(I.target.selectionStart)},S=I=>{const E=I.target;c(E.selectionStart)},j=I=>{const E=I.target;c(E.selectionStart)},_=I=>{const{newTemplate:E,newCursorPosition:D}=nht(s,I.id,a);i(E),c(D),m.current&&(m.current.focus(),setTimeout(()=>{m.current&&m.current.setSelectionRange(D,D)},0))},k=()=>{w.valid&&(o({...n,urlTemplate:s,parameters:y,encodeParameters:u,label:f}),t(!1))},T=()=>{t(!1)};return l.jsx(Mo,{open:e,onOpenChange:t,children:l.jsxs(go,{className:"flex max-h-[90vh] max-w-5xl flex-col gap-0 overflow-hidden p-0",onOpenAutoFocus:I=>{I.preventDefault(),setTimeout(()=>{var E;(E=m.current)==null||E.focus()},0)},children:[l.jsxs(Is,{className:"space-y-1 border-b border-border px-5 pb-3.5 pt-4 text-left",children:[l.jsx(bo,{className:"text-[15px] font-semibold tracking-tight",children:"Configure drill to URL"}),l.jsx(Ro,{className:"text-[12px] leading-[1.5] text-muted-foreground",children:"Build a custom URL with dynamic parameters that opens when users click on chart elements."})]}),l.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-5 py-4",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-5",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Label,{htmlFor:"url-template",className:"text-[13px] font-medium",children:"URL"}),l.jsx(p.TooltipProvider,{children:l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsx(p.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-[12px]",children:"Enter your URL and click parameters from the right panel to insert them. Parameters will be replaced with actual values when the URL is opened."})})]})})]}),l.jsx(zm,{ref:m,id:"url-template",value:s,onChange:N,onClick:S,onKeyUp:j,placeholder:"https://example.com/product/{{product_id}}?region={{region}}",className:"min-h-[200px] font-mono text-[12px] leading-[1.55]"}),!w.valid&&s&&l.jsx("div",{className:"space-y-0.5 text-[12px] text-destructive",children:w.errors.map((I,E)=>l.jsx("div",{children:I},E))}),C&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:r2,children:"Preview"}),l.jsx("p",{className:"break-all rounded-control border border-border/70 bg-muted/40 px-2 py-1.5 font-mono text-[11px] text-muted-foreground",children:C})]})]}),l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Parameters"}),l.jsx(p.TooltipProvider,{children:l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsx(p.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-[12px]",children:"Click any parameter to insert it into your URL at the cursor position. Attributes come from your chart data, identifiers are system values."})})]})})]}),l.jsxs("div",{className:"flex flex-col gap-4 rounded-card border border-border/60 p-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:r2,children:"Attributes"}),l.jsxs("div",{className:"space-y-0.5",children:[g.map(I=>l.jsx(JW,{parameter:I,isUsed:y.some(E=>E.id===I.id),onClick:()=>_(I)},I.id)),g.length===0&&l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"No attributes available"})]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:r2,children:"Identifiers"}),l.jsx("div",{className:"space-y-0.5",children:b.map(I=>l.jsx(JW,{parameter:I,isUsed:y.some(E=>E.id===I.id),onClick:()=>_(I)},I.id))})]})]})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Tn,{id:"encode-params",checked:u,onCheckedChange:I=>d(I===!0)}),l.jsx(p.Label,{htmlFor:"encode-params",className:"cursor-pointer text-[13px] font-normal",children:"URL encode parameters"}),l.jsx(p.TooltipProvider,{children:l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsx(p.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-[12px]",children:"Recommended. Encodes special characters in parameter values to ensure valid URLs (e.g., spaces become %20)."})})]})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Menu label"}),l.jsx(p.TooltipProvider,{children:l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsx(p.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-[12px]",children:"How this interaction appears when multiple actions are available"})})]})})]}),l.jsx(p.Input,{size:"sm",value:f,onChange:I=>h(I.target.value),placeholder:op("drillToURL")})]}),l.jsxs("p",{className:"flex items-start gap-1.5 text-[12px] text-muted-foreground",children:[l.jsx(p.Info,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"URLs always open in a new browser tab when clicked."]})]}),l.jsxs(tl,{className:"gap-1.5 border-t border-border px-5 py-3 sm:space-x-0",children:[l.jsx(p.Button,{size:"xs",variant:"outline",onClick:T,children:"Cancel"}),l.jsx(p.Button,{size:"xs",onClick:k,disabled:!w.valid,children:"Save"})]})]})})}function JW({parameter:e,isUsed:t,onClick:n}){var s,i;const r=e.category==="attribute"?OZ:ub,o=((s=e.field)==null?void 0:s.qualifiedFieldName)||((i=e.field)==null?void 0:i.name);return l.jsxs(p.Button,{type:"button",variant:"ghost",className:"h-auto w-full justify-start gap-2 px-2 py-1.5 font-normal hover:bg-muted/60",onClick:n,children:[l.jsx(r,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),l.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-start gap-0.5",children:[l.jsx("span",{className:"w-full truncate text-[13px]",children:e.label}),o&&l.jsx("span",{className:"w-full truncate font-mono text-[11px] text-muted-foreground",children:o})]}),t&&l.jsx(p.Check,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground"})]})}function sht({interaction:e,availableFields:t,onUpdate:n}){const[r,o]=v.useState(!1),s=!!e.urlTemplate;return l.jsxs("div",{className:"flex flex-col gap-4",children:[s?l.jsxs("div",{className:"flex flex-col gap-3 rounded-card border border-border/60 p-3",children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(Ld,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"text-[13px] font-medium",children:"URL template"})]}),l.jsx("p",{className:"break-all rounded-control border border-border/70 bg-muted/40 px-2 py-1.5 font-mono text-[11px] text-muted-foreground",children:e.urlTemplate})]}),l.jsxs(p.Button,{variant:"outline",size:"xs",onClick:()=>o(!0),children:[l.jsx(DO,{className:"h-3.5 w-3.5"}),"Edit"]})]}),l.jsxs("p",{className:"text-[12px] text-muted-foreground",children:[e.parameters&&e.parameters.length>0?`${e.parameters.length} parameter${e.parameters.length!==1?"s":""} · `:"","URL encoding"," ",e.encodeParameters!==!1?"enabled":"disabled"]})]}):l.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[l.jsx(Ld,{className:"h-8 w-8 text-muted-foreground/40",strokeWidth:1.5}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"No URL configured"}),l.jsx(p.Button,{variant:"outline",size:"xs",onClick:()=>o(!0),children:"Add custom URL"})]}),l.jsx(oht,{open:r,onOpenChange:o,interaction:e,availableFields:t,onSave:n})]})}function iht({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs(Ys,{label:"Fetch mode",description:"Choose when to load the detailed data",children:[l.jsxs(p.Select,{value:e.fetchMode||"lazy",onValueChange:n=>t({...e,fetchMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsx(p.SelectValue,{placeholder:"Choose fetch mode…"})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"lazy",className:lv,children:l.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-[13px] font-medium leading-[1.35]",children:"Lazy loading"}),l.jsx("span",{className:"text-[12px] leading-[1.35] text-muted-foreground",children:"Fetch data only when user clicks"})]})}),l.jsx(p.SelectItem,{value:"preloaded",className:lv,children:l.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-[13px] font-medium leading-[1.35]",children:"Preloaded"}),l.jsx("span",{className:"text-[12px] leading-[1.35] text-muted-foreground",children:"Fetch all data when dashboard loads"})]})})]})]}),l.jsxs("p",{className:"flex gap-1.5 text-[12px] leading-[1.5] text-muted-foreground",children:[l.jsx(p.Info,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),l.jsx("span",{children:e.fetchMode==="lazy"?"Data is fetched on-demand when the user clicks. Best for large datasets or when detailed data isn't always needed.":"Data is fetched when the dashboard loads. Best for small datasets or when instant drill-down is required."})]})]}),l.jsx(Ys,{label:"Record limit",description:"Maximum number of detailed records to show (0 for unlimited)",children:l.jsx(p.Input,{size:"sm",type:"number",min:"0",placeholder:"100",value:e.inlineLimit??100,onChange:n=>{const r=parseInt(n.target.value)||0;t({...e,inlineLimit:r})}})}),l.jsx(Ys,{label:"Display mode",description:"How to display the detailed records",children:l.jsxs(p.Select,{value:e.displayMode||"table",onValueChange:n=>t({...e,displayMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsx(p.SelectValue,{placeholder:"Choose display mode…"})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"table",children:"Table view"}),l.jsx(p.SelectItem,{value:"list",children:"List view"}),l.jsx(p.SelectItem,{value:"cards",children:"Card view"})]})]})}),l.jsxs("div",{className:"divide-y divide-border/60 border-y border-border/60",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3 py-2.5",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Show in modal"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Display detailed records in a modal overlay"})]}),l.jsx(p.Switch,{checked:e.showInModal??!1,onCheckedChange:n=>t({...e,showInModal:n})})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 py-2.5",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Allow export"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Enable users to export the detailed records"})]}),l.jsx(p.Switch,{checked:e.allowExport??!0,onCheckedChange:n=>t({...e,allowExport:n})})]})]}),l.jsx(Ys,{label:"Menu label",description:"How this interaction appears when multiple actions are available",children:l.jsx(p.Input,{size:"sm",value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:op(e.mode)})})]})}function aht({interaction:e,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onUpdate:i,onRemove:a}){const c=e.trigger!==void 0,u=e.mode!==void 0,d=c&&u,[f,h]=v.useState(!d),m=()=>{var y;if(!c)return"Configure interaction";const b=`When ${((y=e.trigger)==null?void 0:y.field.label)||"..."}`;if(!u)return`${b} → Choose action`;const x=e.label||op(e.mode);return`${b} → ${x}`},g=u?Vj(e.mode):null;return l.jsxs("div",{className:"relative rounded-card border border-border bg-card text-card-foreground",children:[l.jsx(p.Button,{variant:"ghost",size:"xs",className:"absolute right-1.5 top-1.5 z-10 h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,"aria-label":"Remove interaction",children:l.jsx(je.X,{className:"h-3.5 w-3.5"})}),l.jsxs(vu,{open:f,onOpenChange:h,children:[l.jsx(wu,{asChild:!0,children:l.jsxs(p.Button,{variant:"ghost",className:"h-auto w-full justify-between gap-3 rounded-card px-3 py-2.5 pr-10 hover:bg-muted/50",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[g&&l.jsx(g,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate text-left text-[13px] font-medium",children:m()})]}),l.jsx(je.ChevronDown,{className:p.cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",f&&"rotate-180")})]})}),l.jsx(Cu,{children:l.jsxs("div",{className:"space-y-5 border-t border-border/60 p-4",children:[l.jsx("div",{className:"space-y-3",children:c?l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"text-[13px] font-medium",children:["When I click on"," ",l.jsx("span",{className:"text-muted-foreground",children:"(value of)"})]}),e.trigger&&l.jsxs("button",{type:"button","aria-label":`Change trigger field (currently ${e.trigger.field.label})`,className:"inline-flex h-6 items-center gap-1 rounded-control border border-transparent bg-muted/60 pl-1 pr-1.5 text-[11px] font-medium text-foreground transition-colors hover:border-border/60 hover:bg-muted [&_svg]:h-3 [&_svg]:w-3",onClick:()=>{i({...e,trigger:void 0})},children:[ek(e.trigger.field.dataType),l.jsx("span",{children:e.trigger.field.label})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"text-[13px] font-medium",children:"When I click on"}),l.jsx(put,{value:e.trigger,onChange:b=>{i({...e,trigger:b})},metrics:t,attributes:n})]})}),c&&l.jsx(l.Fragment,{children:l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"text-[13px] font-medium",children:"I want to"}),l.jsx(gut,{value:e.mode,onChange:b=>{if(!e.trigger){console.error("Trigger must be defined before selecting action");return}const x={mode:b,trigger:e.trigger};switch(b){case"clickFilter":i({...x,mode:"clickFilter",filterFields:[]});break;case"drillDown":i({...x,mode:"drillDown",filterFields:[]});break;case"dynamicDrill":i({...x,mode:"dynamicDrill",availableFields:[]});break;case"drillThrough":i({...x,mode:"drillThrough",filterFields:[],targetDashboardId:""});break;case"drillToDetail":i({...x,mode:"drillToDetail",filterFields:[]});break;case"drillToURL":i({...x,mode:"drillToURL",filterFields:[],urlTemplate:"",parameters:[],encodeParameters:!0});break;case"inlineDrill":i({...x,mode:"inlineDrill",filterFields:[]});break}}})]})}),c&&u&&l.jsxs(l.Fragment,{children:[l.jsx(p.Separator,{}),l.jsx(lht,{interaction:e,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onUpdate:i})]})]})})]})]})}function lht({interaction:e,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onUpdate:i}){switch(e.mode){case"clickFilter":return l.jsx(xut,{interaction:e,onUpdate:a=>i(a)});case"drillDown":return l.jsx(zft,{interaction:e,onUpdate:a=>i(a),card:o,availableFields:r,onUpdateHierarchies:s});case"dynamicDrill":return l.jsx(Hft,{interaction:e,onUpdate:a=>i(a),availableFields:r});case"drillThrough":return l.jsx(Kft,{interaction:e,onUpdate:a=>i(a)});case"drillToDetail":return l.jsx(Xft,{interaction:e,onUpdate:a=>i(a)});case"drillToURL":return l.jsx(sht,{interaction:e,availableFields:[...t,...n],onUpdate:a=>i(a)});case"inlineDrill":return l.jsx(iht,{interaction:e,onUpdate:a=>i(a)});default:return l.jsx("div",{className:"text-[13px] text-muted-foreground",children:"Unknown interaction type"})}}function cht({interactions:e,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onChange:i}){const[a,c]=v.useState(null),u=()=>{const h=_et().id,m={id:h};i([...e,m]),c(h)},d=(h,m)=>{const g=e[h],b={...m,id:m.id||(g==null?void 0:g.id)},x=[...e];x[h]=b,i(x)},f=h=>{var g;const m=e.filter((b,x)=>x!==h);i(m),a===((g=e[h])==null?void 0:g.id)&&c(null)};return l.jsxs("div",{className:"space-y-4",children:[e.length>0?l.jsx("div",{className:"space-y-3",children:e.map((h,m)=>l.jsx(aht,{interaction:h,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onUpdate:g=>d(m,g),onRemove:()=>f(m)},h.id||m))}):l.jsxs("div",{className:"flex flex-col items-center gap-3 py-10 text-center",children:[l.jsx(Ive,{className:"h-8 w-8 text-muted-foreground/40",strokeWidth:1.5}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-[13px] font-medium",children:"No interactions yet"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Add one to make this chart respond to clicks."})]}),l.jsxs(p.Button,{onClick:u,size:"xs",variant:"outline",children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Add interaction"]})]}),e.length>0&&l.jsx("div",{className:"flex justify-start pt-2",children:l.jsxs(p.Button,{onClick:u,size:"xs",variant:"outline",children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Add interaction"]})})]})}function Mhe(e){const t=p.fromSemanticFormat(e.format);if((t==null?void 0:t.type)==="temporal_bucket"){if(!e.granularity)return{};const n=va.resolveApplicableTemporalBucketFormat(t,e.granularity);return n?{granularity:e.granularity,semanticTemporalPresentation:{granularity:e.granularity,format:n}}:{}}return{...e.granularity?{granularity:e.granularity}:{},...t?{format:t}:{}}}const uht=[],dht=[],fht=[];function o2(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function hht(e){return e.flatMap(t=>t.columns.map(n=>({...n,id:n.id||`${t.entityId}-${n.name}`,name:n.name,qualifiedFieldName:n.qualifiedFieldName||n.name,dataType:n.dataType,qualifiedEntityName:n.qualifiedEntityName||t.qualifiedEntityName,label:n.label||p.toTitleCase(n.name),description:n.description,entityId:n.entityId||t.entityId,entityName:n.entityName||t.entityName,entityType:n.entityType||t.entityType})))}function Vz(e){var N;const{tokenProps:t}=It(),n=p.useDashboardStore(S=>S.authToken)||e,{selectedConnection:r,hasSchemaSupport:o}=Eee(e),s=p.useEditorStore(S=>{var j;return(j=S.card.dataSource)==null?void 0:j.connectionId}),i=p.useEditorStore(S=>{var j;return(j=S.card.dataSource)==null?void 0:j.semanticDomainId}),a=p.useEditorStore(S=>{var j;return(j=S.card.dataSource)==null?void 0:j.selectedEntities}),c=v.useMemo(()=>(a==null?void 0:a.filter(S=>S.type==="model"))||uht,[a]),u=v.useMemo(()=>(a==null?void 0:a.filter(S=>dt.DATABASE_ENTITY_TYPES.includes(S.type)))||dht,[a]),d=v.useMemo(()=>(a==null?void 0:a.filter(S=>S.type==="dataset"))||fht,[a]);function f(S){var j;if(S.type==="dataset")return!!s&&!!S.domainId&&!!S.name;if(S.type==="model")return!!s&&!!S.id;if(dt.DATABASE_ENTITY_TYPES.includes(S.type)){const _=((j=r==null?void 0:r.capabilities)==null?void 0:j.path)||[],k=_.includes("database"),T=_.includes("schema")||o;return!(!s||!S.name||k&&!S.database||T&&!S.schema)}return!1}const h=[...c,...u,...d],m=ib({queries:h.map(S=>{let j={};return S.type==="model"?j=o2({connection_id:s,datamodel_id:S.id,database_name:"",schema_name:"",table_name:""}):S.type==="dataset"?j=o2({connection_id:S.connectionId,domain_id:S.domainId,dataset_name:S.name,database_name:S.database,schema_name:S.schema,table_name:S.table}):j=o2({connection_id:s,datamodel_id:"",database_name:S.database,schema_name:S.schema,table_name:S.name}),{queryKey:["columns",s,S,i||null],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",j),enabled:!!s&&f(S)}})}),g=m.some(S=>S.isPending&&S.fetchStatus==="fetching"),b=m.some(S=>S.isError),x=(N=m.find(S=>S.isError))==null?void 0:N.error,y=m.map((S,j)=>{var D,R;const _=h[j],k=((D=S.data)==null?void 0:D.columns)||[],T=_.type==="dataset"?(R=k.find(A=>A.entityName))==null?void 0:R.entityName:void 0,I=T||_.name,E=p.getQualifiedEntityName(_.type==="dataset"&&T?{..._,name:T}:_);return{entityId:_.id||_.name,entityType:_.type,entityName:I,label:_.label,description:_.description,qualifiedEntityName:E,columns:k.map(A=>{const F=_.type==="dataset"?A.entityName||I:_.name,z=A.qualifiedEntityName||(_.type==="dataset"&&F?p.getQualifiedEntityName({..._,name:F}):E);return{id:`${F}-${A.column_name}`,name:A.column_name,qualifiedFieldName:A.qualifiedFieldName||A.column_name,dataType:A.data_type,label:A.label||p.toLabel(A.column_name),description:A.description||"",qualifiedEntityName:z,entityId:A.entityId||_.id||_.id||F,entityName:F,entityType:A.entityType||_.type,role:A.role,expression:A.expression,calculatedFormula:A.calculatedFormula,derivedField:A.derivedField,...Mhe(A),aggregate:A.aggregate}})}}).filter(S=>{var j;return((j=S==null?void 0:S.columns)==null?void 0:j.length)>0})||[],w=m.flatMap(S=>{var j;return((j=S.data)==null?void 0:j.calculatedFields)||[]}).map(S=>({...S,id:p.getStableDomainCalculatedFieldId({...S}),fieldScope:"domain"}));if(w.length>0){const S=new Map;w.forEach(j=>{const _=p.getStableDomainCalculatedFieldId(j);S.has(_)||S.set(_,j)}),y.unshift({entityId:dt.CALCULATED_FIELDS_GROUP_ID,entityType:"dataset",entityName:dt.CALCULATED_FIELDS_GROUP_NAME,label:"Calculated Fields",description:"Domain-level calculated metrics and dimensions",qualifiedEntityName:dt.CALCULATED_FIELDS_GROUP_NAME,columns:Array.from(S.values())})}const C=hht(y);return{columnGroups:y,columns:C,isLoading:g,hasError:b,error:x,refetch:async()=>{await Promise.all(m.map(S=>S.refetch()))}}}function mht(e){const t=n=>{if(!n||typeof n!="object")return!1;const r=n;return Array.isArray(r.cards)};if(!e)return null;if(typeof e=="string")try{const n=JSON.parse(e);return t(n)?n:null}catch{return null}return t(e)?e:null}function ak(e){return Array.isArray(e)?e.map(t=>ak(t)):e&&typeof e=="object"?Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).reduce((t,[n,r])=>(t[n]=ak(r),t),{}):e}function s2(e,t){return JSON.stringify(ak(e))===JSON.stringify(ak(t))}function pht(){var Y,O,q,U,V,K,Q,se,oe;const{open:e,frameId:t,cardId:n,closePopover:r,anchorPosition:o}=K5(),{authToken:s,tokenProps:i}=It(),a=Wr(),{updateCurrentDashboardCard:c,updateFrameCard:u}=p.useDashboardActions(),{setCard:d}=p.useEditorActions(),f=p.useDashboardStore(me=>me.dashboard),h=((Y=f==null?void 0:f.sheets)==null?void 0:Y.flatMap(me=>me.frames||[]).find(me=>(me==null?void 0:me.id)===t))||null,m=h&&n?h.cards.find(me=>me.id===n):null,g=!!(h!=null&&h.visualId&&m),b=Bk((h==null?void 0:h.visualId)||"",{enabled:e&&g&&!!(s!=null&&s.accessToken)&&!!(i!=null&&i.apiServiceUrl)}),x=((O=b.data)==null?void 0:O.frameObject)||((U=(q=b.data)==null?void 0:q.visual)==null?void 0:U.frameObject),y=v.useMemo(()=>mht(x),[x]),w=((V=b.data)==null?void 0:V.lastModified)||((Q=(K=b.data)==null?void 0:K.visual)==null?void 0:Q.lastModified),C=v.useMemo(()=>{if(!m||!h||!y)return null;const me=m.linkedSourceCardId&&y.cards.find(ue=>ue.id===m.linkedSourceCardId);if(me)return me;const le=h.cards.findIndex(ue=>ue.id===m.id);return le>=0&&y.cards[le]||null},[m,h,y]),N=v.useMemo(()=>{const me=new Map;return!h||!y||h.cards.forEach((le,ue)=>{var de;const ne=le.linkedSourceCardId||((de=y.cards[ue])==null?void 0:de.id);ne&&me.set(ne,le.id)}),me},[h,y]),S=v.useMemo(()=>{var le;if(!C)return[];const me=Qf((le=C.interactionConfig)==null?void 0:le.interactions);return H1(me,N)},[C,N]),j=v.useMemo(()=>m?jM(S,m.linkedInteractionTargetOverrides):[],[m,S]),_=g?C:m,k=g&&!!x&&!y&&!b.isFetching;v.useEffect(()=>{if(!e)return;const me=g&&C||m;me&&d(me)},[e,g,C,m,d]);const{columns:T}=Vz(),I=_==null?void 0:_.config,E=T,D=(I==null?void 0:I.metricColumns)||[],R=[...(I==null?void 0:I.groupByColumns)||[],...(I==null?void 0:I.pivotByColumns)||[]],[A,F]=v.useState(((se=_==null?void 0:_.interactionConfig)==null?void 0:se.drillHierarchies)||[]),[z,L]=v.useState(((oe=_==null?void 0:_.interactionConfig)==null?void 0:oe.allowedDrillTargets)||[]),[$,H]=v.useState([]),[M,B]=v.useState(!1),W=v.useRef(null),P=v.useMemo(()=>`${e}-${t}-${n}-${g?(C==null?void 0:C.id)||"loading":(m==null?void 0:m.id)||"none"}`,[e,t,n,g,C==null?void 0:C.id,m==null?void 0:m.id]);v.useEffect(()=>{e||(W.current=null)},[e]),v.useEffect(()=>{var me,le,ue;!e||!_||g&&!C||W.current!==P&&(F(((me=_.interactionConfig)==null?void 0:me.drillHierarchies)||[]),L(((le=_.interactionConfig)==null?void 0:le.allowedDrillTargets)||[]),H(g?j:Qf((ue=_.interactionConfig)==null?void 0:ue.interactions)),W.current=P)},[e,_,P,g,C,j]);const G=async()=>{var me,le,ue,ne,de;if(m){B(!0);try{const Ce=Qf(p.normalizeInteractionsForSave($));if(!g||!(h!=null&&h.visualId)||!y||!C){const Ke={...m,interactionConfig:{...m.interactionConfig,drillHierarchies:A,allowedDrillTargets:z,interactions:Ce}},We=(le=(me=f==null?void 0:f.sheets)==null?void 0:me.find(Qe=>(Qe.frames||[]).some(xe=>xe.id===(h==null?void 0:h.id))))==null?void 0:le.id;We&&(h!=null&&h.id)&&u?u(We,h.id,Ke):c(Ke),d(Ke),r();return}const ce=Qf((ue=C.interactionConfig)==null?void 0:ue.interactions),ie=jet(Ce,ce),we=((ne=C.interactionConfig)==null?void 0:ne.drillHierarchies)||[],fe=((de=C.interactionConfig)==null?void 0:de.allowedDrillTargets)||[],ae=!s2(A,we)||!s2(z,fe)||!s2(ie,ce),ee={...C,interactionConfig:{...C.interactionConfig,drillHierarchies:A,allowedDrillTargets:z,interactions:ie}},J={...y,cards:y.cards.map(Ke=>Ke.id===C.id?ee:Ke)};if(ae){if(!(i!=null&&i.apiServiceUrl)||!(s!=null&&s.accessToken))throw new Error("Missing authentication context for visual update");const Ke=await fetch(`${i.apiServiceUrl}/management/v1/visuals/${h.visualId}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(s==null?void 0:s.accessToken)||""}`},body:JSON.stringify({frameObject:J,expectedLastModified:w})});if(!Ke.ok){const Qe=await Ke.json().catch(()=>({})),xe=new Error((Qe==null?void 0:Qe.error)||"Failed to update visual");throw xe.status=Ke.status,xe}const We=await Ke.json();a.setQueryData(["resource-by-id","visual",h.visualId],We)}const re=H1(Qf(ie),N),pe=re.filter(Ke=>Ke.id).map(Ke=>Ke.id),Ee=hU(ket(Ce,re),pe),Te=jM(re,Ee),ze={...m,linkedSourceCardId:m.linkedSourceCardId||C.id,linkedInteractionTargetOverrides:Ee,interactionConfig:{...m.interactionConfig,drillHierarchies:A,allowedDrillTargets:z,interactions:Te}},Pe=Ke=>{const We=new Map;return Ke.cards.forEach((Qe,xe)=>{var Ae;const Ve=Qe.linkedSourceCardId||((Ae=y.cards[xe])==null?void 0:Ae.id);Ve&&We.set(Ve,Qe.id)}),We},He=Ke=>{const We=Ke.cards.find(xe=>xe.linkedSourceCardId===C.id);if(We)return We;const Qe=y.cards.findIndex(xe=>xe.id===C.id);return Qe>=0&&Ke.cards[Qe]||null},ye=[];if((f.sheets||[]).forEach(Ke=>{(Ke.frames||[]).forEach(We=>{if(We.visualId!==h.visualId)return;const Qe=He(We);if(!Qe)return;const xe=Pe(We),Ve=H1(Qf(ie),xe),Ae=Ve.filter($e=>$e.id).map($e=>$e.id),ke=We.id===h.id&&Qe.id===m.id?Ee:Qe.linkedInteractionTargetOverrides,Be=hU(ke,Ae),Ie=jM(Ve,Be);ye.push({sheetId:Ke.id,frameId:We.id,isCurrentCard:We.id===h.id&&Qe.id===m.id,card:{...Qe,linkedSourceCardId:Qe.linkedSourceCardId||C.id,linkedInteractionTargetOverrides:Be,interactionConfig:{...Qe.interactionConfig,drillHierarchies:A,allowedDrillTargets:z,interactions:Ie}}})})}),ye.length>0&&u){ye.forEach(We=>{u(We.sheetId,We.frameId,We.card)});const Ke=ye.find(We=>We.isCurrentCard);Ke||c(ze),d((Ke==null?void 0:Ke.card)||ze)}else c(ze),d(ze);r()}catch(Ce){Ce.status===409?(lt.error("This saved visual was updated by another editor. Refresh and retry."),W.current=null,await b.refetch()):lt.error(Ce.message||"Failed to save interactions")}finally{B(!1)}}},Z=()=>{W.current=null,r()};if(!e||!t||!n||!m||!o)return null;const X={position:"fixed",left:`${o.left}px`,top:`${o.top}px`,width:`${o.width}px`,height:`${o.height}px`};return l.jsxs(p.Popover,{modal:!1,open:e,onOpenChange:me=>!me&&r(),children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsx("div",{style:X,className:"pointer-events-none invisible","aria-hidden":"true"})}),l.jsxs(p.PopoverContent,{onEscapeKeyDown:me=>me.preventDefault(),className:"mt-5 flex max-h-[70vh] w-[600px] max-w-4xl flex-col overflow-hidden p-0",align:"start",side:"right",sideOffset:20,children:[l.jsx(p.Arrow2,{className:"fill-border",width:12,height:8}),l.jsxs("div",{className:"flex flex-col border-b border-border px-5 pb-3.5 pt-4",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("h2",{className:"text-[15px] font-semibold tracking-tight",children:"Configure interactions"}),$.length>0&&l.jsx("span",{className:"text-[11px] tabular-nums text-muted-foreground/70",children:$.length})]}),l.jsxs("p",{className:"mt-1 text-[12px] leading-[1.5] text-muted-foreground",children:["Set up drill behaviors for ",(m==null?void 0:m.title)||"this chart"]}),g&&l.jsx("p",{className:"mt-2 text-[12px] leading-[1.5] text-muted-foreground",children:"Logic is owned by the saved visual. Filter target routing is saved per dashboard instance."})]}),l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:l.jsx("div",{className:"space-y-6 px-5 py-4",children:g&&!C?l.jsx("p",{className:"text-[13px] text-muted-foreground",children:b.isFetching?"Loading saved visual interaction config...":k?"Unable to load interaction settings for this saved visual. Please refresh or relink the visual.":"Unable to map this dashboard card to its source card in the saved visual. Re-link the visual to continue."}):l.jsx("div",{children:l.jsx("div",{className:"grid grid-cols-1 gap-4",children:l.jsx(cht,{interactions:$,metrics:D,attributes:R,availableFields:E,card:{..._||m,interactionConfig:{...(_==null?void 0:_.interactionConfig)||m.interactionConfig,drillHierarchies:A}},onUpdateHierarchies:F,onChange:me=>H(me)})})})})}),l.jsxs("div",{className:"flex justify-end gap-1.5 border-t border-border px-5 py-3",children:[l.jsx(p.Button,{size:"xs",variant:"outline",onClick:Z,children:"Cancel"}),l.jsx(p.Button,{size:"xs",onClick:G,disabled:M||g&&!C,children:M?"Saving…":g?"Save to library":"Save"})]})]})]})}function jF(e,t){return Ho.serializeLayoutsForDirtyCheck(e)!==Ho.serializeLayoutsForDirtyCheck(t)}function ght(e,t){return t&&jF(e,t)?t:null}function bht(e){return!!e.expression}function xht(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function yht(e){const t=xht(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function Rhe(e){return e.fieldScope==="domain"&&e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===dt.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===dt.CALCULATED_FIELDS_GROUP_NAME}function vht(e){return Rhe(e)}function wht(e){return e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER||(e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card")&&yht(e.id)&&!e.entityName}function rf(e){return bht(e)?vht(e)?"domain_calculated":wht(e)?"user_calculated":"inline_expression":"none"}function nx(e){return rf(e)!=="none"}function Qa(e){if(!nx(e))return!1;const t=rf(e);return t==="domain_calculated"||t==="user_calculated"?!0:e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card"}function Ahe(e){return Qa(e)&&e.fieldScope!=="card"}function Phe(e,t,n){return nx(e)?t==="editor"?!0:t==="filter"?Qa(e)&&e.fieldScope!=="card":Qa(e)&&(n==null?void 0:n.isValuePickSafe)!==!1:!1}function i2(e,t){return e.map(n=>({...n,fieldScope:t}))}function Fhe(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:o,refetch:s}=Vz(),i=p.useEditorStore(_=>_.frame.calculatedFields),a=p.useEditorStore(_=>_.card.calculatedFields),c=p.useEditorStore(_=>_.card.config),u=p.useDashboardStore(_=>_.dashboard),d=p.useDashboardStore(_=>_.visualEditPendingDashboardCalculatedFields),f=p.useDashboardStore(_=>_.selectedSheetId),h=p.useDashboardStore(_=>_.selectedFrameId),m=p.useDashboardStore(_=>_.isVisualEditing),g=v.useMemo(()=>e.filter(_=>rf(_)==="domain_calculated"),[e]),b=v.useMemo(()=>e.filter(_=>rf(_)!=="domain_calculated"),[e]),x=v.useMemo(()=>{var k;if(m)return i||[];const _=(k=u==null?void 0:u.sheets)==null?void 0:k.find(T=>T.id===f);return p.getSheetCalculatedFields(_)},[u==null?void 0:u.sheets,i,m,h,f]),y=v.useMemo(()=>{const _=d??(u==null?void 0:u.calculatedFields)??[];return _.length?i2(_,"dashboard"):[]},[u==null?void 0:u.calculatedFields,d]),w=v.useMemo(()=>x.length?i2(x,"sheet"):[],[x]),C=v.useMemo(()=>p.buildCalculatedFieldComparableKeySet([...y,...w]),[y,w]),N=v.useMemo(()=>{const _=(a||[]).filter(D=>Qa(D)&&D.fieldScope!=="domain"),k=((c==null?void 0:c.metricColumns)||[]).filter(D=>Qa(D)&&D.fieldScope!=="domain"),T=((c==null?void 0:c.groupByColumns)||[]).filter(D=>Qa(D)&&D.fieldScope!=="domain"),E=p.dedupeCalculatedFields([..._,...k,...T]).filter(D=>!C.has(p.getCalculatedFieldComparableKey(D)));return i2(E,"card").map(D=>({...D,id:`card-source-${D.id}`}))},[a,c==null?void 0:c.groupByColumns,c==null?void 0:c.metricColumns,C]),S=v.useMemo(()=>[...g,...y,...w,...N,...b],[N,b,y,g,w]),j=v.useMemo(()=>t.filter(_=>_.entityId!==dt.CALCULATED_FIELDS_GROUP_ID),[t]);return{columns:e,columnGroups:j,rawColumnGroups:t,columnFields:b,domainCalculatedFields:g,dashboardCalculatedFields:y,sheetCalculatedFields:w,cardCalculatedFields:N,scopedFields:S,isLoading:n,hasError:r,error:o,refetch:s}}function Cht(e){const t="expression"in e&&e.expression||"",n=e.qualifiedEntityName||e.entityName||"",r=e.fieldScope||"unscoped",o=e.qualifiedFieldName||e.name;return t?["calculated",r,e.role||"field",n,o,t].join("::"):["calculated",r,e.role||"field",n,p.normalizeCalculatedFieldId(e.id)||o].join("::")}function Sht(e){return["physical",e.fieldScope||"physical",e.role||"field",e.qualifiedEntityName||"",e.qualifiedFieldName||e.name,e.name].join("::")}function $p(e){const t=new Map;return e.forEach(n=>{const r=nx(n)?Cht(n):Sht(n);t.has(r)||t.set(r,n)}),Array.from(t.values())}function Hz(e){return!xr.isCalculatedMetric(e)}function a2(e,t){return $p(e.filter(n=>Phe(n,t,{isValuePickSafe:Hz(n)})))}function Nht(e){return!nx(e)||Phe(e,"inline-filter",{isValuePickSafe:Hz(e)})}function jht(e){return!nx(e)||Ahe(e)}function Ohe(){const e=Fhe(),t=v.useMemo(()=>$p(e.scopedFields),[e.scopedFields]),n=v.useMemo(()=>$p([...e.columns,...e.dashboardCalculatedFields,...e.sheetCalculatedFields]),[e.columns,e.dashboardCalculatedFields,e.sheetCalculatedFields]),r=v.useMemo(()=>$p(n.filter(jht)),[n]),o=v.useMemo(()=>a2(t,"editor"),[t]),s=v.useMemo(()=>a2(n.filter(Ahe),"filter"),[n]),i=v.useMemo(()=>$p(t.filter(Hz)),[t]),a=v.useMemo(()=>$p(i.filter(Nht)),[i]),c=v.useMemo(()=>a2(a,"inline-filter"),[a]);return{...e,filterableFields:t,sharedFilterableFields:n,dashboardFilterableFields:r,inlineFilterableFields:a,scopedCalculatedFields:o,sharedCalculatedFields:s,inlineCalculatedFields:c,valuePickFilterableFields:i}}const Lhe=te.forwardRef(function({icon:t,label:n,asButton:r,disabled:o,labelWrapper:s,inQuery:i,trailing:a,kebab:c,showKebab:u,onKebabClick:d,selected:f,dragging:h,disableHover:m,className:g,...b},x){const y=l.jsx("span",{className:"block min-w-0 flex-1 truncate text-[13px] text-foreground/90",children:n}),w=p.cn("group/field-row relative flex h-7 items-center gap-2 px-4 transition-colors",h&&"opacity-40",f?"bg-muted":i?"bg-foreground/[0.06] hover:bg-foreground/[0.09]":!m&&"hover:bg-muted/60",r&&"w-full text-left disabled:cursor-not-allowed",g),C=l.jsxs(l.Fragment,{children:[t,s?s(y):y,i&&l.jsx("span",{className:"sr-only",children:"In query"}),a,(c||u)&&l.jsx("button",{type:"button","aria-label":"Field actions",onClick:N=>{N.stopPropagation(),d==null||d(N)},onPointerDown:N=>N.stopPropagation(),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:opacity-100 group-focus-within/field-row:opacity-100 [@media(hover:none)]:opacity-100",children:c??l.jsx(Ci,{className:"h-3 w-3"})})]});return r?l.jsx("button",{ref:x,type:"button",disabled:o,"data-selected":f?"true":void 0,className:w,...b,children:C}):l.jsx("div",{ref:x,"data-selected":f?"true":void 0,className:w,...b,children:C})});function qz(e){const{tokenProps:t,authToken:n}=It(),r=t==null?void 0:t.apiServiceUrl;return Un({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const o=`${r}/v1/domains/${e}/joinability`;return p.getRequest(o,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:o=>Math.min(1e3*2**o,3e4)})}function $he(e,t,n){if(t==="source")return{isValid:!0};const r=p.getDataType(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function zhe(e,t,n,r,o){if(e!=="kpi"||o.length<3)return;const s=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=o.some(a=>{var c;return((c=a.comparison)==null?void 0:c.mode)==="explicit"});!s&&!i||n(r,{groupByColumns:[],metricColumns:o.map(a=>({...a,comparison:void 0}))})}function kht(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const _ht=new Set(["COUNT","DISTINCT"]),Iht=new Set(["running_total","moving_average","previous_period_delta"]);function Tht(e){return p.getDataType(e.dataType||"")==="number"?!0:e.aggregate?_ht.has(e.aggregate.toUpperCase()):!1}function Eht(e,t){var r,o;return!!((o=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:o.function)}function Uz(e,t){var n,r;return e==="aggregateTable"&&((((n=t.rowAggregates)==null?void 0:n.length)??0)>0||(((r=t.columnAggregates)==null?void 0:r.length)??0)>0)}function Bhe({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,c;if(e==="detailTable"||e==="kpi")return{supported:!1,reason:"Metric transforms are not supported for this card type."};if((((i=t.groupByColumns)==null?void 0:i.length)??0)===0)return{supported:!1,reason:"Metric transforms require at least one grouped dimension."};if(!Tht(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const o=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,s=e==="pivotTable"||Uz(e,t);return o&&!s?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:Iht.has(r)&&(((c=t.groupByColumns)==null?void 0:c.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function Dht(e){return e.find(t=>p.getDataType(t.dataType||"")==="date")}function Mht(e){return e}function l0({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(s=>s.id&&s.id!==n).map(s=>s.id),o=[];if(e==="pivotTable"||Uz(e,t))for(const s of t.pivotByColumns||[])s.id&&o.push(s.id);return Array.from(new Set([...r,...o]))}function Rht({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const o=r||((i=Dht(n.groupByColumns||[]))==null?void 0:i.id),s=l0({cardType:t,cardConfig:n,orderByFieldId:o});return e==="moving_average"?{function:"moving_average",...o?{orderBy:{fieldId:o,direction:"asc"}}:{},partitionByFieldIds:s,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...o?{orderBy:{fieldId:o,direction:"asc"}}:{},partitionByFieldIds:s,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...o?{orderBy:{fieldId:o,direction:"asc"}}:{},partitionByFieldIds:s,frame:"unbounded_preceding"}}const Aht=new Set(["table","aggregateTable","pivotTable","detailTable"]);function Pht(e){return e.alias||e.label||e.name}function Vhe(e,t,n){var a,c,u;if(!e)return null;const r=p.fromSemanticFormat(t.format);if(!r)return null;const o=n||{};let s=o,i=!1;if(Aht.has(e.type)){const d=p.toColumnNumberFormat(r),f=Pht(t);if(d&&!((c=(a=o.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:c[f])){const m=To();s={...s,tablePrefs:{...s.tablePrefs||{},columnSettingsMap:{...((u=s.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...m,type:"number",textAlign:"right",numberFormat:{...m.numberFormat,...d}}}}},i=!0}if(!o.formatNumber){const h=p.toLegacyFormatNumber(r);h&&(s={...s,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?s:null}const Hhe=e=>{var X;const t=(X=e==null?void 0:e.dataSource)==null?void 0:X.semanticDomainId,{data:n}=qz(t),{updateCardConfig:r,updateGroupByColumn:o,updateMetricColumn:s,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=p.useEditorActions(),m=p.useEditorStore(Y=>Y.card.type),g=e==null?void 0:e.id,b=(Y,O)=>p.resolveShelfFieldId(Y,O),x=v.useCallback(Y=>{if(!(e!=null&&e.config))return[];switch(Y){case"groupBy":return(e.config.groupByColumns||[]).map(O=>({...O,id:b(O,"groupBy"),label:O.label!==void 0?O.label:O.name}));case"metrics":return(e.config.metricColumns||[]).map(O=>({...O,id:b(O,"metrics"),label:O.label!==void 0?O.label:O.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map(O=>({...O,id:b(O,"pivotBy"),label:O.label!==void 0?O.label:O.name}));case"sortBy":return(e.config.sortByColumns||[]).map(O=>({id:b(O,"sortBy"),name:O.name,dataType:O.dataType,label:O.label!==void 0?O.label:O.name,qualifiedEntityName:O.qualifiedEntityName,entityId:O.entityId,entityName:O.entityName,entityType:O.entityType,direction:O.direction}));case"detailColumns":return kht(e.config.detailColumns,O=>b(O,"detailColumns"));case"source":return[];default:return[]}},[e]),y=v.useCallback((Y,O)=>{if(g)switch(Y){case"groupBy":{r(g,{groupByColumns:O});break}case"metrics":{r(g,{metricColumns:O});break}case"pivotBy":{r(g,{pivotByColumns:O});break}case"sortBy":{r(g,{sortByColumns:O});break}case"detailColumns":{r(g,{detailColumns:O});break}}},[g,r]),w=v.useCallback((Y,O,q)=>{if(!g)return;const U=x(Y),V=U[O];if(V)switch(Y){case"groupBy":o(g,V.id,{label:q});break;case"metrics":s(g,V.id,{label:q});break;case"pivotBy":i(g,V.id,{label:q});break;case"sortBy":a(g,V.id,{label:q});break;case"detailColumns":{const K=U.map((Q,se)=>se===O?{...Q,label:q}:Q);r(g,{detailColumns:K});break}}},[g,x,o,s,i,a,r]),C=v.useCallback((Y,O)=>{if(!g)return;const U=x("metrics")[Y];U&&s(g,U.id,{aggregate:O,label:qre(U.name,O)})},[g,x,s]),N=v.useCallback((Y,O,q)=>{if(!g)return;const U=x("detailColumns");if(!U[Y])return;const K={dateFormat:O,customFormat:O==="custom"&&q?q:void 0},Q=U.map((se,oe)=>oe===Y?{...se,...K}:se);r(g,{detailColumns:Q})},[g,x,r]),S=v.useCallback((Y,O)=>{if(!g)return;const q=x("groupBy")[Y];if(!q)return;const U=p.readTemporalBucketAuthoringState({fieldId:q.id,dataType:q.dataType,granularity:q.granularity,format:q.format,dateFormat:q.dateFormat,customFormat:q.customFormat,semanticTemporalPresentation:q.semanticTemporalPresentation});U.ok&&o(g,q.id,{granularity:U.granularity,format:O,dateFormat:void 0,customFormat:void 0})},[g,x,o]),j=v.useCallback((Y,O)=>{if(!g)return;const U=x("groupBy")[Y];if(!U)return;const V=O,K=p.readTemporalBucketAuthoringSelection({fieldId:U.id,dataType:U.dataType,granularity:V,format:U.format,dateFormat:U.dateFormat,customFormat:U.customFormat,semanticTemporalPresentation:U.semanticTemporalPresentation}).format;o(g,U.id,{granularity:V,format:qc.reconcileTemporalBucketAuthoringFormat(K,V),dateFormat:void 0,customFormat:void 0})},[g,x,o]),_=v.useCallback((Y,O)=>{if(!g)return;const U=x("metrics")[Y];U&&s(g,U.id,{aliasTemplate:O})},[g,x,s]),k=v.useCallback((Y,O)=>{if(!g)return;const U=x("pivotBy")[Y];U&&i(g,U.id,{memberOrder:O})},[g,x,i]),T=v.useCallback((Y,O)=>{if(console.log("handleValueAliasesChange",Y,O),!g)return;console.log("handleValueAliasesChange",Y,O);const U=x("metrics")[Y];U&&(console.log("handleValueAliasesChange",O),s(g,U.id,{valueAliases:O}))},[g,x,s]),I=v.useCallback((Y,O)=>{var V,K;if(!g)return;const U=x("metrics")[Y];U&&(s(g,U.id,{format:O}),m==="kpi"&&((K=(V=e==null?void 0:e.preferences)==null?void 0:V.kpiVisualOptions)!=null&&K.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,g,m,x,h,s]),E=v.useCallback((Y,O)=>{var Q,se;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=O!=="inherit"&&O!=="off"&&((Q=U.parameters)==null?void 0:Q.windowTransform),K=O==="inherit"?void 0:O==="off"?{mode:"off"}:O==="target"?{mode:"explicit",spec:{kind:"target",targetValue:((se=U.comparison)==null?void 0:se.mode)==="explicit"&&U.comparison.spec.kind==="target"?U.comparison.spec.targetValue:0}}:{mode:"explicit",spec:{kind:O}};s(g,U.id,{comparison:K,...V?{parameters:{...U.parameters||{},windowTransform:void 0}}:{}})},[g,x,s]),D=v.useCallback((Y,O)=>{if(!g)return;const q=x("metrics")[Y];q&&s(g,q.id,{comparison:{mode:"explicit",spec:O}})},[g,x,s]),R=v.useCallback((Y,O)=>{if(!g)return;const q=x("metrics")[Y];!q||q.semanticComparisonPolarity||s(g,q.id,{comparisonPolarity:O})},[g,x,s]),A=v.useCallback((Y,O)=>{var me,le,ue;if(!g||!(e!=null&&e.config))return;const U=x("metrics")[Y];if(!U)return;if(O==="none"){s(g,U.id,{parameters:{...U.parameters||{},windowTransform:void 0}});return}const V=Bhe({cardType:m,cardConfig:e.config,metric:U,transformMode:O});if(!V.supported){lt.error(V.reason||"Metric transform is not supported here.");return}const K=new Set((e.config.groupByColumns||[]).map(ne=>ne.id)),Q=(ue=(le=(me=U.parameters)==null?void 0:me.windowTransform)==null?void 0:le.orderBy)==null?void 0:ue.fieldId,se=Q&&K.has(Q)?Q:void 0,oe=Rht({transformMode:O,cardType:m,cardConfig:e.config,fallbackOrderByFieldId:se});s(g,U.id,{comparison:void 0,parameters:{...U.parameters||{},windowTransform:oe}})},[e,g,m,x,s]),F=v.useCallback((Y,O)=>{var oe,me;if(!g||!(e!=null&&e.config))return;const U=x("metrics")[Y];if(!U)return;const V=(oe=U.parameters)==null?void 0:oe.windowTransform;if(!V||!["running_total","moving_average","previous_period_delta"].includes(V.function))return;const K=l0({cardType:m,cardConfig:e.config,orderByFieldId:O}),se=(V.partitionByFieldIds||K).filter(le=>le!==O);s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,orderBy:{fieldId:O,direction:((me=V.orderBy)==null?void 0:me.direction)||"asc"},partitionByFieldIds:se}}})},[e,g,m,x,s]),z=v.useCallback((Y,O)=>{var K;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(K=U.parameters)==null?void 0:K.windowTransform;!V||!["running_total","moving_average","previous_period_delta"].includes(V.function)||s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,orderBy:V.orderBy?{...V.orderBy,direction:O}:V.orderBy}}})},[g,x,s]),L=v.useCallback((Y,O)=>{var se,oe;if(!g||!(e!=null&&e.config))return;const U=x("metrics")[Y];if(!U)return;const V=(se=U.parameters)==null?void 0:se.windowTransform;if(!V)return;const K=l0({cardType:m,cardConfig:e.config,orderByFieldId:(oe=V.orderBy)==null?void 0:oe.fieldId}),Q=new Set(V.partitionByFieldIds||K);Q.has(O)?Q.delete(O):Q.add(O),s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,partitionByFieldIds:Array.from(Q)}}})},[e,g,m,x,s]),$=v.useCallback((Y,O)=>{var oe,me;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(oe=U.parameters)==null?void 0:oe.windowTransform;if(!V||V.function!=="moving_average")return;const K=Math.max(1,Math.floor(O||1)),Q=((me=V.movingAverage)==null?void 0:me.minPeriods)||1,se=Math.min(Q,K);s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,movingAverage:{windowSize:K,minPeriods:se}}}})},[g,x,s]),H=v.useCallback((Y,O)=>{var se,oe;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(se=U.parameters)==null?void 0:se.windowTransform;if(!V||V.function!=="moving_average")return;const K=((oe=V.movingAverage)==null?void 0:oe.windowSize)||7,Q=Math.max(1,Math.min(Math.floor(O||1),K));s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,movingAverage:{windowSize:K,minPeriods:Q}}}})},[g,x,s]),M=v.useCallback((Y,O)=>{var K;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(K=U.parameters)==null?void 0:K.windowTransform;!V||V.function!=="previous_period_delta"||s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,previousPeriodDelta:{mode:O}}}})},[g,x,s]),B=v.useCallback((Y,O)=>{var Q;if(!g||!(e!=null&&e.config))return;const U=x("metrics")[Y];if(!U)return;const V=(Q=U.parameters)==null?void 0:Q.windowTransform;if(!V||V.function!=="percent_of_total")return;const K=O==="grand_total"?[]:(V.partitionByFieldIds||[]).length>0?V.partitionByFieldIds||[]:l0({cardType:m,cardConfig:e.config,orderByFieldId:void 0});s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,partitionByFieldIds:K,percentOfTotal:{...V.percentOfTotal||{},scope:O}}}})},[e,g,m,x,s]),W=v.useCallback((Y,O)=>{var K;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(K=U.parameters)==null?void 0:K.windowTransform;!V||V.function!=="percent_of_total"||s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,percentOfTotal:{...V.percentOfTotal||{},output:O}}}})},[g,x,s]),P=v.useCallback((Y,O)=>{if(!g)return;const U=x("metrics")[Y];U&&s(g,U.id,{comparison:O===void 0?{mode:"explicit",spec:{kind:"target",targetValue:0}}:{mode:"explicit",spec:{kind:"target",targetValue:O}}})},[g,x,s]),G=v.useCallback(async Y=>{var oe;if(!g)return;const O=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy"),...x("detailColumns")],q=Y,U=p3e(q,O,{joinPlan:(oe=e==null?void 0:e.config)==null?void 0:oe.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t,datasetAliases:n==null?void 0:n.datasets});if(!U.isValid){U.showError&&$re();return}const V=j3e(q,O,m);if(!V){lt.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const K=$he(q,V,m);if(!K.isValid){lt.error("Invalid Field Type",{description:K.reason,position:"top-center",duration:3e3});return}const Q=x(V);if(zre(q,Q))return;const se=Ure(q,V,Q);if(se){const me=[...Q,se];if(y(V,me),V==="metrics"){const le=Vhe(e,se,e==null?void 0:e.preferences);le&&h(le),zhe(m,e==null?void 0:e.config,r,g,me)}}},[g,e,x,y,t,n,m,r,h]),Z=v.useCallback((Y,O)=>{if(!g)return;const U=x(Y)[O];if(U){if(Y!=="sortBy"){const V=x("sortBy"),K=V.filter(Q=>!(Q.name===U.name&&Q.qualifiedEntityName===U.qualifiedEntityName));K.length!==V.length&&r(g,{sortByColumns:K})}switch(Y){case"groupBy":c(g,U.id);break;case"metrics":u(g,U.id);break;case"pivotBy":d(g,U.id);break;case"sortBy":f(g,U.id);break;case"detailColumns":{r(g,{detailColumns:(x("detailColumns")||[]).filter((V,K)=>K!==O)});break}}}},[g,x,c,u,d,f,r]);return{getFieldsForContainer:x,setFieldsForContainer:y,updateLabel:w,handleAggregationChange:C,handleDetailDateFormatChange:N,handleTemporalBucketFormatChange:S,handleGranularityChange:j,handleAliasTemplateChange:_,handlePivotMemberOrderChange:k,handleValueAliasesChange:T,handleMetricFormatChange:I,removeField:Z,handleFieldClick:G,handleMetricComparisonChange:E,handleMetricComparisonSpecChange:D,handleMetricComparisonPolarityChange:R,handleMetricWindowTransformChange:A,handleMetricWindowOrderByChange:F,handleMetricWindowDirectionChange:z,handleMetricWindowPartitionToggle:L,handleMetricMovingAverageWindowSizeChange:$,handleMetricMovingAverageMinPeriodsChange:H,handleMetricPreviousPeriodDeltaModeChange:M,handleMetricPercentOfTotalScopeChange:B,handleMetricPercentOfTotalOutputChange:W,handleMetricTargetValueChange:P,cardType:m}};function qhe(e){var y;const{tokenProps:t}=It(),n=p.useDashboardStore(w=>w.authToken)||e,r=p.useEditorStore(w=>w.selectedConnectionId),o=p.useEditorStore(w=>w.selectedDatabaseName),s=p.useEditorStore(w=>w.selectedDatamodelId),i=p.useEditorStore(w=>w.selectedSchemaName),a=p.useEditorStore(w=>w.selectedTableName),{selectedConnection:c}=Au(),u=c==null?void 0:c.type,{data:d,isLoading:f,isFetching:h,isError:m,refetch:g}=Un({queryKey:["columns",r,o,s,i,a],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",{connection_id:r,datamodel_id:s||"",database_name:o,schema_name:i,table_name:a}),enabled:b(u)});function b(w){var _;if(!(n!=null&&n.accessToken))return!1;if(s&&s)return!0;if(!r||!w)return!1;const C=((_=c==null?void 0:c.capabilities)==null?void 0:_.path)||[],N=C.includes("database"),S=C.includes("schema"),j=C.includes("table");return!(N&&(!o||o==="NA")||S&&!i||j&&!a)}return{columns:(y=d==null?void 0:d.columns)==null?void 0:y.map(w=>({...w,data_type:w.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:m,refetchColumns:g}}function Fht(e){const t=p.useDashboardStore(w=>w.dashboard),n=p.useDashboardStore(w=>{var C;return((C=w.reportContext)==null?void 0:C.calendar)??null}),r=p.useDashboardStore(w=>w.selectedLensId),o=p.useFinalFilterGroupKey(e)||"",s=JL(e),{cardFilterValues:i,controlValues:a,queryRelevantConfig:c}=s,u=p.useDashboardStore(w=>w.dashboardInputReferenceTime),d=v.useMemo(()=>p.getDashboardCards(t),[t]),f=v.useMemo(()=>d.length>0?d:[e],[e,d]),h=v.useMemo(()=>Object.fromEntries(f.map(w=>[w.id,w.id===e.id?c:w.config])),[e.id,c,f]),m=u_(f,{authority:"editor",queryRelevantConfigsByCardId:h}).payload,g=p.resolveCardPrimaryDateField({card:e,cardConfig:c,semanticExecutionPayload:m}),b=(e==null?void 0:e.sql)||"",x=p.getGlobalDateFilterCoverage(t,m);return{queryKey:n?E5(e,{...s,finalFiltersKey:o},{selectedLensId:r,resolvedPrimaryDateField:g,calendarContext:n,allowGlobalDateMinutePrecision:x.allEligibleTargetsAreDateTime,globalDateComparisonReferenceTime:u}).queryKey:[],sql:b,cardFilterValues:i,controlValues:a}}function mT(e,t){var Te,ze,Pe,He,ye,Ke,We,Qe;const{tokenProps:n}=It(),r=Wr(),o=It().authToken||e,s=p.useEditorStore(xe=>xe.selectedConnectionId),i=p.useEditorStore(xe=>xe.card),{queryKey:a}=Fht(i),c=p.useEditorStore(xe=>xe.selectedDatamodelId),u=p.useEditorStore(xe=>xe.isDevMode),d=p.useEditorStore(xe=>xe.selectedDatabaseName),f=p.useEditorStore(xe=>xe.selectedSchemaName),h=p.useEditorStore(xe=>xe.selectedTableName),m=p.useEditorStore(xe=>xe.actions.setSelectedConnectionId),g=p.useEditorStore(xe=>xe.actions.setSelectedDatamodelId),b=p.useEditorStore(xe=>xe.actions.setSelectedDatabaseName),x=p.useEditorStore(xe=>xe.actions.setSelectedSchemaName),y=p.useEditorStore(xe=>xe.actions.setSelectedTableName);p.useEditorStore(xe=>xe.actions.setCardSql);const{setQueryConfig:w}=p.useEditorActions();function C(xe){var Ie;if(!s||!xe)return!1;const Ve=((Ie=T==null?void 0:T.capabilities)==null?void 0:Ie.path)||[],Ae=Ve.includes("database"),ke=Ve.includes("schema");return!(!Ve.includes("table")||Ae&&(!d||d==="NA")||ke&&!f)}function N(xe){var Ve;return!s||!xe?!1:!!((Ve=T==null?void 0:T.capabilities)!=null&&Ve.path.includes("database"))}const{refetchConnections:S,connectionsData:j,isConnectionsLoading:_,isConnectionsError:k,selectedConnection:T}=Au(e),{refetch:I,data:E,isLoading:D,isError:R}=Un({queryKey:["models",s],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/datamodels`,(o==null?void 0:o.accessToken)||"",{connection_id:s}),enabled:!!(o!=null&&o.accessToken)&&!!s}),A=T==null?void 0:T.type,F=((Te=T==null?void 0:T.capabilities)==null?void 0:Te.path.includes("schema"))??!1,z=((ze=T==null?void 0:T.capabilities)==null?void 0:ze.path.length)===1&&((Pe=T==null?void 0:T.capabilities)==null?void 0:Pe.path[0])==="table",L=z,{data:$,isLoading:H,isFetching:M,isError:B,refetch:W}=Un({queryKey:["databases",s],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/databases`,(o==null?void 0:o.accessToken)||"",{connection_id:s}),enabled:N(A)}),{data:P,isLoading:G,isFetching:Z,isError:X,refetch:Y}=Un({queryKey:["schemas",s,d],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/schemas`,(o==null?void 0:o.accessToken)||"",{connection_id:s,database_name:d}),enabled:!!s&&!!d&&F&&d!=="NA"}),{data:O,isLoading:q,isFetching:U,isError:V,refetch:K}=Un({queryKey:["tables",s,d,f],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/tables`,(o==null?void 0:o.accessToken)||"",{connection_id:s,database_name:d,schema_name:f}),enabled:C(A)}),{columns:Q,isColumnsLoading:se,isColumnsFetching:oe,isColumnsError:me,refetchColumns:le}=qhe(e);v.useEffect(()=>{z&&(b(""),x(""),g(""),A==="API"&&y("api"))},[A,y,b,x,g,z]);const ue=(T==null?void 0:T.type)==="API"?(He=T==null?void 0:T.type)==null?void 0:He.toLowerCase():h||"",ne=F&&f||"";function de(xe){y(xe),w(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(xe){x(xe),y("")}function ce(xe){b(xe==="none"?"":xe),x(""),y(""),xe!=="none"&&xe!==""&&g("")}function ie(xe){m(xe)}function we(xe){g(xe==="none"?"":xe),xe!=="none"&&xe!==""&&b("")}$&&((ye=$==null?void 0:$.databases)==null?void 0:ye.length)>0,P&&((Ke=P==null?void 0:P.schemas)==null?void 0:Ke.length)>0;const fe=j==null?void 0:j.connections.map(xe=>({id:xe.id,name:xe.name,type:xe.type})),ae=(We=E==null?void 0:E.datamodels)==null?void 0:We.map(xe=>({id:xe.id,name:xe.name})),ee=$==null?void 0:$.databases.map(xe=>({id:xe.database_name,name:xe.database_name})),J=P==null?void 0:P.schemas.map(xe=>({id:xe.schema_name,name:xe.schema_name})),re=O==null?void 0:O.tables.map(xe=>({id:xe.table_name,name:xe.table_name})),pe=(Qe=E==null?void 0:E.datamodels.find(xe=>xe.id===c))==null?void 0:Qe.name,Ee=T!=null&&T.capabilities?p.getFormattedTableNameForQuery({schemaName:ne,tableName:ue,modelName:pe,databaseName:d||"",capabilities:T.capabilities}):ue;return{connectionItems:fe,selectedConnectionId:s,selectedConnection:T,isConnectionsLoading:_,isConnectionsError:k,modelItems:ae,selectedDatamodelId:c,selectedDatamodelName:pe,isModelsLoading:D,isModelsError:R,selectedDatabaseName:d,databaseItems:ee,isDatabasesLoadingOrFetching:H||M,isDatabaseError:B,schemaItems:J,selectedSchemaName:f,isSchemaLoadingOrFetching:G||Z,isSchemaError:X,tableItems:re,selectedTableName:h,isTableLoadingOrFetching:q||U,isTableError:V,columns:Q,isColumnsLoadingOrFetching:se||oe,isColumnsError:me,isNonDbConnection:L,connectionType:A,tableName:ue,formattedTableName:Ee,schemaName:ne,refetchConnections:S,refetchModels:I,refetchDatabases:W,refetchSchemas:Y,refetchTables:K,refetchColumns:le,handleConnectionChange:ie,handleDatamodelChange:we,handleDatabaseChange:ce,handleSchemaChange:Ce,handleTableChange:de}}function ZS(e){return`${e}-${dt.v4()}`}function eK(e,t){const n=p.toTitleCase(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Oht(e,t){const n=p.toTitleCase(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function Wz(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 Uhe(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Whe(){const e=p.useEditorStore(_=>_.sqlGen),t=p.useEditorStore(_=>_.isDevMode),n=p.useEditorStore(_=>_.card.dataSource),r=p.useEditorStore(_=>{var k,T;return(T=(k=_.card)==null?void 0:k.queryConfig)==null?void 0:T.metricColumns}),{tableName:o,schemaName:s,databaseName:i}=Wz(n),a=Uhe(n),c=p.useEditorStore(_=>_.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:g}=p.useEditorActions(),{modelItems:b,selectedDatamodelName:x}=mT(),{selectedConnection:y}=Au(),w=y==null?void 0:y.capabilities,C=_=>({column_name:_.name,data_type:_.dataType,label:_.label,description:_.description});return{handleDevModeFieldClick:_=>{var T;if(!t)return;const k=C(_);if(t&&a&&o&&w){const I=p.createSqlGenConfig(k,e);m(I);const E=(T=b==null?void 0:b.find(R=>R.id===c))==null?void 0:T.name,D=p.getSql(I,s||"",o,E||"",i||"",w,_.qualifiedEntityName);D&&(f(D),h(!0))}else if(!t){if(p.isTextDataType(k.data_type))if(r&&r.length>0){const I={...k,role:"groupby",id:ZS(k.column_name),name:k.column_name,type:k.data_type};d(I)}else{const I={...k,role:"metric",id:ZS(k.column_name),name:k.column_name,label:eK(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};u(I)}if(p.isDateDataType(k.data_type)){const I={...k,role:"groupby",id:ZS(k.column_name),name:k.column_name,type:k.data_type,label:Oht(k.column_name,"month"),granularity:"month"};d(I)}if(p.isNumberDataType(k.data_type)){const I={...k,role:"metric",id:ZS(k.column_name),name:k.column_name,label:eK(k.column_name,"SUM"),type:k.data_type,aggregate:"SUM"};u(I)}}},handleShowSample:()=>{if(!a||!o||!w){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=p.getFormattedTableNameForQuery({schemaName:s||"",tableName:o,modelName:x,databaseName:i||"",capabilities:w});g(!1);const T=(y==null?void 0:y.type)==="MSSQL"?`SELECT top 10 * FROM ${_}`:`SELECT * FROM ${_} LIMIT 10`;f(T),h(!0)},handleShowCount:()=>{if(!a||!o||!w){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=p.getFormattedTableNameForQuery({schemaName:s||"",tableName:o,modelName:x,databaseName:i||"",capabilities:w});f(`SELECT COUNT(*) as count FROM ${_}`),h(!0)},isNumberField:_=>p.isNumberDataType(_.dataType)}}function Khe(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(s=>p.fmt(s)).join("."),o=p.fmt(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:o}}function Kz(e){const t=e;return{id:e.id,name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,fieldScope:e.fieldScope,expression:t.expression,calculatedFormula:t.calculatedFormula}}function Gz(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function tK(e){var t,n;return e?!!(e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function nK(e){return e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e}function rb(e,t){var b,x,y,w,C,N,S;if(!e.fieldMeta)return e.column===t.qualifiedFieldName||e.column===t.name;const n=nK((b=e.fieldMeta)==null?void 0:b.id),r=nK(t.id),o=((x=e.fieldMeta)==null?void 0:x.qualifiedFieldName)||e.column,s=o===t.qualifiedFieldName||o===t.name,i=(y=e.fieldMeta)==null?void 0:y.qualifiedEntityName,a=!i||!t.qualifiedEntityName||i===t.qualifiedEntityName,c=(w=e.fieldMeta)==null?void 0:w.entityId,u=!c||!t.entityId||c===t.entityId,d=(C=e.fieldMeta)==null?void 0:C.fieldScope;if(d&&t.fieldScope&&d!==t.fieldScope)return!1;const f=(N=e.fieldMeta)==null?void 0:N.role;if(f&&t.role&&f!==t.role)return!1;const h=tK(e.fieldMeta)||tK(t);if(h&&n&&r&&n===r)return!0;if(!h&&(!a||!u))return!1;const m=(S=e.fieldMeta)==null?void 0:S.expression,g=t.expression;return m||g?s&&a&&u&&m===g:s&&a&&u}function Lht(){const e=p.useDashboardStore(c=>c.dashboard.filters)||[],t=p.useDashboardStore(c=>c.selectedSheetId),n=p.useDashboardStore(c=>c.actions.addFilter),r=p.useDashboardStore(c=>c.actions.removeFilter),{removeFilterValues:o}=p.useDashboardActions(),s=p.useEditorStore(c=>c.card.dataSource),{selectedConnection:i}=Au();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f}=Khe(c);let h;if(u==="sheet"&&t){const m=pf(e,t);h=m.find(g=>g.fieldMeta&&rb(g,c))||zTe(m.filter(g=>!g.fieldMeta),d,f,t)}else h=e==null?void 0:e.find(m=>rb(m,c)||!m.fieldMeta&&Lg(m.column)===Lg(d));if(h)o(h.id),r(h.id);else{const m=dt.v4(),g=Kz(c),b=Gz(s,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),x=u==="sheet"&&t?[t]:void 0,y=p.getDataType(c.dataType)==="date"?"between":"in";return n({id:m,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:y,applyToSheetIds:x,sql:"",fieldMeta:g,semanticContext:b}),m}}return{assignFilter:a}}function $ht({column:e}){const[t,n]=v.useState(!1),r=p.useEditorStore(C=>C.isDevMode),o=p.useEditorStore(C=>C.card.dataSource),{tableName:s,schemaName:i,databaseName:a}=Wz(o),c=p.useEditorStore(C=>C.selectedDatamodelId),u=p.useEditorStore(C=>C.sqlGen),{modelItems:d,selectedConnection:f}=mT(),h=f==null?void 0:f.capabilities,m=p.useEditorStore(C=>C.actions.setSqlGen),g=p.useEditorStore(C=>C.actions.setCardSql),b=p.useEditorStore(C=>C.actions.setRunSql),x=Uhe(o);function y(C,N){var T,I;if(!x||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=p.createSqlGenConfig(C,u,N),j=(T=d==null?void 0:d.find(E=>E.id===c))==null?void 0:T.name;if(m(S),!h){console.warn("Cannot generate SQL: missing connection capabilities");return}const _=(I=C.qualifiedFieldName)==null?void 0:I.split(".").slice(0,-1).join("."),k=p.getSql(S,i||"",s,j||"",a||"",h,_);k&&(g(k),b(!0)),n(!1)}function w(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>y(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>y(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>y(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>y(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>y(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return!r||!x?null:l.jsxs(Xm,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Yd,{asChild:!0,children:l.jsx(Rm,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(bu,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:w()})]})}const rK="bg-emerald-500/90 text-white",zht="bg-blue-500/90 text-white";function Yz(e){const t=rf(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:rK}:{label:"fx",badgeClassName:e.role==="metric"?rK:zht}}function Bht(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),"prefix"in e&&e.prefix&&t.push({label:"Prefix",value:e.prefix}),"suffix"in e&&e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="temporal_bucket")return t.push({label:"Presentation",value:e.presentation.mode}),t;if(e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const o=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:o})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function Vht(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,o)=>{const s=t[Number(o)];return s?`{${s.name||s.label}}`:r}):e.expression}function Hht({field:e,fieldState:t}){var s;const n=Vht(e),r=Bht(((s=e.semanticTemporalPresentation)==null?void 0:s.format)??e.format),o=!!Yz(e);return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-start gap-1.5 px-3 pt-2.5",children:[l.jsx("span",{className:"flex h-[18px] shrink-0 items-center",children:l.jsx(Yw,{dataType:e.dataType,calculated:o})}),l.jsx("p",{className:"min-w-0 flex-1 break-words text-[13px] font-semibold leading-[18px] text-foreground",children:e.label||e.name})]}),l.jsx("div",{className:"px-3 pb-2 pt-0.5",children:l.jsx("code",{className:"font-mono text-[11px] text-muted-foreground",children:e.dataType})}),e.description&&l.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[12px] leading-[1.55] text-muted-foreground",children:e.description}),n&&l.jsxs("div",{className:"border-t border-border/60 bg-muted/40 px-3 py-2",children:[l.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Expression"}),l.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-[11px] leading-[1.55] text-foreground/90",children:n})]}),r.length>0&&l.jsxs("div",{className:"border-t border-border/60 px-3 py-2",children:[l.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Format"}),l.jsx("dl",{className:"grid grid-cols-[64px_1fr] gap-x-3 gap-y-1 text-[11px]",children:r.map(i=>l.jsxs("div",{className:"contents",children:[l.jsx("dt",{className:"font-medium uppercase tracking-[0.08em] text-muted-foreground",children:i.label}),l.jsx("dd",{className:"truncate font-mono tabular-nums text-foreground/90",children:i.value})]},`${i.label}-${i.value}`))})]}),t&&t.tooltip&&l.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[11px] text-muted-foreground",children:t.tooltip}),l.jsx("div",{className:"border-t border-border/60 px-3 py-2",children:l.jsx("code",{className:"block break-all font-mono text-[11px] leading-[1.45] text-muted-foreground",children:e.name})})]})}function oK({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:o,actions:s,onHover:i}){const a=p.useEditorStore(U=>U.isDevMode),c=t==="inline-filter"||t==="document-filter",u=t==="filter"||c,d=a||u||(n==null?void 0:n.state)==="unreachable"&&!u,f=p.useDashboardStore(U=>U.dashboard.filters),h=p.useDashboardStore(U=>U.selectedSheetId),m=p.useDashboardStore(U=>U.actions.removeFilter),{removeFilterValues:g}=p.useDashboardActions(),{assignFilter:b}=Lht(),x=t==="filter"?pf(f,h):f,y=t==="filter"?x==null?void 0:x.find(U=>{if(rb(U,e))return!0;if(U.fieldMeta)return!1;const V=Lg(U.column||""),K=Lg(e.name);return V.endsWith(`.${K}`)||V===K}):void 0,w=!!y,C=c&&(o==null?void 0:o.some(U=>rb(U,e))),N=w||C,S=y&&u?f==null?void 0:f.find(U=>U.id===y.id):void 0,j=S&&(S.applyToSheetIds&&S.applyToSheetIds.length>1||S.excludeSheetIds&&S.excludeSheetIds.length>0||!S.applyToSheetIds&&!S.excludeSheetIds&&!S.sheetId),[_,k]=v.useState(!1),[,T]=v.useState(null),{attributes:I,listeners:E,setNodeRef:D,transform:R,transition:A,isDragging:F}=tx({id:e.id,disabled:d}),z=p.useEditorStore(U=>U.card),{handleFieldClick:L}=Hhe(z),{handleDevModeFieldClick:$,isNumberField:H}=Whe(),M=()=>{S&&(console.log("[SourceField] Removing multi-sheet filter:",S.id),g(S.id),m(S.id)),T(null),k(!1)},B=()=>{if(c&&r){r(e);return}t==="filter"?N&&j?(T(e),k(!0)):b(e,"sheet"):a?$(e):L(e)},W={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},P={transform:Ki.Transform.toString(R),transition:A};function G(U){return U==="domain"?{label:"Semantic domain",Icon:Dve}:U==="sheet"?{label:"Sheet",Icon:em}:U==="dashboard"?{label:"Dashboard",Icon:em}:{label:"Card",Icon:MO}}const Z=Yz(e),X=e.fieldScope,Y=X&&!Z?G(X):null,O=(n==null?void 0:n.state)==="unreachable",q=(n==null?void 0:n.state)==="indirect";return l.jsxs(l.Fragment,{children:[l.jsx(Lhe,{ref:D,style:P,...d?{}:I,...d?{}:E,onClick:B,onMouseEnter:U=>i==null?void 0:i(!0,U.currentTarget),onMouseLeave:()=>i==null?void 0:i(!1),title:n==null?void 0:n.tooltip,selected:w,dragging:F,disableHover:O,inQuery:!u&&!!(n!=null&&n.isSelected),icon:l.jsx(Yw,{dataType:e.dataType,calculated:!!Z}),label:e.label||e.name,trailing:l.jsxs(l.Fragment,{children:[a&&!u&&H(e)&&l.jsx("span",{onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),children:l.jsx($ht,{column:W})}),s?l.jsx("span",{className:"pointer-events-none inline-flex items-center opacity-0 transition-opacity group-hover/field-row:pointer-events-auto group-hover/field-row:opacity-100 group-focus-within/field-row:pointer-events-auto group-focus-within/field-row:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),children:s}):t==="editor"?l.jsxs(Uo,{children:[l.jsx(Wo,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Field actions",onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),className:"pointer-events-none inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:pointer-events-auto group-hover/field-row:opacity-100 group-focus-within/field-row:pointer-events-auto group-focus-within/field-row:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",children:l.jsx(Ci,{className:"h-3 w-3"})})}),l.jsx(Do,{align:"end",className:"w-44",children:l.jsx(kn,{onClick:U=>{U.stopPropagation(),navigator.clipboard.writeText(e.name).then(()=>{lt.success(`Copied "${e.name}"`)}).catch(()=>{lt.error("Could not copy field name")})},children:"Copy field name"})})]}):null,t==="editor"&&Y&&l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx("span",{"aria-label":`${Y.label} calculated field`,className:"inline-flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),children:l.jsx(Y.Icon,{className:"h-3 w-3"})})}),l.jsxs(p.TooltipContent,{side:"top",align:"end",children:[Y.label," calculated field"]})]})]}),className:p.cn((a||u)&&"cursor-pointer",!d&&!a&&!u&&"cursor-grab active:cursor-grabbing",O&&"cursor-not-allowed opacity-50",q&&"text-muted-foreground/80",C&&"bg-primary/10 hover:bg-primary/15")}),l.jsx(ff,{open:_,onOpenChange:k,children:l.jsxs(ku,{children:[l.jsxs(_u,{children:[l.jsx(Tu,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Eu,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Iu,{children:[l.jsx(Mu,{children:"Cancel"}),l.jsx(Du,{onClick:M,children:"Remove Filter"})]})]})})]})}var bl="Accordion",qht=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[Zz,Uht,Wht]=p.createCollection(bl),[pT]=p.createContextScope(bl,[Wht,fue]),Xz=fue(),Ghe=v.forwardRef((e,t)=>{const{type:n,...r}=e,o=r,s=r;return l.jsx(Zz.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?l.jsx(Zht,{...s,ref:t}):l.jsx(Yht,{...o,ref:t})})});Ghe.displayName=bl;var[Yhe,Kht]=pT(bl),[Zhe,Ght]=pT(bl,{collapsible:!1}),Yht=v.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:o=()=>{},collapsible:s=!1,...i}=e,[a,c]=p.useControllableState({prop:n,defaultProp:r??"",onChange:o,caller:bl});return l.jsx(Yhe,{scope:e.__scopeAccordion,value:v.useMemo(()=>a?[a]:[],[a]),onItemOpen:c,onItemClose:v.useCallback(()=>s&&c(""),[s,c]),children:l.jsx(Zhe,{scope:e.__scopeAccordion,collapsible:s,children:l.jsx(Xhe,{...i,ref:t})})})}),Zht=v.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:o=()=>{},...s}=e,[i,a]=p.useControllableState({prop:n,defaultProp:r??[],onChange:o,caller:bl}),c=v.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=v.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return l.jsx(Yhe,{scope:e.__scopeAccordion,value:i,onItemOpen:c,onItemClose:u,children:l.jsx(Zhe,{scope:e.__scopeAccordion,collapsible:!0,children:l.jsx(Xhe,{...s,ref:t})})})}),[Xht,gT]=pT(bl),Xhe=v.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:o,orientation:s="vertical",...i}=e,a=v.useRef(null),c=p.useComposedRefs(a,t),u=Uht(n),f=p.useDirection(o)==="ltr",h=p.composeEventHandlers(e.onKeyDown,m=>{var k;if(!qht.includes(m.key))return;const g=m.target,b=u().filter(T=>{var I;return!((I=T.ref.current)!=null&&I.disabled)}),x=b.findIndex(T=>T.ref.current===g),y=b.length;if(x===-1)return;m.preventDefault();let w=x;const C=0,N=y-1,S=()=>{w=x+1,w>N&&(w=C)},j=()=>{w=x-1,w<C&&(w=N)};switch(m.key){case"Home":w=C;break;case"End":w=N;break;case"ArrowRight":s==="horizontal"&&(f?S():j());break;case"ArrowDown":s==="vertical"&&S();break;case"ArrowLeft":s==="horizontal"&&(f?j():S());break;case"ArrowUp":s==="vertical"&&j();break}const _=w%y;(k=b[_].ref.current)==null||k.focus()});return l.jsx(Xht,{scope:n,disabled:r,direction:o,orientation:s,children:l.jsx(Zz.Slot,{scope:n,children:l.jsx(p.Primitive.div,{...i,"data-orientation":s,ref:c,onKeyDown:r?void 0:h})})})}),lk="AccordionItem",[Qht,Qz]=pT(lk),Qhe=v.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...o}=e,s=gT(lk,n),i=Kht(lk,n),a=Xz(n),c=p.useId(),u=r&&i.value.includes(r)||!1,d=s.disabled||e.disabled;return l.jsx(Qht,{scope:n,open:u,disabled:d,triggerId:c,children:l.jsx(pue,{"data-orientation":s.orientation,"data-state":ome(u),...a,...o,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Qhe.displayName=lk;var Jhe="AccordionHeader",eme=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,o=gT(bl,n),s=Qz(Jhe,n);return l.jsx(p.Primitive.h3,{"data-orientation":o.orientation,"data-state":ome(s.open),"data-disabled":s.disabled?"":void 0,...r,ref:t})});eme.displayName=Jhe;var kF="AccordionTrigger",tme=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,o=gT(bl,n),s=Qz(kF,n),i=Ght(kF,n),a=Xz(n);return l.jsx(Zz.ItemSlot,{scope:n,children:l.jsx(vJe,{"aria-disabled":s.open&&!i.collapsible||void 0,"data-orientation":o.orientation,id:s.triggerId,...a,...r,ref:t})})});tme.displayName=kF;var nme="AccordionContent",rme=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,o=gT(bl,n),s=Qz(nme,n),i=Xz(n);return l.jsx(wJe,{role:"region","aria-labelledby":s.triggerId,"data-orientation":o.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}})});rme.displayName=nme;function ome(e){return e?"open":"closed"}var Jht=Ghe,emt=Qhe,tmt=eme,sme=tme,ime=rme;const Jz=Jht,fv=te.forwardRef(({className:e,...t},n)=>l.jsx(emt,{ref:n,className:p.cn("border-b",e),...t}));fv.displayName="AccordionItem";const hv=te.forwardRef(({className:e,children:t,...n},r)=>l.jsx(tmt,{className:"flex",children:l.jsxs(sme,{ref:r,className:p.cn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,l.jsx(je.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));hv.displayName=sme.displayName;const mv=te.forwardRef(({className:e,children:t,...n},r)=>l.jsx(ime,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:l.jsx("div",{className:p.cn("pb-4 pt-0",e),children:t})}));mv.displayName=ime.displayName;let ame=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const bT=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",insertTemplate:()=>"({a} + {b})",insertHint:"A + B",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",insertTemplate:()=>"({a} - {b})",insertHint:"A − B",requiresTwoInputs:!0},{id:"product",label:"Product",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",insertTemplate:()=>"({a} * {b})",insertHint:"A × B",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",insertTemplate:()=>"({a} / NULLIF({b}, 0))",insertHint:"A ÷ B (null-safe)",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",insertTemplate:()=>"(({b} - {a}) / NULLIF({a}, 0))",insertHint:"% change A → B",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",insertTemplate:()=>"(({a} / NULLIF({b}, 0)) * 100)",insertHint:"(A ÷ B) × 100",requiresTwoInputs:!0},{id:"scale",label:"Scale",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",insertTemplate:()=>"({a} * 1.0)",insertHint:"A × constant",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],nmt=bT.filter(e=>e.id!=="custom"&&!!e.insertTemplate),e4=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),ck=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function lme(e,t){e.forEach(n=>{var i;const r=n.id||n.qualifiedFieldName||n.name;if(r&&t.visited.has(r))return;if(r&&t.visited.add(r),Rhe(n)){t.disqualified=!0;return}const o=(i=n.calculatedFormula)==null?void 0:i.inputFields;if(o!=null&&o.length){lme(o,t);return}if(n.expression&&!(rf(n)==="inline_expression"&&Qa(n)&&n.fieldScope==="domain")){t.disqualified=!0;return}if(!n.entityName||!n.entityId){t.disqualified=!0;return}const s=n.qualifiedEntityName||n.entityId||n.entityName;t.entities.has(s)||t.entities.set(s,{entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName})})}function t4(e){const t={entities:new Map,disqualified:!1,visited:new Set};if(lme(e,t),t.disqualified||t.entities.size!==1)return{kind:"multi-entity"};const[n]=Array.from(t.entities.values());return!(n!=null&&n.entityName)||!n.entityId?{kind:"multi-entity"}:{kind:"inline",entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName}}const sK="calculated_fields";function rmt(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function omt(e){return e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===sK||e.qualifiedEntityName===sK||rmt(e.id)}function smt(e){return e.aggregate?e.aggregate:YL(e.dataType)}function imt(e,t){const n=smt(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function amt(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const o=Number(r),s=t[o];return!s||omt(s)||typeof s.expression=="string"&&Bre(s.expression)?n:imt(n,s)})}function lmt(e,t,n,r,o,s,i,a,c,u){if(!bT.find(w=>w.id===t))throw new Error(`Unknown operation: ${t}`);let f,h=[],m;{if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}const g={operation:t,inputFields:h,...m!==void 0},b=e4(e),x=t4(h);return{id:i||`calc_${ame(10)}`,name:b,label:e,alias:b,qualifiedFieldName:b,dataType:"number",role:"metric",expression:f,calculatedFormula:g,entityId:x.kind==="inline"?x.entityId:s,entityName:x.kind==="inline"?x.entityName:xr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:x.kind==="inline"?x.qualifiedEntityName:void 0,entityType:x.kind==="inline"?"dataset":"table",description:`Calculated field: ${e}`}}function cmt(e){var r,o;const t=bT.find(s=>s.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const s=((r=e.inputFields[0])==null?void 0:r.label)||((o=e.inputFields[0])==null?void 0:o.name)||"A",i=e.constant??1;return`${s} × ${i}`}return e.inputFields.map(s=>s.label||s.name).join(` ${t.symbol} `)}function umt(e,t,n,r,o,s){const i=e4(e),a=t4(n);return Vre({id:s||`calc_dim_${ame(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(c=>c.role==="metric"?{...c,role:"metric"}:{...c,role:"groupby"})},entityId:a.kind==="inline"?a.entityId:o,entityName:a.kind==="inline"?a.entityName:xr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:a.kind==="inline"?a.qualifiedEntityName:void 0,entityType:a.kind==="inline"?"dataset":"table",description:`Calculated field: ${e.trim()}`})}function cme(e){return e==="metric"?"Calculated Metric":"Calculated Column"}function dmt(e){return e==="inline"?"Single dataset":"Cross-entity"}function yy(e){switch(e){case"card":return"This card";case"sheet":return"This sheet";case"dashboard":return"This dashboard";case"domain":return"Semantic domain"}}function iK(e){return e.replace(/\s+/g,"")}function fmt(e){var o;const t=e.calculatedFormula;if(!t||t.operation==="custom")return;const n=bT.find(s=>s.id===t.operation),r=(o=n==null?void 0:n.template)==null?void 0:o.call(n);if(r)return t.operation!=="scale"?r:r.replace("{constant}",String(t.constant??1))}function hmt(e){var r;const t=e.expression||"",n=fmt(e);return!n||iK(t)!==iK(n)?t:amt(t,((r=e.calculatedFormula)==null?void 0:r.inputFields)||[])}function mmt(e){const t=new Set,n=/\{field_(\d+)\}/g;let r=n.exec(e);for(;r;)t.add(Number(r[1])),r=n.exec(e);return[...t].sort((o,s)=>o-s)}function pmt(e){var s;const t=e.expression||"",n=mmt(t);if(n.length===0)return{readOnly:!1};const r=((s=e.calculatedFormula)==null?void 0:s.inputFields)||[];return n[n.length-1]<r.length?{readOnly:!1}:{readOnly:!0,reason:"This legacy metric uses saved field tokens but is missing the input metadata needed to reopen it safely. It can be viewed, but editing is disabled to avoid changing query semantics."}}function gmt(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function bmt(e){var r;const t=new Map;return(((r=e==null?void 0:e.calculatedFormula)==null?void 0:r.inputFields)||[]).forEach(o=>{const s=ck(o.id);s&&t.set(s,o),o.qualifiedFieldName&&t.set(o.qualifiedFieldName,o),o.name&&t.set(o.name,o)}),t}function xmt(e,t){const n=ck(e.id);return n&&t.get(n)||e.qualifiedFieldName&&t.get(e.qualifiedFieldName)||t.get(e.name)}function ymt(e){const t=YL(e.dataType);if(e.role==="metric"){const n=e;return n.aggregate||n.expression||n.calculatedFormula?n:{...n,aggregate:t}}return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}}function vmt(e,t){const n=bmt(t);return e.map(r=>{const o=xmt(r,n);return(o==null?void 0:o.role)==="metric"?o:ymt(r)})}function wmt({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:o,targetQualifiedEntityName:s}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=rf(i);if(r==="inline"){const c=p.getCalculatedFieldNamespace(i),u=s||o;return a==="inline_expression"&&!!u&&c===u}return a==="domain_calculated"})}function Cmt({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const o=r.length>0?r:["dimension","metric"],s=["dimension","metric"].filter(c=>o.includes(c)),i=n||s.length<=1,a=s.includes(e)?e:s[0];return l.jsx(p.Tabs,{value:a,onValueChange:c=>t(c),className:"w-fit shrink-0",children:l.jsx(p.TabsList,{size:"xs",children:s.map(c=>l.jsx(p.TabsTrigger,{value:c,disabled:i,children:cme(c)},c))})})}const n4=te.forwardRef(({className:e,sideOffset:t=8,...n},r)=>l.jsx(p.Portal$2,{children:l.jsx(Kb,{children:l.jsx(p.Content2$1,{ref:r,sideOffset:t,className:p.cn("z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})})}));n4.displayName="ValidationTooltipContent";const ume=p.Arrow2$1;function l2(e,t){return`${e} ${t}${e===1?"":"s"}`}function Smt({result:e}){const t=e.errors.length>0,n=l2(e.tokens.length,"token"),r=e.errors.length>0?l2(e.errors.length,"error"):null,o=e.warnings.length>0?l2(e.warnings.length,"warning"):null,s=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
|
|
1293
|
+
`},Dut={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function Mut(e){let{announcements:t=Dut,container:n,hiddenTextDescribedById:r,screenReaderInstructions:o=Eut}=e;const{announce:s,announcement:i}=_ut(),a=Qw("DndLiveRegion"),[c,u]=v.useState(!1);if(v.useEffect(()=>{u(!0)},[]),Iut(v.useMemo(()=>({onDragStart(f){let{active:h}=f;s(t.onDragStart({active:h}))},onDragMove(f){let{active:h,over:m}=f;t.onDragMove&&s(t.onDragMove({active:h,over:m}))},onDragOver(f){let{active:h,over:m}=f;s(t.onDragOver({active:h,over:m}))},onDragEnd(f){let{active:h,over:m}=f;s(t.onDragEnd({active:h,over:m}))},onDragCancel(f){let{active:h,over:m}=f;s(t.onDragCancel({active:h,over:m}))}}),[s,t])),!c)return null;const d=v.createElement(v.Fragment,null,v.createElement(jut,{id:r,value:o.draggable}),v.createElement(kut,{id:a,announcement:i}));return n?br.createPortal(d,n):d}var ko;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(ko||(ko={}));function ok(){}function nb(e,t){return v.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function oT(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return v.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const al=Object.freeze({x:0,y:0});function Xfe(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function Rut(e,t){const n=rk(e);if(!n)return"0 0";const r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+"% "+r.y+"%"}function Qfe(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function Aut(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function FW(e){let{left:t,top:n,height:r,width:o}=e;return[{x:t,y:n},{x:t+o,y:n},{x:t,y:n+r},{x:t+o,y:n+r}]}function Jfe(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function OW(e,t,n){return t===void 0&&(t=e.left),n===void 0&&(n=e.top),{x:t+e.width*.5,y:n+e.height*.5}}const Jw=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const o=OW(t,t.left,t.top),s=[];for(const i of r){const{id:a}=i,c=n.get(a);if(c){const u=Xfe(OW(c),o);s.push({id:a,data:{droppableContainer:i,value:u}})}}return s.sort(Qfe)},Put=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const o=FW(t),s=[];for(const i of r){const{id:a}=i,c=n.get(a);if(c){const u=FW(c),d=o.reduce((h,m,g)=>h+Xfe(u[g],m),0),f=Number((d/4).toFixed(4));s.push({id:a,data:{droppableContainer:i,value:f}})}}return s.sort(Qfe)};function Fut(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),o=Math.min(t.left+t.width,e.left+e.width),s=Math.min(t.top+t.height,e.top+e.height),i=o-r,a=s-n;if(r<o&&n<s){const c=t.width*t.height,u=e.width*e.height,d=i*a,f=d/(c+u-d);return Number(f.toFixed(4))}return 0}const Out=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const o=[];for(const s of r){const{id:i}=s,a=n.get(i);if(a){const c=Fut(a,t);c>0&&o.push({id:i,data:{droppableContainer:s,value:c}})}}return o.sort(Aut)};function Lut(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function ehe(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:al}function $ut(e){return function(n){for(var r=arguments.length,o=new Array(r>1?r-1:0),s=1;s<r;s++)o[s-1]=arguments[s];return o.reduce((i,a)=>({...i,top:i.top+e*a.y,bottom:i.bottom+e*a.y,left:i.left+e*a.x,right:i.right+e*a.x}),{...n})}}const zut=$ut(1);function the(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function But(e,t,n){const r=the(t);if(!r)return e;const{scaleX:o,scaleY:s,x:i,y:a}=r,c=e.left-i-(1-o)*parseFloat(n),u=e.top-a-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),d=o?e.width/o:e.width,f=s?e.height/s:e.height;return{width:d,height:f,top:u,right:c+d,bottom:u+f,left:c}}const Vut={ignoreTransform:!1};function Qb(e,t){t===void 0&&(t=Vut);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:d}=ni(e).getComputedStyle(e);u&&(n=But(n,u,d))}const{top:r,left:o,width:s,height:i,bottom:a,right:c}=n;return{top:r,left:o,width:s,height:i,bottom:a,right:c}}function LW(e){return Qb(e,{ignoreTransform:!0})}function Hut(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function qut(e,t){return t===void 0&&(t=ni(e).getComputedStyle(e)),t.position==="fixed"}function Uut(e,t){t===void 0&&(t=ni(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{const s=t[o];return typeof s=="string"?n.test(s):!1})}function sT(e,t){const n=[];function r(o){if(t!=null&&n.length>=t||!o)return n;if(Rz(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!Zw(o)||Gfe(o)||n.includes(o))return n;const s=ni(e).getComputedStyle(o);return o!==e&&Uut(o,s)&&n.push(o),qut(o,s)?n:r(o.parentNode)}return e?r(e):n}function nhe(e){const[t]=sT(e,1);return t??null}function ZM(e){return!tT||!e?null:Zb(e)?e:Mz(e)?Rz(e)||e===Xb(e).scrollingElement?window:Zw(e)?e:null:null}function rhe(e){return Zb(e)?e.scrollX:e.scrollLeft}function ohe(e){return Zb(e)?e.scrollY:e.scrollTop}function vF(e){return{x:rhe(e),y:ohe(e)}}var Fo;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(Fo||(Fo={}));function she(e){return!tT||!e?!1:e===document.scrollingElement}function ihe(e){const t={x:0,y:0},n=she(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},o=e.scrollTop<=t.y,s=e.scrollLeft<=t.x,i=e.scrollTop>=r.y,a=e.scrollLeft>=r.x;return{isTop:o,isLeft:s,isBottom:i,isRight:a,maxScroll:r,minScroll:t}}const Wut={x:.2,y:.2};function Kut(e,t,n,r,o){let{top:s,left:i,right:a,bottom:c}=n;r===void 0&&(r=10),o===void 0&&(o=Wut);const{isTop:u,isBottom:d,isLeft:f,isRight:h}=ihe(e),m={x:0,y:0},g={x:0,y:0},b={height:t.height*o.y,width:t.width*o.x};return!u&&s<=t.top+b.height?(m.y=Fo.Backward,g.y=r*Math.abs((t.top+b.height-s)/b.height)):!d&&c>=t.bottom-b.height&&(m.y=Fo.Forward,g.y=r*Math.abs((t.bottom-b.height-c)/b.height)),!h&&a>=t.right-b.width?(m.x=Fo.Forward,g.x=r*Math.abs((t.right-b.width-a)/b.width)):!f&&i<=t.left+b.width&&(m.x=Fo.Backward,g.x=r*Math.abs((t.left+b.width-i)/b.width)),{direction:m,speed:g}}function Gut(e){if(e===document.scrollingElement){const{innerWidth:s,innerHeight:i}=window;return{top:0,left:0,right:s,bottom:i,width:s,height:i}}const{top:t,left:n,right:r,bottom:o}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:o,width:e.clientWidth,height:e.clientHeight}}function ahe(e){return e.reduce((t,n)=>dg(t,vF(n)),al)}function Yut(e){return e.reduce((t,n)=>t+rhe(n),0)}function Zut(e){return e.reduce((t,n)=>t+ohe(n),0)}function lhe(e,t){if(t===void 0&&(t=Qb),!e)return;const{top:n,left:r,bottom:o,right:s}=t(e);nhe(e)&&(o<=0||s<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const Xut=[["x",["left","right"],Yut],["y",["top","bottom"],Zut]];class Az{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=sT(n),o=ahe(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[s,i,a]of Xut)for(const c of i)Object.defineProperty(this,c,{get:()=>{const u=a(r),d=o[s]-u;return this.rect[c]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class s0{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var o;(o=this.target)==null||o.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function Qut(e){const{EventTarget:t}=ni(e);return e instanceof t?e:Xb(e)}function XM(e,t){const n=Math.abs(e.x),r=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var aa;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(aa||(aa={}));function $W(e){e.preventDefault()}function Jut(e){e.stopPropagation()}var Fn;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(Fn||(Fn={}));const che={start:[Fn.Space,Fn.Enter],cancel:[Fn.Esc],end:[Fn.Space,Fn.Enter,Fn.Tab]},edt=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Fn.Right:return{...n,x:n.x+25};case Fn.Left:return{...n,x:n.x-25};case Fn.Down:return{...n,y:n.y+25};case Fn.Up:return{...n,y:n.y-25}}};class eC{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new s0(Xb(n)),this.windowListeners=new s0(ni(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(aa.Resize,this.handleCancel),this.windowListeners.add(aa.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(aa.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&lhe(r),n(al)}handleKeyDown(t){if(rT(t)){const{active:n,context:r,options:o}=this.props,{keyboardCodes:s=che,coordinateGetter:i=edt,scrollBehavior:a="smooth"}=o,{code:c}=t;if(s.end.includes(c)){this.handleEnd(t);return}if(s.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:al;this.referenceCoordinates||(this.referenceCoordinates=d);const f=i(t,{active:n,context:r.current,currentCoordinates:d});if(f){const h=uv(f,d),m={x:0,y:0},{scrollableAncestors:g}=r.current;for(const b of g){const x=t.code,{isTop:y,isRight:w,isLeft:C,isBottom:N,maxScroll:S,minScroll:j}=ihe(b),_=Gut(b),k={x:Math.min(x===Fn.Right?_.right-_.width/2:_.right,Math.max(x===Fn.Right?_.left:_.left+_.width/2,f.x)),y:Math.min(x===Fn.Down?_.bottom-_.height/2:_.bottom,Math.max(x===Fn.Down?_.top:_.top+_.height/2,f.y))},T=x===Fn.Right&&!w||x===Fn.Left&&!C,I=x===Fn.Down&&!N||x===Fn.Up&&!y;if(T&&k.x!==f.x){const E=b.scrollLeft+h.x,D=x===Fn.Right&&E<=S.x||x===Fn.Left&&E>=j.x;if(D&&!h.y){b.scrollTo({left:E,behavior:a});return}D?m.x=b.scrollLeft-E:m.x=x===Fn.Right?b.scrollLeft-S.x:b.scrollLeft-j.x,m.x&&b.scrollBy({left:-m.x,behavior:a});break}else if(I&&k.y!==f.y){const E=b.scrollTop+h.y,D=x===Fn.Down&&E<=S.y||x===Fn.Up&&E>=j.y;if(D&&!h.x){b.scrollTo({top:E,behavior:a});return}D?m.y=b.scrollTop-E:m.y=x===Fn.Down?b.scrollTop-S.y:b.scrollTop-j.y,m.y&&b.scrollBy({top:-m.y,behavior:a});break}}this.handleMove(t,dg(uv(f,this.referenceCoordinates),m))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}eC.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=che,onActivation:o}=t,{active:s}=n;const{code:i}=e.nativeEvent;if(r.start.includes(i)){const a=s.activatorNode.current;return a&&e.target!==a?!1:(e.preventDefault(),o==null||o({event:e.nativeEvent}),!0)}return!1}}];function zW(e){return!!(e&&"distance"in e)}function BW(e){return!!(e&&"delay"in e)}class Pz{constructor(t,n,r){var o;r===void 0&&(r=Qut(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:s}=t,{target:i}=s;this.props=t,this.events=n,this.document=Xb(i),this.documentListeners=new s0(this.document),this.listeners=new s0(r),this.windowListeners=new s0(ni(i)),this.initialCoordinates=(o=rk(s))!=null?o:al,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(aa.Resize,this.handleCancel),this.windowListeners.add(aa.DragStart,$W),this.windowListeners.add(aa.VisibilityChange,this.handleCancel),this.windowListeners.add(aa.ContextMenu,$W),this.documentListeners.add(aa.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(BW(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(zW(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:o}=this.props;o(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(aa.Click,Jut,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(aa.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:o,props:s}=this,{onMove:i,options:{activationConstraint:a}}=s;if(!o)return;const c=(n=rk(t))!=null?n:al,u=uv(o,c);if(!r&&a){if(zW(a)){if(a.tolerance!=null&&XM(u,a.tolerance))return this.handleCancel();if(XM(u,a.distance))return this.handleStart()}if(BW(a)&&XM(u,a.tolerance))return this.handleCancel();this.handlePending(a,u);return}t.cancelable&&t.preventDefault(),i(c)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Fn.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const tdt={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Jb extends Pz{constructor(t){const{event:n}=t,r=Xb(n.target);super(t,tdt,r)}}Jb.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const ndt={move:{name:"mousemove"},end:{name:"mouseup"}};var wF;(function(e){e[e.RightClick=2]="RightClick"})(wF||(wF={}));class rdt extends Pz{constructor(t){super(t,ndt,Xb(t.event.target))}}rdt.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===wF.RightClick?!1:(r==null||r({event:n}),!0)}}];const QM={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class odt extends Pz{constructor(t){super(t,QM)}static setup(){return window.addEventListener(QM.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(QM.move.name,t)};function t(){}}}odt.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:o}=n;return o.length>1?!1:(r==null||r({event:n}),!0)}}];var i0;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(i0||(i0={}));var sk;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(sk||(sk={}));function sdt(e){let{acceleration:t,activator:n=i0.Pointer,canScroll:r,draggingRect:o,enabled:s,interval:i=5,order:a=sk.TreeOrder,pointerCoordinates:c,scrollableAncestors:u,scrollableAncestorRects:d,delta:f,threshold:h}=e;const m=adt({delta:f,disabled:!s}),[g,b]=vut(),x=v.useRef({x:0,y:0}),y=v.useRef({x:0,y:0}),w=v.useMemo(()=>{switch(n){case i0.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case i0.DraggableRect:return o}},[n,o,c]),C=v.useRef(null),N=v.useCallback(()=>{const j=C.current;if(!j)return;const _=x.current.x*y.current.x,k=x.current.y*y.current.y;j.scrollBy(_,k)},[]),S=v.useMemo(()=>a===sk.TreeOrder?[...u].reverse():u,[a,u]);v.useEffect(()=>{if(!s||!u.length||!w){b();return}for(const j of S){if((r==null?void 0:r(j))===!1)continue;const _=u.indexOf(j),k=d[_];if(!k)continue;const{direction:T,speed:I}=Kut(j,k,w,t,h);for(const E of["x","y"])m[E][T[E]]||(I[E]=0,T[E]=0);if(I.x>0||I.y>0){b(),C.current=j,g(N,i),x.current=I,y.current=T;return}}x.current={x:0,y:0},y.current={x:0,y:0},b()},[t,N,r,b,s,i,JSON.stringify(w),JSON.stringify(m),g,u,S,d,JSON.stringify(h)])}const idt={x:{[Fo.Backward]:!1,[Fo.Forward]:!1},y:{[Fo.Backward]:!1,[Fo.Forward]:!1}};function adt(e){let{delta:t,disabled:n}=e;const r=nk(t);return Xw(o=>{if(n||!r||!o)return idt;const s={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[Fo.Backward]:o.x[Fo.Backward]||s.x===-1,[Fo.Forward]:o.x[Fo.Forward]||s.x===1},y:{[Fo.Backward]:o.y[Fo.Backward]||s.y===-1,[Fo.Forward]:o.y[Fo.Forward]||s.y===1}}},[n,t,r])}function ldt(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return Xw(o=>{var s;return t==null?null:(s=r??o)!=null?s:null},[r,t])}function cdt(e,t){return v.useMemo(()=>e.reduce((n,r)=>{const{sensor:o}=r,s=o.activators.map(i=>({eventName:i.eventName,handler:t(i.handler,r)}));return[...n,...s]},[]),[e,t])}var dv;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(dv||(dv={}));var CF;(function(e){e.Optimized="optimized"})(CF||(CF={}));const VW=new Map;function udt(e,t){let{dragging:n,dependencies:r,config:o}=t;const[s,i]=v.useState(null),{frequency:a,measure:c,strategy:u}=o,d=v.useRef(e),f=x(),h=cv(f),m=v.useCallback(function(y){y===void 0&&(y=[]),!h.current&&i(w=>w===null?y:w.concat(y.filter(C=>!w.includes(C))))},[h]),g=v.useRef(null),b=Xw(y=>{if(f&&!n)return VW;if(!y||y===VW||d.current!==e||s!=null){const w=new Map;for(let C of e){if(!C)continue;if(s&&s.length>0&&!s.includes(C.id)&&C.rect.current){w.set(C.id,C.rect.current);continue}const N=C.node.current,S=N?new Az(c(N),N):null;C.rect.current=S,S&&w.set(C.id,S)}return w}return y},[e,s,n,f,c]);return v.useEffect(()=>{d.current=e},[e]),v.useEffect(()=>{f||m()},[n,f]),v.useEffect(()=>{s&&s.length>0&&i(null)},[JSON.stringify(s)]),v.useEffect(()=>{f||typeof a!="number"||g.current!==null||(g.current=setTimeout(()=>{m(),g.current=null},a))},[a,f,m,...r]),{droppableRects:b,measureDroppableContainers:m,measuringScheduled:s!=null};function x(){switch(u){case dv.Always:return!1;case dv.BeforeDragging:return n;default:return!n}}}function Fz(e,t){return Xw(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function ddt(e,t){return Fz(e,t)}function fdt(e){let{callback:t,disabled:n}=e;const r=nT(t),o=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(r)},[r,n]);return v.useEffect(()=>()=>o==null?void 0:o.disconnect(),[o]),o}function iT(e){let{callback:t,disabled:n}=e;const r=nT(t),o=v.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(r)},[n]);return v.useEffect(()=>()=>o==null?void 0:o.disconnect(),[o]),o}function hdt(e){return new Az(Qb(e),e)}function HW(e,t,n){t===void 0&&(t=hdt);const[r,o]=v.useState(null);function s(){o(c=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=c??n)!=null?u:null}const d=t(e);return JSON.stringify(c)===JSON.stringify(d)?c:d})}const i=fdt({callback(c){if(e)for(const u of c){const{type:d,target:f}=u;if(d==="childList"&&f instanceof HTMLElement&&f.contains(e)){s();break}}}}),a=iT({callback:s});return il(()=>{s(),e?(a==null||a.observe(e),i==null||i.observe(document.body,{childList:!0,subtree:!0})):(a==null||a.disconnect(),i==null||i.disconnect())},[e]),r}function mdt(e){const t=Fz(e);return ehe(e,t)}const qW=[];function pdt(e){const t=v.useRef(e),n=Xw(r=>e?r&&r!==qW&&e&&t.current&&e.parentNode===t.current.parentNode?r:sT(e):qW,[e]);return v.useEffect(()=>{t.current=e},[e]),n}function gdt(e){const[t,n]=v.useState(null),r=v.useRef(e),o=v.useCallback(s=>{const i=ZM(s.target);i&&n(a=>a?(a.set(i,vF(i)),new Map(a)):null)},[]);return v.useEffect(()=>{const s=r.current;if(e!==s){i(s);const a=e.map(c=>{const u=ZM(c);return u?(u.addEventListener("scroll",o,{passive:!0}),[u,vF(u)]):null}).filter(c=>c!=null);n(a.length?new Map(a):null),r.current=e}return()=>{i(e),i(s)};function i(a){a.forEach(c=>{const u=ZM(c);u==null||u.removeEventListener("scroll",o)})}},[o,e]),v.useMemo(()=>e.length?t?Array.from(t.values()).reduce((s,i)=>dg(s,i),al):ahe(e):al,[e,t])}function UW(e,t){t===void 0&&(t=[]);const n=v.useRef(null);return v.useEffect(()=>{n.current=null},t),v.useEffect(()=>{const r=e!==al;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?uv(e,n.current):al}function bdt(e){v.useEffect(()=>{if(!tT)return;const t=e.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n==null||n()}},e.map(t=>{let{sensor:n}=t;return n}))}function xdt(e,t){return v.useMemo(()=>e.reduce((n,r)=>{let{eventName:o,handler:s}=r;return n[o]=i=>{s(i,t)},n},{}),[e,t])}function uhe(e){return v.useMemo(()=>e?Hut(e):null,[e])}const WW=[];function ydt(e,t){t===void 0&&(t=Qb);const[n]=e,r=uhe(n?ni(n):null),[o,s]=v.useState(WW);function i(){s(()=>e.length?e.map(c=>she(c)?r:new Az(t(c),c)):WW)}const a=iT({callback:i});return il(()=>{a==null||a.disconnect(),i(),e.forEach(c=>a==null?void 0:a.observe(c))},[e]),o}function dhe(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Zw(t)?t:e}function vdt(e){let{measure:t}=e;const[n,r]=v.useState(null),o=v.useCallback(u=>{for(const{target:d}of u)if(Zw(d)){r(f=>{const h=t(d);return f?{...f,width:h.width,height:h.height}:h});break}},[t]),s=iT({callback:o}),i=v.useCallback(u=>{const d=dhe(u);s==null||s.disconnect(),d&&(s==null||s.observe(d)),r(d?t(d):null)},[t,s]),[a,c]=tk(i);return v.useMemo(()=>({nodeRef:a,rect:n,setRef:c}),[n,a,c])}const wdt=[{sensor:Jb,options:{}},{sensor:eC,options:{}}],Cdt={current:{}},Y1={draggable:{measure:LW},droppable:{measure:LW,strategy:dv.WhileDragging,frequency:CF.Optimized},dragOverlay:{measure:Qb}};class a0 extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const Sdt={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new a0,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ok},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Y1,measureDroppableContainers:ok,windowRect:null,measuringScheduled:!1},fhe={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:ok,draggableNodes:new Map,over:null,measureDroppableContainers:ok},tC=v.createContext(fhe),hhe=v.createContext(Sdt);function Ndt(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new a0}}}function jdt(e,t){switch(t.type){case ko.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case ko.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case ko.DragEnd:case ko.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ko.RegisterDroppable:{const{element:n}=t,{id:r}=n,o=new a0(e.droppable.containers);return o.set(r,n),{...e,droppable:{...e.droppable,containers:o}}}case ko.SetDroppableDisabled:{const{id:n,key:r,disabled:o}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const i=new a0(e.droppable.containers);return i.set(n,{...s,disabled:o}),{...e,droppable:{...e.droppable,containers:i}}}case ko.UnregisterDroppable:{const{id:n,key:r}=t,o=e.droppable.containers.get(n);if(!o||r!==o.key)return e;const s=new a0(e.droppable.containers);return s.delete(n),{...e,droppable:{...e.droppable,containers:s}}}default:return e}}function kdt(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:o}=v.useContext(tC),s=nk(r),i=nk(n==null?void 0:n.id);return v.useEffect(()=>{if(!t&&!r&&s&&i!=null){if(!rT(s)||document.activeElement===s.target)return;const a=o.get(i);if(!a)return;const{activatorNode:c,node:u}=a;if(!c.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[c.current,u.current]){if(!d)continue;const f=Sut(d);if(f){f.focus();break}}})}},[r,t,o,i,s]),null}function mhe(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((o,s)=>s({transform:o,...r}),n):n}function _dt(e){return v.useMemo(()=>({draggable:{...Y1.draggable,...e==null?void 0:e.draggable},droppable:{...Y1.droppable,...e==null?void 0:e.droppable},dragOverlay:{...Y1.dragOverlay,...e==null?void 0:e.dragOverlay}}),[e==null?void 0:e.draggable,e==null?void 0:e.droppable,e==null?void 0:e.dragOverlay])}function Idt(e){let{activeNode:t,measure:n,initialRect:r,config:o=!0}=e;const s=v.useRef(!1),{x:i,y:a}=typeof o=="boolean"?{x:o,y:o}:o;il(()=>{if(!i&&!a||!t){s.current=!1;return}if(s.current||!r)return;const u=t==null?void 0:t.node.current;if(!u||u.isConnected===!1)return;const d=n(u),f=ehe(d,r);if(i||(f.x=0),a||(f.y=0),s.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const h=nhe(u);h&&h.scrollBy({top:f.y,left:f.x})}},[t,i,a,r,n])}const aT=v.createContext({...al,scaleX:1,scaleY:1});var rd;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(rd||(rd={}));const nC=v.memo(function(t){var n,r,o,s;let{id:i,accessibility:a,autoScroll:c=!0,children:u,sensors:d=wdt,collisionDetection:f=Out,measuring:h,modifiers:m,...g}=t;const b=v.useReducer(jdt,void 0,Ndt),[x,y]=b,[w,C]=Tut(),[N,S]=v.useState(rd.Uninitialized),j=N===rd.Initialized,{draggable:{active:_,nodes:k,translate:T},droppable:{containers:I}}=x,E=_!=null?k.get(_):null,D=v.useRef({initial:null,translated:null}),R=v.useMemo(()=>{var Ae;return _!=null?{id:_,data:(Ae=E==null?void 0:E.data)!=null?Ae:Cdt,rect:D}:null},[_,E]),A=v.useRef(null),[F,z]=v.useState(null),[L,$]=v.useState(null),H=cv(g,Object.values(g)),M=Qw("DndDescribedBy",i),B=v.useMemo(()=>I.getEnabled(),[I]),W=_dt(h),{droppableRects:P,measureDroppableContainers:G,measuringScheduled:Z}=udt(B,{dragging:j,dependencies:[T.x,T.y],config:W.droppable}),X=ldt(k,_),Y=v.useMemo(()=>L?rk(L):null,[L]),O=Ve(),q=ddt(X,W.draggable.measure);Idt({activeNode:_!=null?k.get(_):null,config:O.layoutShiftCompensation,initialRect:q,measure:W.draggable.measure});const U=HW(X,W.draggable.measure,q),V=HW(X?X.parentElement:null),K=v.useRef({activatorEvent:null,active:null,activeNode:X,collisionRect:null,collisions:null,droppableRects:P,draggableNodes:k,draggingNode:null,draggingNodeRect:null,droppableContainers:I,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Q=I.getNodeFor((n=K.current.over)==null?void 0:n.id),se=vdt({measure:W.dragOverlay.measure}),oe=(r=se.nodeRef.current)!=null?r:X,me=j?(o=se.rect)!=null?o:U:null,le=!!(se.nodeRef.current&&se.rect),ue=mdt(le?null:U),ne=uhe(oe?ni(oe):null),de=pdt(j?Q??X:null),Ce=ydt(de),ce=mhe(m,{transform:{x:T.x-ue.x,y:T.y-ue.y,scaleX:1,scaleY:1},activatorEvent:L,active:R,activeNodeRect:U,containerNodeRect:V,draggingNodeRect:me,over:K.current.over,overlayNodeRect:se.rect,scrollableAncestors:de,scrollableAncestorRects:Ce,windowRect:ne}),ie=Y?dg(Y,T):null,we=gdt(de),fe=UW(we),ae=UW(we,[U]),ee=dg(ce,fe),J=me?zut(me,ce):null,re=R&&J?f({active:R,collisionRect:J,droppableRects:P,droppableContainers:B,pointerCoordinates:ie}):null,pe=Jfe(re,"id"),[Ee,Te]=v.useState(null),ze=le?ce:dg(ce,ae),Pe=Lut(ze,(s=Ee==null?void 0:Ee.rect)!=null?s:null,U),He=v.useRef(null),ye=v.useCallback((Ae,ke)=>{let{sensor:Be,options:Ie}=ke;if(A.current==null)return;const $e=k.get(A.current);if(!$e)return;const st=Ae.nativeEvent,ct=new Be({active:A.current,activeNode:$e,event:st,options:Ie,context:K,onAbort(Ct){if(!k.get(Ct))return;const{onDragAbort:vt}=H.current,Tt={id:Ct};vt==null||vt(Tt),w({type:"onDragAbort",event:Tt})},onPending(Ct,Lt,vt,Tt){if(!k.get(Ct))return;const{onDragPending:Je}=H.current,kt={id:Ct,constraint:Lt,initialCoordinates:vt,offset:Tt};Je==null||Je(kt),w({type:"onDragPending",event:kt})},onStart(Ct){const Lt=A.current;if(Lt==null)return;const vt=k.get(Lt);if(!vt)return;const{onDragStart:Tt}=H.current,Me={activatorEvent:st,active:{id:Lt,data:vt.data,rect:D}};br.unstable_batchedUpdates(()=>{Tt==null||Tt(Me),S(rd.Initializing),y({type:ko.DragStart,initialCoordinates:Ct,active:Lt}),w({type:"onDragStart",event:Me}),z(He.current),$(st)})},onMove(Ct){y({type:ko.DragMove,coordinates:Ct})},onEnd:rt(ko.DragEnd),onCancel:rt(ko.DragCancel)});He.current=ct;function rt(Ct){return async function(){const{active:vt,collisions:Tt,over:Me,scrollAdjustedTranslate:Je}=K.current;let kt=null;if(vt&&Je){const{cancelDrop:mt}=H.current;kt={activatorEvent:st,active:vt,collisions:Tt,delta:Je,over:Me},Ct===ko.DragEnd&&typeof mt=="function"&&await Promise.resolve(mt(kt))&&(Ct=ko.DragCancel)}A.current=null,br.unstable_batchedUpdates(()=>{y({type:Ct}),S(rd.Uninitialized),Te(null),z(null),$(null),He.current=null;const mt=Ct===ko.DragEnd?"onDragEnd":"onDragCancel";if(kt){const _t=H.current[mt];_t==null||_t(kt),w({type:mt,event:kt})}})}}},[k]),Ke=v.useCallback((Ae,ke)=>(Be,Ie)=>{const $e=Be.nativeEvent,st=k.get(Ie);if(A.current!==null||!st||$e.dndKit||$e.defaultPrevented)return;const ct={active:st};Ae(Be,ke.options,ct)===!0&&($e.dndKit={capturedBy:ke.sensor},A.current=Ie,ye(Be,ke))},[k,ye]),We=cdt(d,Ke);bdt(d),il(()=>{U&&N===rd.Initializing&&S(rd.Initialized)},[U,N]),v.useEffect(()=>{const{onDragMove:Ae}=H.current,{active:ke,activatorEvent:Be,collisions:Ie,over:$e}=K.current;if(!ke||!Be)return;const st={active:ke,activatorEvent:Be,collisions:Ie,delta:{x:ee.x,y:ee.y},over:$e};br.unstable_batchedUpdates(()=>{Ae==null||Ae(st),w({type:"onDragMove",event:st})})},[ee.x,ee.y]),v.useEffect(()=>{const{active:Ae,activatorEvent:ke,collisions:Be,droppableContainers:Ie,scrollAdjustedTranslate:$e}=K.current;if(!Ae||A.current==null||!ke||!$e)return;const{onDragOver:st}=H.current,ct=Ie.get(pe),rt=ct&&ct.rect.current?{id:ct.id,rect:ct.rect.current,data:ct.data,disabled:ct.disabled}:null,Ct={active:Ae,activatorEvent:ke,collisions:Be,delta:{x:$e.x,y:$e.y},over:rt};br.unstable_batchedUpdates(()=>{Te(rt),st==null||st(Ct),w({type:"onDragOver",event:Ct})})},[pe]),il(()=>{K.current={activatorEvent:L,active:R,activeNode:X,collisionRect:J,collisions:re,droppableRects:P,draggableNodes:k,draggingNode:oe,draggingNodeRect:me,droppableContainers:I,over:Ee,scrollableAncestors:de,scrollAdjustedTranslate:ee},D.current={initial:me,translated:J}},[R,X,re,J,k,oe,me,P,I,Ee,de,ee]),sdt({...O,delta:T,draggingRect:J,pointerCoordinates:ie,scrollableAncestors:de,scrollableAncestorRects:Ce});const Qe=v.useMemo(()=>({active:R,activeNode:X,activeNodeRect:U,activatorEvent:L,collisions:re,containerNodeRect:V,dragOverlay:se,draggableNodes:k,droppableContainers:I,droppableRects:P,over:Ee,measureDroppableContainers:G,scrollableAncestors:de,scrollableAncestorRects:Ce,measuringConfiguration:W,measuringScheduled:Z,windowRect:ne}),[R,X,U,L,re,V,se,k,I,P,Ee,G,de,Ce,W,Z,ne]),xe=v.useMemo(()=>({activatorEvent:L,activators:We,active:R,activeNodeRect:U,ariaDescribedById:{draggable:M},dispatch:y,draggableNodes:k,over:Ee,measureDroppableContainers:G}),[L,We,R,U,y,M,k,Ee,G]);return v.createElement(Zfe.Provider,{value:C},v.createElement(tC.Provider,{value:xe},v.createElement(hhe.Provider,{value:Qe},v.createElement(aT.Provider,{value:Pe},u)),v.createElement(kdt,{disabled:(a==null?void 0:a.restoreFocus)===!1})),v.createElement(Mut,{...a,hiddenTextDescribedById:M}));function Ve(){const Ae=(F==null?void 0:F.autoScrollEnabled)===!1,ke=typeof c=="object"?c.enabled===!1:c===!1,Be=j&&!Ae&&!ke;return typeof c=="object"?{...c,enabled:Be}:{enabled:Be}}}),Tdt=v.createContext(null),KW="button",Edt="Draggable";function Ddt(e){let{id:t,data:n,disabled:r=!1,attributes:o}=e;const s=Qw(Edt),{activators:i,activatorEvent:a,active:c,activeNodeRect:u,ariaDescribedById:d,draggableNodes:f,over:h}=v.useContext(tC),{role:m=KW,roleDescription:g="draggable",tabIndex:b=0}=o??{},x=(c==null?void 0:c.id)===t,y=v.useContext(x?aT:Tdt),[w,C]=tk(),[N,S]=tk(),j=xdt(i,t),_=cv(n);il(()=>(f.set(t,{id:t,key:s,node:w,activatorNode:N,data:_}),()=>{const T=f.get(t);T&&T.key===s&&f.delete(t)}),[f,t]);const k=v.useMemo(()=>({role:m,tabIndex:b,"aria-disabled":r,"aria-pressed":x&&m===KW?!0:void 0,"aria-roledescription":g,"aria-describedby":d.draggable}),[r,m,b,x,g,d.draggable]);return{active:c,activatorEvent:a,activeNodeRect:u,attributes:k,isDragging:x,listeners:r?void 0:j,node:w,over:h,setNodeRef:C,setActivatorNodeRef:S,transform:y}}function phe(){return v.useContext(hhe)}const Mdt="Droppable",Rdt={timeout:25};function ghe(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:o}=e;const s=Qw(Mdt),{active:i,dispatch:a,over:c,measureDroppableContainers:u}=v.useContext(tC),d=v.useRef({disabled:n}),f=v.useRef(!1),h=v.useRef(null),m=v.useRef(null),{disabled:g,updateMeasurementsFor:b,timeout:x}={...Rdt,...o},y=cv(b??r),w=v.useCallback(()=>{if(!f.current){f.current=!0;return}m.current!=null&&clearTimeout(m.current),m.current=setTimeout(()=>{u(Array.isArray(y.current)?y.current:[y.current]),m.current=null},x)},[x]),C=iT({callback:w,disabled:g||!i}),N=v.useCallback((k,T)=>{C&&(T&&(C.unobserve(T),f.current=!1),k&&C.observe(k))},[C]),[S,j]=tk(N),_=cv(t);return v.useEffect(()=>{!C||!S.current||(C.disconnect(),f.current=!1,C.observe(S.current))},[S,C]),v.useEffect(()=>(a({type:ko.RegisterDroppable,element:{id:r,key:s,disabled:n,node:S,rect:h,data:_}}),()=>a({type:ko.UnregisterDroppable,key:s,id:r})),[r]),v.useEffect(()=>{n!==d.current.disabled&&(a({type:ko.SetDroppableDisabled,id:r,key:s,disabled:n}),d.current.disabled=n)},[r,s,n,a]),{active:i,rect:h,isOver:(c==null?void 0:c.id)===r,node:S,over:c,setNodeRef:j}}function Adt(e){let{animation:t,children:n}=e;const[r,o]=v.useState(null),[s,i]=v.useState(null),a=nk(n);return!n&&!r&&a&&o(a),il(()=>{if(!s)return;const c=r==null?void 0:r.key,u=r==null?void 0:r.props.id;if(c==null||u==null){o(null);return}Promise.resolve(t(u,s)).then(()=>{o(null)})},[t,r,s]),v.createElement(v.Fragment,null,n,r?v.cloneElement(r,{ref:i}):null)}const Pdt={x:0,y:0,scaleX:1,scaleY:1};function Fdt(e){let{children:t}=e;return v.createElement(tC.Provider,{value:fhe},v.createElement(aT.Provider,{value:Pdt},t))}const Odt={position:"fixed",touchAction:"none"},Ldt=e=>rT(e)?"transform 250ms ease":void 0,$dt=v.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:o,children:s,className:i,rect:a,style:c,transform:u,transition:d=Ldt}=e;if(!a)return null;const f=o?u:{...u,scaleX:1,scaleY:1},h={...Odt,width:a.width,height:a.height,top:a.top,left:a.left,transform:Ki.Transform.toString(f),transformOrigin:o&&r?Rut(r,a):void 0,transition:typeof d=="function"?d(r):d,...c};return v.createElement(n,{className:i,style:h,ref:t},s)}),zdt=e=>t=>{let{active:n,dragOverlay:r}=t;const o={},{styles:s,className:i}=e;if(s!=null&&s.active)for(const[a,c]of Object.entries(s.active))c!==void 0&&(o[a]=n.node.style.getPropertyValue(a),n.node.style.setProperty(a,c));if(s!=null&&s.dragOverlay)for(const[a,c]of Object.entries(s.dragOverlay))c!==void 0&&r.node.style.setProperty(a,c);return i!=null&&i.active&&n.node.classList.add(i.active),i!=null&&i.dragOverlay&&r.node.classList.add(i.dragOverlay),function(){for(const[c,u]of Object.entries(o))n.node.style.setProperty(c,u);i!=null&&i.active&&n.node.classList.remove(i.active)}},Bdt=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Ki.Transform.toString(t)},{transform:Ki.Transform.toString(n)}]},Vdt={duration:250,easing:"ease",keyframes:Bdt,sideEffects:zdt({styles:{active:{opacity:"0"}}})};function Hdt(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:o}=e;return nT((s,i)=>{if(t===null)return;const a=n.get(s);if(!a)return;const c=a.node.current;if(!c)return;const u=dhe(i);if(!u)return;const{transform:d}=ni(i).getComputedStyle(i),f=the(d);if(!f)return;const h=typeof t=="function"?t:qdt(t);return lhe(c,o.draggable.measure),h({active:{id:s,data:a.data,node:c,rect:o.draggable.measure(c)},draggableNodes:n,dragOverlay:{node:i,rect:o.dragOverlay.measure(u)},droppableContainers:r,measuringConfiguration:o,transform:f})})}function qdt(e){const{duration:t,easing:n,sideEffects:r,keyframes:o}={...Vdt,...e};return s=>{let{active:i,dragOverlay:a,transform:c,...u}=s;if(!t)return;const d={x:a.rect.left-i.rect.left,y:a.rect.top-i.rect.top},f={scaleX:c.scaleX!==1?i.rect.width*c.scaleX/a.rect.width:1,scaleY:c.scaleY!==1?i.rect.height*c.scaleY/a.rect.height:1},h={x:c.x-d.x,y:c.y-d.y,...f},m=o({...u,active:i,dragOverlay:a,transform:{initial:c,final:h}}),[g]=m,b=m[m.length-1];if(JSON.stringify(g)===JSON.stringify(b))return;const x=r==null?void 0:r({active:i,dragOverlay:a,...u}),y=a.node.animate(m,{duration:t,easing:n,fill:"forwards"});return new Promise(w=>{y.onfinish=()=>{x==null||x(),w()}})}}let GW=0;function Udt(e){return v.useMemo(()=>{if(e!=null)return GW++,GW},[e])}const bhe=v.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:o,transition:s,modifiers:i,wrapperElement:a="div",className:c,zIndex:u=999}=e;const{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:m,draggableNodes:g,droppableContainers:b,dragOverlay:x,over:y,measuringConfiguration:w,scrollableAncestors:C,scrollableAncestorRects:N,windowRect:S}=phe(),j=v.useContext(aT),_=Udt(f==null?void 0:f.id),k=mhe(i,{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:m,draggingNodeRect:x.rect,over:y,overlayNodeRect:x.rect,scrollableAncestors:C,scrollableAncestorRects:N,transform:j,windowRect:S}),T=Fz(h),I=Hdt({config:r,draggableNodes:g,droppableContainers:b,measuringConfiguration:w}),E=T?x.setRef:void 0;return v.createElement(Fdt,null,v.createElement(Adt,{animation:I},f&&_?v.createElement($dt,{key:_,id:f.id,ref:E,as:a,activatorEvent:d,adjustScale:t,className:c,transition:s,rect:T,style:{zIndex:u,...o},transform:k},n):null))});function ex(e,t,n){const r=e.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function Wdt(e,t){return e.reduce((n,r,o)=>{const s=t.get(r);return s&&(n[o]=s),n},Array(e.length))}function KS(e){return e!==null&&e>=0}function Kdt(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Gdt(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const GS={scaleX:1,scaleY:1},Oz=e=>{var t;let{rects:n,activeNodeRect:r,activeIndex:o,overIndex:s,index:i}=e;const a=(t=n[o])!=null?t:r;if(!a)return null;const c=Ydt(n,i,o);if(i===o){const u=n[s];return u?{x:o<s?u.left+u.width-(a.left+a.width):u.left-a.left,y:0,...GS}:null}return i>o&&i<=s?{x:-a.width-c,y:0,...GS}:i<o&&i>=s?{x:a.width+c,y:0,...GS}:{x:0,y:0,...GS}};function Ydt(e,t,n){const r=e[t],o=e[t-1],s=e[t+1];return!r||!o&&!s?0:n<t?o?r.left-(o.left+o.width):s.left-(r.left+r.width):s?s.left-(r.left+r.width):r.left-(o.left+o.width)}const xhe=e=>{let{rects:t,activeIndex:n,overIndex:r,index:o}=e;const s=ex(t,r,n),i=t[o],a=s[o];return!a||!i?null:{x:a.left-i.left,y:a.top-i.top,scaleX:a.width/i.width,scaleY:a.height/i.height}},YS={scaleX:1,scaleY:1},Lz=e=>{var t;let{activeIndex:n,activeNodeRect:r,index:o,rects:s,overIndex:i}=e;const a=(t=s[n])!=null?t:r;if(!a)return null;if(o===n){const u=s[i];return u?{x:0,y:n<i?u.top+u.height-(a.top+a.height):u.top-a.top,...YS}:null}const c=Zdt(s,o,n);return o>n&&o<=i?{x:0,y:-a.height-c,...YS}:o<n&&o>=i?{x:0,y:a.height+c,...YS}:{x:0,y:0,...YS}};function Zdt(e,t,n){const r=e[t],o=e[t-1],s=e[t+1];return r?n<t?o?r.top-(o.top+o.height):s?s.top-(r.top+r.height):0:s?s.top-(r.top+r.height):o?r.top-(o.top+o.height):0:0}const yhe="Sortable",vhe=v.createContext({activeIndex:-1,containerId:yhe,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:xhe,disabled:{draggable:!1,droppable:!1}});function rC(e){let{children:t,id:n,items:r,strategy:o=xhe,disabled:s=!1}=e;const{active:i,dragOverlay:a,droppableRects:c,over:u,measureDroppableContainers:d}=phe(),f=Qw(yhe,n),h=a.rect!==null,m=v.useMemo(()=>r.map(j=>typeof j=="object"&&"id"in j?j.id:j),[r]),g=i!=null,b=i?m.indexOf(i.id):-1,x=u?m.indexOf(u.id):-1,y=v.useRef(m),w=!Kdt(m,y.current),C=x!==-1&&b===-1||w,N=Gdt(s);il(()=>{w&&g&&d(m)},[w,m,g,d]),v.useEffect(()=>{y.current=m},[m]);const S=v.useMemo(()=>({activeIndex:b,containerId:f,disabled:N,disableTransforms:C,items:m,overIndex:x,useDragOverlay:h,sortedRects:Wdt(m,c),strategy:o}),[b,f,N.draggable,N.droppable,C,m,x,c,h,o]);return v.createElement(vhe.Provider,{value:S},t)}const Xdt=e=>{let{id:t,items:n,activeIndex:r,overIndex:o}=e;return ex(n,r,o).indexOf(t)},Qdt=e=>{let{containerId:t,isSorting:n,wasDragging:r,index:o,items:s,newIndex:i,previousItems:a,previousContainerId:c,transition:u}=e;return!u||!r||a!==s&&o===i?!1:n?!0:i!==o&&t===c},Jdt={duration:200,easing:"ease"},whe="transform",eft=Ki.Transition.toString({property:whe,duration:0,easing:"linear"}),tft={roleDescription:"sortable"};function nft(e){let{disabled:t,index:n,node:r,rect:o}=e;const[s,i]=v.useState(null),a=v.useRef(n);return il(()=>{if(!t&&n!==a.current&&r.current){const c=o.current;if(c){const u=Qb(r.current,{ignoreTransform:!0}),d={x:c.left-u.left,y:c.top-u.top,scaleX:c.width/u.width,scaleY:c.height/u.height};(d.x||d.y)&&i(d)}}n!==a.current&&(a.current=n)},[t,n,r,o]),v.useEffect(()=>{s&&i(null)},[s]),s}function tx(e){let{animateLayoutChanges:t=Qdt,attributes:n,disabled:r,data:o,getNewIndex:s=Xdt,id:i,strategy:a,resizeObserverConfig:c,transition:u=Jdt}=e;const{items:d,containerId:f,activeIndex:h,disabled:m,disableTransforms:g,sortedRects:b,overIndex:x,useDragOverlay:y,strategy:w}=v.useContext(vhe),C=rft(r,m),N=d.indexOf(i),S=v.useMemo(()=>({sortable:{containerId:f,index:N,items:d},...o}),[f,o,N,d]),j=v.useMemo(()=>d.slice(d.indexOf(i)),[d,i]),{rect:_,node:k,isOver:T,setNodeRef:I}=ghe({id:i,data:S,disabled:C.droppable,resizeObserverConfig:{updateMeasurementsFor:j,...c}}),{active:E,activatorEvent:D,activeNodeRect:R,attributes:A,setNodeRef:F,listeners:z,isDragging:L,over:$,setActivatorNodeRef:H,transform:M}=Ddt({id:i,data:S,attributes:{...tft,...n},disabled:C.draggable}),B=yut(I,F),W=!!E,P=W&&!g&&KS(h)&&KS(x),G=!y&&L,Z=G&&P?M:null,Y=P?Z??(a??w)({rects:b,activeNodeRect:R,activeIndex:h,overIndex:x,index:N}):null,O=KS(h)&&KS(x)?s({id:i,items:d,activeIndex:h,overIndex:x}):N,q=E==null?void 0:E.id,U=v.useRef({activeId:q,items:d,newIndex:O,containerId:f}),V=d!==U.current.items,K=t({active:E,containerId:f,isDragging:L,isSorting:W,id:i,index:N,items:d,newIndex:U.current.newIndex,previousItems:U.current.items,previousContainerId:U.current.containerId,transition:u,wasDragging:U.current.activeId!=null}),Q=nft({disabled:!K,index:N,node:k,rect:_});return v.useEffect(()=>{W&&U.current.newIndex!==O&&(U.current.newIndex=O),f!==U.current.containerId&&(U.current.containerId=f),d!==U.current.items&&(U.current.items=d)},[W,O,f,d]),v.useEffect(()=>{if(q===U.current.activeId)return;if(q!=null&&U.current.activeId==null){U.current.activeId=q;return}const oe=setTimeout(()=>{U.current.activeId=q},50);return()=>clearTimeout(oe)},[q]),{active:E,activeIndex:h,attributes:A,data:S,rect:_,index:N,newIndex:O,items:d,isOver:T,isSorting:W,isDragging:L,listeners:z,node:k,overIndex:x,over:$,setNodeRef:B,setActivatorNodeRef:H,setDroppableNodeRef:I,setDraggableNodeRef:F,transform:Q??Y,transition:se()};function se(){if(Q||V&&U.current.newIndex===N)return eft;if(!(G&&!rT(D)||!u)&&(W||K))return Ki.Transition.toString({...u,property:whe})}}function rft(e,t){var n,r;return typeof e=="boolean"?{draggable:e,droppable:!1}:{draggable:(n=e==null?void 0:e.draggable)!=null?n:t.draggable,droppable:(r=e==null?void 0:e.droppable)!=null?r:t.droppable}}function ik(e){if(!e)return!1;const t=e.data.current;return!!(t&&"sortable"in t&&typeof t.sortable=="object"&&"containerId"in t.sortable&&"items"in t.sortable&&"index"in t.sortable)}const oft=[Fn.Down,Fn.Right,Fn.Up,Fn.Left],$z=(e,t)=>{let{context:{active:n,collisionRect:r,droppableRects:o,droppableContainers:s,over:i,scrollableAncestors:a}}=t;if(oft.includes(e.code)){if(e.preventDefault(),!n||!r)return;const c=[];s.getEnabled().forEach(f=>{if(!f||f!=null&&f.disabled)return;const h=o.get(f.id);if(h)switch(e.code){case Fn.Down:r.top<h.top&&c.push(f);break;case Fn.Up:r.top>h.top&&c.push(f);break;case Fn.Left:r.left>h.left&&c.push(f);break;case Fn.Right:r.left<h.left&&c.push(f);break}});const u=Put({collisionRect:r,droppableRects:o,droppableContainers:c});let d=Jfe(u,"id");if(d===(i==null?void 0:i.id)&&u.length>1&&(d=u[1].id),d!=null){const f=s.get(n.id),h=s.get(d),m=h?o.get(h.id):null,g=h==null?void 0:h.node.current;if(g&&m&&f&&h){const x=sT(g).some((j,_)=>a[_]!==j),y=Che(f,h),w=sft(f,h),C=x||!y?{x:0,y:0}:{x:w?r.width-m.width:0,y:w?r.height-m.height:0},N={x:m.left,y:m.top};return C.x&&C.y?N:uv(N,C)}}}};function Che(e,t){return!ik(e)||!ik(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function sft(e,t){return!ik(e)||!ik(t)||!Che(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function ift(e,t,n){const[r,o]=v.useState(null),[s,i]=v.useState(""),a=()=>{const g={id:`hierarchy_${Date.now()}`,label:s||"New Hierarchy",type:"static",steps:[],default:!1};t([...e,g]),i(""),o(g.id)},c=g=>{t(e.filter(b=>b.id!==g))},u=(g,b)=>{t(e.map(x=>x.id===g?{...x,...b}:x))};return{editingHierarchy:r,setEditingHierarchy:o,newHierarchyName:s,setNewHierarchyName:i,createNewHierarchy:a,deleteHierarchy:c,updateHierarchy:u,addStepToHierarchy:(g,b)=>{const x=n.find(C=>C.id===b);if(!x)return;const y={field:x,mode:"drillDown",label:`Drill to ${x.label}`,retainFilters:!0,preferredChartType:"bar"},w=e.find(C=>C.id===g);w&&u(g,{steps:[...w.steps,y]})},removeStepFromHierarchy:(g,b)=>{const x=e.find(y=>y.id===g);if(x){const y=[...x.steps];y.splice(b,1),u(g,{steps:y})}},updateStep:(g,b,x)=>{const y=e.find(w=>w.id===g);if(y){const w=y.steps.map((C,N)=>N===b?{...C,...x}:C);u(g,{steps:w})}},setDefaultHierarchy:g=>{t(e.map(b=>({...b,default:b.id===g})))}}}const JM="text-[13px] font-medium";function aft({step:e,hierarchyId:t,stepIndex:n,onUpdateStep:r,open:o,onOpenChange:s,trigger:i}){const a=v.useId();return l.jsxs(p.Popover,{open:o,onOpenChange:s,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:i}),l.jsx(p.PopoverContent,{className:"z-50 w-80 p-3",align:"start",children:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:JM,children:"Chart type"}),l.jsxs(p.Select,{value:e.preferredChartType||"bar",onValueChange:c=>{r(t,n,{preferredChartType:c})},children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"bar",children:"Bar chart"}),l.jsx(p.SelectItem,{value:"pie",children:"Pie chart"}),l.jsx(p.SelectItem,{value:"line",children:"Line chart"}),l.jsx(p.SelectItem,{value:"donut",children:"Donut chart"}),l.jsx(p.SelectItem,{value:"table",children:"Table"}),l.jsx(p.SelectItem,{value:"metric",children:"Metric"})]})]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:JM,children:"Step label"}),l.jsx(p.Input,{size:"sm",value:e.label||"",onChange:c=>r(t,n,{label:c.target.value}),placeholder:"Custom drill label"})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:JM,children:"Breadcrumb label template"}),l.jsx(p.Input,{size:"sm",value:e.breadcrumbLabelTemplate||"",onChange:c=>r(t,n,{breadcrumbLabelTemplate:c.target.value}),placeholder:"e.g., 'Region: {{value}}'"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Tn,{id:a,checked:e.retainFilters!==!1,onCheckedChange:c=>r(t,n,{retainFilters:c===!0})}),l.jsx(p.Label,{htmlFor:a,className:"cursor-pointer text-[13px] font-normal",children:"Retain filters when drilling"})]}),l.jsx("div",{className:"flex justify-end",children:l.jsx(p.Button,{size:"xs",variant:"outline",onClick:()=>s(!1),children:"Done"})})]})})]})}const lft="whitespace-nowrap rounded-[4px] border border-border/70 bg-muted/40 px-1 py-px font-mono text-[10px] text-muted-foreground";function cft({field:e,step:t,stepIndex:n,hierarchyId:r,onUpdateStep:o,onRemoveStep:s}){const[i,a]=v.useState(!1),{attributes:c,listeners:u,setNodeRef:d,transform:f,transition:h,isDragging:m}=tx({id:`${r}-${e.id}-${n}`,disabled:!1}),g={transform:Ki.Transform.toString(f),transition:h,opacity:m?.8:1,zIndex:m?1e3:1};return l.jsx("div",{ref:d,style:g,className:`relative ${i?"z-[9998]":""}`,...c,children:l.jsx(aft,{step:t,hierarchyId:r,stepIndex:n,onUpdateStep:o,open:i,onOpenChange:a,trigger:l.jsxs("div",{className:p.cn("flex h-7 cursor-pointer items-center gap-1.5 rounded-control border border-input bg-background px-2 transition-colors hover:bg-muted/60",m&&"border-ring"),...u,onClick:b=>{b.stopPropagation(),a(x=>!x)},children:[l.jsxs("div",{className:"pointer-events-none flex items-center gap-1.5",children:[l.jsx("span",{className:"whitespace-nowrap text-[12px] font-medium",children:e.label}),t.preferredChartType&&t.preferredChartType!=="bar"&&l.jsx("span",{className:lft,children:t.preferredChartType}),t.linkedInsightId&&l.jsx(aZ,{className:"h-3 w-3 text-muted-foreground","aria-label":"Linked insight"})]}),l.jsx("button",{type:"button","aria-label":`Remove ${e.label} from hierarchy`,className:"pointer-events-auto text-muted-foreground hover:text-destructive",onClick:b=>{b.stopPropagation(),s(r,n)},children:l.jsx(je.X,{className:"h-3 w-3"})})]})})})}function uft(e){return{sensors:oT(nb(Jb,{activationConstraint:{distance:5}}),nb(eC,{coordinateGetter:$z})),handleStepDragEnd:(r,o)=>{const{active:s,over:i}=r;if(!i||s.id===i.id)return;const a=s.id.replace(`${o.id}-`,""),c=i.id.replace(`${o.id}-`,""),u=o.steps.findIndex(f=>f.field.id===a),d=o.steps.findIndex(f=>f.field.id===c);if(u!==-1&&d!==-1&&u!==d){const f=ex(o.steps,u,d);e(o.id,{steps:f})}}}}function dft({hierarchy:e,onUpdateStep:t,onRemoveStep:n,onUpdateHierarchy:r}){const{sensors:o}=uft(r),[s,i]=v.useState(null),a=e.steps.filter(h=>h&&h.field&&h.field.id),u=a.map(h=>h.field).map((h,m)=>`${e.id}-${h.id}-${m}`),d=h=>{const m=h.active.id,g=Number.parseInt(m.split("-").pop()||"0"),b=a[g],x=b==null?void 0:b.field;i(x||null)},f=h=>{i(null);const{active:m,over:g}=h;if(!g||m.id===g.id)return;const b=Number.parseInt(m.id.split("-").pop()||"0"),x=Number.parseInt(g.id.split("-").pop()||"0");if(b!==x&&b<a.length&&x<a.length){const y=[...e.steps],[w]=y.splice(b,1);y.splice(x,0,w),r(e.id,{steps:y})}};return a.length===0?l.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:l.jsx("div",{className:"rounded-card border border-border/60 bg-muted/30 px-2.5 py-2 text-[12px] text-muted-foreground",children:"No drill steps configured. Add steps to create a drill hierarchy."})}):l.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:l.jsxs(nC,{sensors:o,collisionDetection:Jw,onDragStart:d,onDragEnd:f,children:[l.jsx(rC,{items:u,strategy:Oz,children:l.jsx("div",{className:"flex flex-wrap items-center gap-2",style:{minHeight:"40px"},children:a.map((h,m)=>{if(!h||!h.field||!h.field.id)return null;const g=[];m>0&&g.push(l.jsx(Ft.ChevronRight,{className:"pointer-events-none h-3.5 w-3.5 text-muted-foreground/70"},`arrow-${m}`));const b=m===0,x=m===a.length-1;return g.push(l.jsx(cft,{field:h.field,step:h,stepIndex:m,hierarchyId:e.id,onUpdateStep:t,onRemoveStep:n,isFirstField:b,isLastField:x},`field-${h.field.id}-${m}`)),g})})}),typeof window<"u"&&br.createPortal(l.jsx(Kb,{children:l.jsx(bhe,{style:{zIndex:9999},children:s?l.jsx("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-ring bg-background px-2",children:l.jsx("span",{className:"whitespace-nowrap text-[12px] font-medium",children:s.label})}):null})}),document.body)]})})}var YW=1,fft=.9,hft=.8,mft=.17,e2=.1,t2=.999,pft=.9999,gft=.99,bft=/[\\\/_+.#"@\[\(\{&]/,xft=/[\\\/_+.#"@\[\(\{&]/g,yft=/[\s-]/,She=/[\s-]/g;function SF(e,t,n,r,o,s,i){if(s===t.length)return o===e.length?YW:gft;var a=`${o},${s}`;if(i[a]!==void 0)return i[a];for(var c=r.charAt(s),u=n.indexOf(c,o),d=0,f,h,m,g;u>=0;)f=SF(e,t,n,r,u+1,s+1,i),f>d&&(u===o?f*=YW:bft.test(e.charAt(u-1))?(f*=hft,m=e.slice(o,u-1).match(xft),m&&o>0&&(f*=Math.pow(t2,m.length))):yft.test(e.charAt(u-1))?(f*=fft,g=e.slice(o,u-1).match(She),g&&o>0&&(f*=Math.pow(t2,g.length))):(f*=mft,o>0&&(f*=Math.pow(t2,u-o))),e.charAt(u)!==t.charAt(s)&&(f*=pft)),(f<e2&&n.charAt(u-1)===r.charAt(s+1)||r.charAt(s+1)===r.charAt(s)&&n.charAt(u-1)!==r.charAt(s))&&(h=SF(e,t,n,r,u+1,s+2,i),h*e2>f&&(f=h*e2)),f>d&&(d=f),u=n.indexOf(c,u+1);return i[a]=d,d}function ZW(e){return e.toLowerCase().replace(She," ")}function vft(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,SF(e,t,ZW(e),ZW(t),0,0,{})}var Hx='[cmdk-group=""]',n2='[cmdk-group-items=""]',wft='[cmdk-group-heading=""]',Nhe='[cmdk-item=""]',XW=`${Nhe}:not([aria-disabled="true"])`,NF="cmdk-item-select",Op="data-value",Cft=(e,t,n)=>vft(e,t,n),jhe=te.createContext(void 0),oC=()=>te.useContext(jhe),khe=te.createContext(void 0),zz=()=>te.useContext(khe),_he=te.createContext(void 0),Ihe=te.forwardRef((e,t)=>{let n=Lp(()=>{var W,P;return{search:"",value:(P=(W=e.value)!=null?W:e.defaultValue)!=null?P:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=Lp(()=>new Set),o=Lp(()=>new Map),s=Lp(()=>new Map),i=Lp(()=>new Set),a=The(e),{label:c,children:u,value:d,onValueChange:f,filter:h,shouldFilter:m,loop:g,disablePointerSelection:b=!1,vimBindings:x=!0,...y}=e,w=p.useId(),C=p.useId(),N=p.useId(),S=te.useRef(null),j=Rft();Im(()=>{if(d!==void 0){let W=d.trim();n.current.value=W,_.emit()}},[d]),Im(()=>{j(6,R)},[]);let _=te.useMemo(()=>({subscribe:W=>(i.current.add(W),()=>i.current.delete(W)),snapshot:()=>n.current,setState:(W,P,G)=>{var Z,X,Y,O;if(!Object.is(n.current[W],P)){if(n.current[W]=P,W==="search")D(),I(),j(1,E);else if(W==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let q=document.getElementById(N);q?q.focus():(Z=document.getElementById(w))==null||Z.focus()}if(j(7,()=>{var q;n.current.selectedItemId=(q=A())==null?void 0:q.id,_.emit()}),G||j(5,R),((X=a.current)==null?void 0:X.value)!==void 0){let q=P??"";(O=(Y=a.current).onValueChange)==null||O.call(Y,q);return}}_.emit()}},emit:()=>{i.current.forEach(W=>W())}}),[]),k=te.useMemo(()=>({value:(W,P,G)=>{var Z;P!==((Z=s.current.get(W))==null?void 0:Z.value)&&(s.current.set(W,{value:P,keywords:G}),n.current.filtered.items.set(W,T(P,G)),j(2,()=>{I(),_.emit()}))},item:(W,P)=>(r.current.add(W),P&&(o.current.has(P)?o.current.get(P).add(W):o.current.set(P,new Set([W]))),j(3,()=>{D(),I(),n.current.value||E(),_.emit()}),()=>{s.current.delete(W),r.current.delete(W),n.current.filtered.items.delete(W);let G=A();j(4,()=>{D(),(G==null?void 0:G.getAttribute("id"))===W&&E(),_.emit()})}),group:W=>(o.current.has(W)||o.current.set(W,new Set),()=>{s.current.delete(W),o.current.delete(W)}),filter:()=>a.current.shouldFilter,label:c||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:w,inputId:N,labelId:C,listInnerRef:S}),[]);function T(W,P){var G,Z;let X=(Z=(G=a.current)==null?void 0:G.filter)!=null?Z:Cft;return W?X(W,n.current.search,P):0}function I(){if(!n.current.search||a.current.shouldFilter===!1)return;let W=n.current.filtered.items,P=[];n.current.filtered.groups.forEach(Z=>{let X=o.current.get(Z),Y=0;X.forEach(O=>{let q=W.get(O);Y=Math.max(q,Y)}),P.push([Z,Y])});let G=S.current;F().sort((Z,X)=>{var Y,O;let q=Z.getAttribute("id"),U=X.getAttribute("id");return((Y=W.get(U))!=null?Y:0)-((O=W.get(q))!=null?O:0)}).forEach(Z=>{let X=Z.closest(n2);X?X.appendChild(Z.parentElement===X?Z:Z.closest(`${n2} > *`)):G.appendChild(Z.parentElement===G?Z:Z.closest(`${n2} > *`))}),P.sort((Z,X)=>X[1]-Z[1]).forEach(Z=>{var X;let Y=(X=S.current)==null?void 0:X.querySelector(`${Hx}[${Op}="${encodeURIComponent(Z[0])}"]`);Y==null||Y.parentElement.appendChild(Y)})}function E(){let W=F().find(G=>G.getAttribute("aria-disabled")!=="true"),P=W==null?void 0:W.getAttribute(Op);_.setState("value",P||void 0)}function D(){var W,P,G,Z;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let X=0;for(let Y of r.current){let O=(P=(W=s.current.get(Y))==null?void 0:W.value)!=null?P:"",q=(Z=(G=s.current.get(Y))==null?void 0:G.keywords)!=null?Z:[],U=T(O,q);n.current.filtered.items.set(Y,U),U>0&&X++}for(let[Y,O]of o.current)for(let q of O)if(n.current.filtered.items.get(q)>0){n.current.filtered.groups.add(Y);break}n.current.filtered.count=X}function R(){var W,P,G;let Z=A();Z&&(((W=Z.parentElement)==null?void 0:W.firstChild)===Z&&((G=(P=Z.closest(Hx))==null?void 0:P.querySelector(wft))==null||G.scrollIntoView({block:"nearest"})),Z.scrollIntoView({block:"nearest"}))}function A(){var W;return(W=S.current)==null?void 0:W.querySelector(`${Nhe}[aria-selected="true"]`)}function F(){var W;return Array.from(((W=S.current)==null?void 0:W.querySelectorAll(XW))||[])}function z(W){let P=F()[W];P&&_.setState("value",P.getAttribute(Op))}function L(W){var P;let G=A(),Z=F(),X=Z.findIndex(O=>O===G),Y=Z[X+W];(P=a.current)!=null&&P.loop&&(Y=X+W<0?Z[Z.length-1]:X+W===Z.length?Z[0]:Z[X+W]),Y&&_.setState("value",Y.getAttribute(Op))}function $(W){let P=A(),G=P==null?void 0:P.closest(Hx),Z;for(;G&&!Z;)G=W>0?Dft(G,Hx):Mft(G,Hx),Z=G==null?void 0:G.querySelector(XW);Z?_.setState("value",Z.getAttribute(Op)):L(W)}let H=()=>z(F().length-1),M=W=>{W.preventDefault(),W.metaKey?H():W.altKey?$(1):L(1)},B=W=>{W.preventDefault(),W.metaKey?z(0):W.altKey?$(-1):L(-1)};return te.createElement(p.Primitive.div,{ref:t,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:W=>{var P;(P=y.onKeyDown)==null||P.call(y,W);let G=W.nativeEvent.isComposing||W.keyCode===229;if(!(W.defaultPrevented||G))switch(W.key){case"n":case"j":{x&&W.ctrlKey&&M(W);break}case"ArrowDown":{M(W);break}case"p":case"k":{x&&W.ctrlKey&&B(W);break}case"ArrowUp":{B(W);break}case"Home":{W.preventDefault(),z(0);break}case"End":{W.preventDefault(),H();break}case"Enter":{W.preventDefault();let Z=A();if(Z){let X=new Event(NF);Z.dispatchEvent(X)}}}}},te.createElement("label",{"cmdk-label":"",htmlFor:k.inputId,id:k.labelId,style:Pft},c),lT(e,W=>te.createElement(khe.Provider,{value:_},te.createElement(jhe.Provider,{value:k},W))))}),Sft=te.forwardRef((e,t)=>{var n,r;let o=p.useId(),s=te.useRef(null),i=te.useContext(_he),a=oC(),c=The(e),u=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;Im(()=>{if(!u)return a.item(o,i==null?void 0:i.id)},[u]);let d=Ehe(o,s,[e.value,e.children,s],e.keywords),f=zz(),h=nf(j=>j.value&&j.value===d.current),m=nf(j=>u||a.filter()===!1?!0:j.search?j.filtered.items.get(o)>0:!0);te.useEffect(()=>{let j=s.current;if(!(!j||e.disabled))return j.addEventListener(NF,g),()=>j.removeEventListener(NF,g)},[m,e.onSelect,e.disabled]);function g(){var j,_;b(),(_=(j=c.current).onSelect)==null||_.call(j,d.current)}function b(){f.setState("value",d.current,!0)}if(!m)return null;let{disabled:x,value:y,onSelect:w,forceMount:C,keywords:N,...S}=e;return te.createElement(p.Primitive.div,{ref:p.composeRefs(s,t),...S,id:o,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!h,"data-disabled":!!x,"data-selected":!!h,onPointerMove:x||a.getDisablePointerSelection()?void 0:b,onClick:x?void 0:g},e.children)}),Nft=te.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:o,...s}=e,i=p.useId(),a=te.useRef(null),c=te.useRef(null),u=p.useId(),d=oC(),f=nf(m=>o||d.filter()===!1?!0:m.search?m.filtered.groups.has(i):!0);Im(()=>d.group(i),[]),Ehe(i,a,[e.value,e.heading,c]);let h=te.useMemo(()=>({id:i,forceMount:o}),[o]);return te.createElement(p.Primitive.div,{ref:p.composeRefs(a,t),...s,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&te.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:u},n),lT(e,m=>te.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?u:void 0},te.createElement(_he.Provider,{value:h},m))))}),jft=te.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,o=te.useRef(null),s=nf(i=>!i.search);return!n&&!s?null:te.createElement(p.Primitive.div,{ref:p.composeRefs(o,t),...r,"cmdk-separator":"",role:"separator"})}),kft=te.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,o=e.value!=null,s=zz(),i=nf(u=>u.search),a=nf(u=>u.selectedItemId),c=oC();return te.useEffect(()=>{e.value!=null&&s.setState("search",e.value)},[e.value]),te.createElement(p.Primitive.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":a,id:c.inputId,type:"text",value:o?e.value:i,onChange:u=>{o||s.setState("search",u.target.value),n==null||n(u.target.value)}})}),_ft=te.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...o}=e,s=te.useRef(null),i=te.useRef(null),a=nf(u=>u.selectedItemId),c=oC();return te.useEffect(()=>{if(i.current&&s.current){let u=i.current,d=s.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=u.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return h.observe(u),()=>{cancelAnimationFrame(f),h.unobserve(u)}}},[]),te.createElement(p.Primitive.div,{ref:p.composeRefs(s,t),...o,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:c.listId},lT(e,u=>te.createElement("div",{ref:p.composeRefs(i,c.listInnerRef),"cmdk-list-sizer":""},u)))}),Ift=te.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:o,contentClassName:s,container:i,...a}=e;return te.createElement(Hk,{open:n,onOpenChange:r},te.createElement(qk,{container:i},te.createElement(db,{"cmdk-overlay":"",className:o}),te.createElement(fb,{"aria-label":e.label,"cmdk-dialog":"",className:s},te.createElement(Ihe,{ref:t,...a}))))}),Tft=te.forwardRef((e,t)=>nf(n=>n.filtered.count===0)?te.createElement(p.Primitive.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),Eft=te.forwardRef((e,t)=>{let{progress:n,children:r,label:o="Loading...",...s}=e;return te.createElement(p.Primitive.div,{ref:t,...s,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":o},lT(e,i=>te.createElement("div",{"aria-hidden":!0},i)))}),ri=Object.assign(Ihe,{List:_ft,Item:Sft,Input:kft,Group:Nft,Separator:jft,Dialog:Ift,Empty:Tft,Loading:Eft});function Dft(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function Mft(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function The(e){let t=te.useRef(e);return Im(()=>{t.current=e}),t}var Im=typeof window>"u"?te.useEffect:te.useLayoutEffect;function Lp(e){let t=te.useRef();return t.current===void 0&&(t.current=e()),t}function nf(e){let t=zz(),n=()=>e(t.snapshot());return te.useSyncExternalStore(t.subscribe,n,n)}function Ehe(e,t,n,r=[]){let o=te.useRef(),s=oC();return Im(()=>{var i;let a=(()=>{var u;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(u=d.current.textContent)==null?void 0:u.trim():o.current}})(),c=r.map(u=>u.trim());s.value(e,a,c),(i=t.current)==null||i.setAttribute(Op,a),o.current=a}),o}var Rft=()=>{let[e,t]=te.useState(),n=Lp(()=>new Map);return Im(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,o)=>{n.current.set(r,o),t({})}};function Aft(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function lT({asChild:e,children:t},n){return e&&te.isValidElement(t)?te.cloneElement(Aft(t),{ref:t.ref},n(t.props.children)):n(t)}var Pft={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const cT=te.forwardRef(({className:e,...t},n)=>l.jsx(ri,{ref:n,className:p.cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));cT.displayName=ri.displayName;const Bz=te.forwardRef(({className:e,...t},n)=>l.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[l.jsx(Ft.Search,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),l.jsx(ri.Input,{ref:n,className:p.cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-[hsl(var(--semaphor-placeholder-foreground))] disabled:cursor-not-allowed disabled:opacity-50",e),...t})]}));Bz.displayName=ri.Input.displayName;const uT=te.forwardRef(({className:e,...t},n)=>l.jsx(ri.List,{ref:n,className:p.cn("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));uT.displayName=ri.List.displayName;const dT=te.forwardRef((e,t)=>l.jsx(ri.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));dT.displayName=ri.Empty.displayName;const fT=te.forwardRef(({className:e,...t},n)=>l.jsx(ri.Group,{ref:n,className:p.cn("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",e),...t}));fT.displayName=ri.Group.displayName;const Dhe=te.forwardRef(({className:e,...t},n)=>l.jsx(ri.Separator,{ref:n,className:p.cn("-mx-1 h-px bg-border",e),...t}));Dhe.displayName=ri.Separator.displayName;const hT=te.forwardRef(({className:e,...t},n)=>l.jsx(ri.Item,{ref:n,className:p.cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",e),...t}));hT.displayName=ri.Item.displayName;const Fft=["[&_[cmdk-input-wrapper]]:px-2","[&_[cmdk-input-wrapper]_svg]:h-3.5","[&_[cmdk-input-wrapper]_svg]:w-3.5","[&_[cmdk-input]]:h-8","[&_[cmdk-input]]:py-0","[&_[cmdk-input]]:text-[13px]","[&_[cmdk-item]]:rounded-control","[&_[cmdk-item]]:px-2","[&_[cmdk-item]]:py-1.5","[&_[cmdk-item]]:text-[13px]","[&_[cmdk-empty]]:py-4","[&_[cmdk-empty]]:text-[12px]","[&_[cmdk-empty]]:text-muted-foreground"].join(" ");function Oft({hierarchy:e,sampleFieldReferences:t,onUpdateHierarchy:n,onDeleteHierarchy:r,onUpdateStep:o,onRemoveStep:s,onAddStep:i}){const[a,c]=v.useState(!1),{attributes:u,listeners:d,setNodeRef:f,transform:h,transition:m}=tx({id:e.id,disabled:!1}),g={transform:Ki.Transform.toString(h),transition:m},b=e.steps.filter(x=>x.field).map(x=>x.field.id);return l.jsxs("div",{ref:f,style:g,className:"hierarchy-container relative rounded-card border border-border bg-background p-3 transition-colors hover:border-border/80",children:[l.jsxs("div",{className:"mb-3 flex cursor-move items-center justify-between",...u,...d,children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("div",{onPointerDown:x=>x.stopPropagation(),onClick:x=>x.stopPropagation(),onKeyDown:x=>x.stopPropagation(),children:l.jsx(xi,{value:e.label||"",onSave:x=>{n(e.id,{label:x})},placeholder:"Hierarchy name",displayClassName:"text-[13px] font-medium",inputClassName:"text-[13px] font-medium"})})}),l.jsx("div",{className:"flex items-center gap-1",children:l.jsx(p.Button,{size:"xs",variant:"ghost","aria-label":"Delete hierarchy",className:"h-7 w-7 p-0 text-muted-foreground hover:text-destructive",onClick:x=>{x.stopPropagation(),r(e.id)},onPointerDown:x=>x.stopPropagation(),children:l.jsx(el,{className:"h-3.5 w-3.5"})})})]}),l.jsx(dft,{hierarchy:e,onUpdateStep:o,onRemoveStep:s,onUpdateHierarchy:n}),l.jsx("div",{className:"mt-3 border-t border-border/60 pt-3","data-hierarchy-editing":!0,children:a?l.jsxs(cT,{className:p.cn("rounded-card border border-border",Fft),children:[l.jsx(Bz,{placeholder:"Search fields…"}),l.jsxs(uT,{className:"max-h-40",children:[l.jsx(dT,{children:"No field found."}),l.jsx(fT,{children:t.filter(x=>!b.includes(x.id)).map(x=>l.jsx(hT,{value:x.label,onSelect:()=>{i(e.id,x.id),c(!1)},children:x.label},x.id))})]})]}):l.jsxs(p.Button,{type:"button",variant:"outline",size:"xs",onClick:x=>{x.preventDefault(),x.stopPropagation(),c(!0)},children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Add step"]})})]})}function Lft({open:e,onOpenChange:t,drillHierarchies:n,onUpdateHierarchies:r,availableFields:o}){const[s,i]=v.useState(n);v.useEffect(()=>{e&&i(n)},[e,n]);const a=v.useMemo(()=>o.filter(w=>p.getDataType(w.dataType)==="string"),[o]),c=oT(nb(Jb),nb(eC,{coordinateGetter:$z})),{createNewHierarchy:u,deleteHierarchy:d,updateHierarchy:f,addStepToHierarchy:h,removeStepFromHierarchy:m,updateStep:g,setDefaultHierarchy:b}=ift(s,i,a),x=w=>{const{active:C,over:N}=w;if(C.id!==(N==null?void 0:N.id)){const S=s.findIndex(_=>_.id===C.id),j=s.findIndex(_=>_.id===(N==null?void 0:N.id));i(ex(s,S,j))}},y=w=>{w||r(s),t(w)};return l.jsx(Mo,{modal:!0,open:e,onOpenChange:y,children:l.jsx(go,{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden p-0",onInteractOutside:w=>w.preventDefault(),onEscapeKeyDown:w=>w.preventDefault(),children:l.jsx(p.FocusScope,{trapped:!1,children:l.jsxs("div",{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden",children:[l.jsxs(Is,{className:"space-y-1 border-b border-border px-5 pb-3.5 pt-4 text-left",children:[l.jsx(bo,{className:"text-[15px] font-semibold tracking-tight",children:"Manage drill hierarchies"}),l.jsx(Ro,{className:"text-[12px] leading-[1.5] text-muted-foreground",children:"Create multiple drill paths for different analysis scenarios."})]}),l.jsx(p.ScrollArea,{className:"flex-1 px-5",children:l.jsxs("div",{className:"space-y-4 py-4",children:[s.length>0&&l.jsx("div",{className:"flex justify-end",children:l.jsxs(p.Button,{type:"button",size:"xs",onClick:w=>{w.preventDefault(),w.stopPropagation(),u()},children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Add hierarchy"]})}),s.length>0?l.jsx(nC,{sensors:c,collisionDetection:Jw,onDragEnd:x,children:l.jsx(rC,{items:s.map(w=>w.id),strategy:Lz,children:l.jsx("div",{className:"space-y-4",children:s.map(w=>l.jsx(Oft,{hierarchy:w,sampleFieldReferences:a,onUpdateHierarchy:f,onDeleteHierarchy:d,onSetDefaultHierarchy:b,onUpdateStep:g,onRemoveStep:m,onAddStep:h},w.id))})})}):l.jsxs("div",{className:"flex flex-col items-center gap-3 py-16 text-center",children:[l.jsx(Pm,{className:"h-8 w-8 text-muted-foreground/40",strokeWidth:1.5}),l.jsxs("div",{className:"max-w-[360px] space-y-1",children:[l.jsx("p",{className:"text-[14px] font-medium",children:"No hierarchies yet"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Create your first hierarchy to enable drill-down interactions."})]}),l.jsxs(p.Button,{type:"button",size:"xs",variant:"outline",onClick:w=>{w.preventDefault(),w.stopPropagation(),u()},children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Create hierarchy"]})]})]})}),l.jsx("div",{className:"flex justify-end gap-1.5 border-t border-border px-5 py-3",children:l.jsx(p.Button,{size:"xs",onClick:()=>y(!1),children:"Done"})})]})})})})}const $ft="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function QW({hierarchy:e,selected:t,path:n,onSelect:r}){return l.jsxs("button",{type:"button",onClick:()=>r(e.id),className:p.cn("flex w-full flex-col items-start gap-0.5 rounded-control px-2 py-1.5 text-left transition-colors hover:bg-muted/60",t&&"bg-accent"),children:[l.jsx("span",{className:"w-full truncate text-[13px] font-medium",children:e.label||"Unnamed hierarchy"}),l.jsx("span",{className:"w-full truncate text-[12px] text-muted-foreground",children:n})]})}function zft({interaction:e,onUpdate:t,card:n,availableFields:r,onUpdateHierarchies:o,onManageHierarchies:s}){var E;const[i,a]=v.useState(!1),[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,m]=v.useState(!1),[g,b]=v.useState({}),x=v.useMemo(()=>{var D;return((D=n.interactionConfig)==null?void 0:D.drillHierarchies)||[]},[(E=n.interactionConfig)==null?void 0:E.drillHierarchies]),y=v.useMemo(()=>{var F,z;const D=[],R=e.trigger;if(!R)return D;let A;if(R.type==="attribute"){const L=r.find(H=>H.id===R.field.id);L&&(L.dataType==="date"||L.dataType==="timestamp")&&(A=L)}else if(R.type==="metric"){const L=(z=(F=n.config)==null?void 0:F.groupByColumns)==null?void 0:z.find($=>$.dataType==="date"||$.dataType==="timestamp");L&&(A=L)}if(A&&p.shouldAutoGenerateDateHierarchy(A,x)){const L=p.generateDateHierarchy(A);D.push(L)}return D},[r,x,e.trigger,n.config]),w=v.useMemo(()=>[...x,...y],[x,y]),C=w.find(D=>D.id===e.hierarchyId);te.useEffect(()=>{i&&C&&C.type==="date"?f(C.id):i||f(null)},[i,C]);const N=D=>{if(y.some(A=>A.id===D)&&o){const A=y.find(F=>F.id===D);A&&o([...x,A])}t({...e,hierarchyId:D}),a(!1)},S=()=>{a(!1),u(!0),s&&s()},j=D=>{o&&o(D)},_=D=>D.steps.map(A=>A.field.label||A.field.name).join(" → "),k=D=>D&&D.charAt(0).toUpperCase()+D.slice(1),T=(D,R,A)=>{var M,B;const F=(M=D.steps[R])==null?void 0:M.field;if(!(F!=null&&F.granularity))return;const z=qc.getTemporalBucketAuthoringOptions(F.granularity).find(W=>W.value==="custom"),L=g[R]||(((B=z==null?void 0:z.format)==null?void 0:B.presentation.mode)==="pattern"?z.format.presentation.pattern:"");b(W=>{const P={...W};return A==="custom"?P[R]=L:delete P[R],P});const $=[...D.steps];$[R]={...$[R],field:{...$[R].field,format:qc.resolveTemporalBucketAuthoringFormat(F.granularity,A,L),dateFormat:void 0,customFormat:void 0}};const H={...D,steps:$};if(o){const W=x.findIndex(P=>P.id===D.id);if(W>=0){const P=[...x];P[W]=H,o(P)}else o([...x,H])}},I=(D,R,A)=>{var $;b(H=>({...H,[R]:A}));const F=($=D.steps[R])==null?void 0:$.field;if(!(F!=null&&F.granularity))return;const z=[...D.steps];z[R]={...z[R],field:{...z[R].field,format:qc.resolveTemporalBucketAuthoringFormat(F.granularity,"custom",A),dateFormat:void 0,customFormat:void 0}};const L={...D,steps:z};if(o){const H=x.findIndex(M=>M.id===D.id);if(H>=0){const M=[...x];M[H]=L,o(M)}else o([...x,L])}};return l.jsxs("div",{className:"space-y-4",children:[l.jsx(Ys,{label:"Choose hierarchy",description:"Select which hierarchy to drill through when this interaction triggers",children:w.length>0?l.jsxs(l.Fragment,{children:[l.jsxs(p.Popover,{open:i,onOpenChange:a,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsxs(p.Button,{variant:"outline",role:"combobox",className:"h-auto w-full justify-between px-2.5 py-1.5",children:[l.jsx("div",{className:"flex min-w-0 flex-1 flex-col items-start gap-0.5 text-left",children:C?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"w-full truncate text-[13px] font-medium",children:C.label||"Unnamed hierarchy"}),l.jsx("span",{className:"w-full truncate text-[12px] font-normal text-muted-foreground",children:_(C)})]}):l.jsx("span",{className:"text-[13px] font-normal text-muted-foreground",children:"Select hierarchy…"})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[C&&C.type==="date"&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Customize date formats",className:"inline-flex h-6 w-6 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:D=>{D.stopPropagation(),m(!h)},onKeyDown:D=>{D.key!=="Enter"&&D.key!==" "||(D.preventDefault(),D.stopPropagation(),m(!h))},children:l.jsx(EO,{className:"h-3.5 w-3.5"})}),l.jsx(Ft.ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]})]})}),l.jsxs(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:[l.jsxs("div",{className:"flex h-10 items-center justify-between gap-2 border-b border-border px-3",children:[l.jsx("span",{className:"text-[13px] font-medium",children:"Select hierarchy"}),l.jsxs(p.Button,{variant:"ghost",size:"xs",onClick:S,children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Create new"]})]}),l.jsxs("div",{className:"p-1.5",children:[y.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-2 pb-1 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Auto-generated"}),y.map(D=>l.jsx(QW,{hierarchy:D,selected:e.hierarchyId===D.id,path:_(D),onSelect:N},D.id))]}),x.length>0&&l.jsxs(l.Fragment,{children:[y.length>0&&l.jsx("div",{className:"my-1.5 border-t border-border/60"}),x.map(D=>l.jsx(QW,{hierarchy:D,selected:e.hierarchyId===D.id,path:_(D),onSelect:N},D.id))]})]})]})]}),C&&C.type==="date"&&h&&l.jsxs("div",{className:"mt-3 space-y-3 rounded-card border border-border/60 p-3",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Customize date formats"}),l.jsx(p.Button,{variant:"ghost",size:"xs",className:"h-6",onClick:()=>m(!1),children:"Close"})]}),C.steps.map((D,R)=>{const A=D.field.granularity;if(!A)return null;const F=p.readTemporalBucketAuthoringSelection({fieldId:D.field.id,dataType:D.field.dataType,granularity:A,format:D.field.format,dateFormat:D.field.dateFormat,customFormat:D.field.customFormat,semanticTemporalPresentation:D.field.semanticTemporalPresentation}),z=qc.getTemporalBucketAuthoringOptions(A,F.format),L=g[R]!==void 0?"custom":F.value;return l.jsxs("div",{className:"space-y-1",children:[l.jsx(p.Label,{className:$ft,children:D.field.label||k(A)}),l.jsxs(p.Select,{value:L,onValueChange:$=>{T(C,R,$)},children:[l.jsx(p.SelectTrigger,{size:"xs",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:z.map($=>l.jsx(p.SelectItem,{value:$.value,className:"text-[12px]",children:$.label},$.value))})]}),L==="custom"&&l.jsxs("div",{className:"mt-2 space-y-1",children:[l.jsx(p.Input,{size:"xs",placeholder:"Enter custom format (e.g., YYYY-MM-DD)",value:g[R]??F.customPattern??"",onChange:$=>{I(C,R,$.target.value)}}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Common tokens: YYYY (year), MM (month), DD (day), HH (hour), mm (minute)"})]})]},R)})]})]}):l.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[l.jsx(Pm,{className:"h-8 w-8 text-muted-foreground/40",strokeWidth:1.5}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-[13px] font-medium",children:"No hierarchies yet"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Create one to define your drill path."})]}),l.jsxs(p.Button,{variant:"outline",size:"xs",onClick:S,children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Create hierarchy"]})]})}),l.jsx(Lft,{open:c,onOpenChange:u,drillHierarchies:x,onUpdateHierarchies:j,availableFields:r})]})}function Bft({fields:e,selectedFieldIds:t,onSelectionChange:n,searchPlaceholder:r="Search fields…",className:o=""}){const[s,i]=v.useState(""),a=e.filter(d=>d.label.toLowerCase().includes(s.toLowerCase())||d.qualifiedEntityName&&d.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),c=()=>{const d=[...new Set([...t,...a.map(f=>f.id)])];n(d)},u=()=>{const d=a.map(f=>f.id);n(t.filter(f=>!d.includes(f)))};return l.jsxs("div",{className:p.cn("space-y-2",o),children:[l.jsx(p.Input,{size:"sm",placeholder:r,value:s,onChange:d=>i(d.target.value)}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Button,{size:"xs",variant:"ghost",onClick:c,children:"Select all"}),l.jsx(p.Button,{size:"xs",variant:"ghost",onClick:u,children:"Clear"}),l.jsxs("span",{className:"ml-auto text-[11px] tabular-nums text-muted-foreground",children:[t.length," of ",e.length," selected"]})]}),l.jsx("div",{className:"grid max-h-32 grid-cols-2 overflow-y-auto rounded-card border border-border/60",children:a.map(d=>l.jsxs("label",{className:"flex cursor-pointer items-center gap-2 px-2 py-1.5 text-[12px] transition-colors hover:bg-muted/50",children:[l.jsx(Tn,{checked:t.includes(d.id),onCheckedChange:f=>{n(f?[...t,d.id]:t.filter(h=>h!==d.id))}}),l.jsx("span",{className:"truncate",children:d.label})]},d.id))}),s&&a.length===0&&l.jsxs("div",{className:"py-4 text-center text-[12px] text-muted-foreground",children:['No fields found matching "',s,'"']})]})}const Vft=e=>["string","boolean"].includes(p.getDataType(e.dataType));function Hft({interaction:e,availableFields:t,onUpdate:n}){var i;const r=t.filter(Vft),o=((i=e.availableFields)==null?void 0:i.map(a=>a.id))||[],s=a=>{const c=r.filter(u=>a.includes(u.id));n({...e,availableFields:c})};return l.jsx("div",{className:"space-y-4",children:l.jsxs(Ys,{label:"Available dimensions",description:"Choose which fields users can explore dynamically",children:[l.jsx(Bft,{fields:r,selectedFieldIds:o,onSelectionChange:s,searchPlaceholder:"Search fields…"}),o.length===0&&l.jsxs("p",{className:"flex items-center gap-1.5 text-[12px] text-muted-foreground",children:[l.jsx(Ca,{className:"h-3.5 w-3.5 shrink-0"}),"Select at least one field to finish this interaction"]})]})})}function qft({value:e,onChange:t}){const[n,r]=v.useState(!1),[o,s]=v.useState(""),[i,a]=v.useState("all"),{currentUser:c}=ti(),{data:u,isLoading:d}=UO(lo.DASHBOARD,o),f=(u==null?void 0:u.dashboards)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(c==null?void 0:c.id):!0),m=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),s("")};return l.jsxs(p.Popover,{open:n,onOpenChange:r,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsx(p.Button,{variant:"outline",size:"sm",className:p.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:m?l.jsx("span",{className:"truncate",children:m.title}):"Choose dashboard…"})}),l.jsx(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:l.jsxs(p.Tabs,{value:i,onValueChange:b=>a(b),children:[l.jsx("div",{className:"border-b border-border p-2",children:l.jsxs("div",{className:"relative",children:[l.jsx(Ft.Search,{className:"absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),l.jsx(p.Input,{size:"sm",placeholder:"Search all dashboards…",value:o,onChange:b=>s(b.target.value),className:"pl-7"})]})}),l.jsxs(p.TabsList,{variant:"underline",className:"px-3",children:[l.jsx(p.TabsTrigger,{variant:"underline",value:"me",children:"Created by me"}),l.jsx(p.TabsTrigger,{variant:"underline",value:"all",children:"All"})]}),l.jsx(p.TabsContent,{value:i,className:"mt-0",children:l.jsx(p.ScrollArea,{className:"h-[300px]",children:d?l.jsx("div",{className:"p-8 text-center text-[13px] text-muted-foreground",children:"Loading dashboards…"}):h.length===0?l.jsx("div",{className:"p-8 text-center text-[13px] text-muted-foreground",children:o?`No dashboards found matching "${o}"`:i==="me"?"No dashboards created by you":"No dashboards available"}):l.jsx("div",{className:"p-1.5",children:h.map(b=>l.jsxs("button",{onClick:()=>g(b),className:p.cn("flex w-full items-start gap-2 rounded-control px-2 py-1.5 text-left transition-colors hover:bg-muted/60",e===b.id&&"bg-accent"),children:[l.jsx(em,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[13px] font-medium",children:b.title}),l.jsx("div",{className:"mt-0.5 text-[11px] uppercase tracking-[0.04em] text-muted-foreground",children:Uft(b.createdAt)})]})]},b.id))})})})]})})]})}function Uft(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear()){const i=t.getHours(),a=t.getMinutes(),c=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${c}`}const o=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),s=t.getDate();return`${o} ${s}`}const Wft=[{value:"interactionFilters",label:"Interaction filters",description:"Pass only the clicked element as a filter"},{value:"full",label:"All filters",description:"Pass current dashboard filters + clicked element"},{value:"none",label:"None",description:"Navigate without passing any filters"}];function Kft({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs(Ys,{label:"Target dashboard",description:"Select which dashboard to navigate to when this interaction triggers",children:[l.jsx(qft,{value:e.targetDashboardId,onChange:(n,r)=>{const o={...e,targetDashboardId:n};!e.label&&r&&(o.label=r),t(o)}}),!e.targetDashboardId&&l.jsxs("p",{className:"flex items-center gap-1.5 text-[12px] text-muted-foreground",children:[l.jsx(Ca,{className:"h-3.5 w-3.5 shrink-0"}),"Select a target dashboard to finish this interaction"]})]}),l.jsx(Ys,{label:"Propagate filters",description:"Choose what filters to pass to the target dashboard",children:l.jsxs(p.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsxs(p.SelectValue,{placeholder:"Choose context mode…",children:[e.contextMode==="interactionFilters"&&"Interaction filters",(e.contextMode==="full"||!e.contextMode)&&"All filters",e.contextMode==="none"&&"None"]})}),l.jsx(p.SelectContent,{children:Wft.map(n=>l.jsx(p.SelectItem,{value:n.value,className:lv,children:l.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-[13px] font-medium leading-[1.35]",children:n.label}),l.jsx("span",{className:"text-[12px] leading-[1.35] text-muted-foreground",children:n.description})]})},n.value))})]})}),l.jsx(Ys,{label:"Menu label",description:"How this interaction appears when multiple actions are available",children:l.jsx(p.Input,{size:"sm",value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:op(e.mode)})})]})}function Gft({value:e,onChange:t}){const[n,r]=v.useState(!1),[o,s]=v.useState(""),[i,a]=v.useState("all"),{currentUser:c}=ti(),{data:u,isLoading:d}=UO(lo.VISUAL,o),f=(u==null?void 0:u.visuals)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(c==null?void 0:c.id):!0),m=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),s("")};return l.jsxs(p.Popover,{open:n,onOpenChange:r,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsx(p.Button,{variant:"outline",size:"sm",className:p.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:m?l.jsx("span",{className:"truncate",children:m.title}):"Choose insight…"})}),l.jsx(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:l.jsxs(p.Tabs,{value:i,onValueChange:b=>a(b),children:[l.jsx("div",{className:"border-b border-border p-2",children:l.jsxs("div",{className:"relative",children:[l.jsx(Ft.Search,{className:"absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),l.jsx(p.Input,{size:"sm",placeholder:"Search all insights…",value:o,onChange:b=>s(b.target.value),className:"pl-7"})]})}),l.jsxs(p.TabsList,{variant:"underline",className:"px-3",children:[l.jsx(p.TabsTrigger,{variant:"underline",value:"me",children:"Created by me"}),l.jsx(p.TabsTrigger,{variant:"underline",value:"all",children:"All"})]}),l.jsx(p.TabsContent,{value:i,className:"mt-0",children:l.jsx(p.ScrollArea,{className:"h-[300px]",children:d?l.jsx("div",{className:"p-8 text-center text-[13px] text-muted-foreground",children:"Loading insights…"}):h.length===0?l.jsx("div",{className:"p-8 text-center text-[13px] text-muted-foreground",children:o?`No insights found matching "${o}"`:i==="me"?"No insights created by you":"No insights available"}):l.jsx("div",{className:"p-1.5",children:h.map(b=>l.jsxs("button",{onClick:()=>g(b),className:p.cn("flex w-full items-start gap-2 rounded-control px-2 py-1.5 text-left transition-colors hover:bg-muted/60",e===b.id&&"bg-accent"),children:[l.jsx(p.ChartColumn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[13px] font-medium",children:b.title}),l.jsx("div",{className:"mt-0.5 text-[11px] uppercase tracking-[0.04em] text-muted-foreground",children:Yft(b.createdAt)})]})]},b.id))})})})]})})]})}function Yft(e){const t=new Date(e),n=new Date;if(t.getDate()===n.getDate()&&t.getMonth()===n.getMonth()&&t.getFullYear()===n.getFullYear()){const i=t.getHours(),a=t.getMinutes(),c=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${c}`}const o=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),s=t.getDate();return`${o} ${s}`}const Zft=[{value:"interactionFilters",label:"Interaction filters",description:"Pass only the clicked element as a filter"},{value:"full",label:"All filters",description:"Pass all current filters and selections"},{value:"none",label:"None",description:"Open insight without any filters"}];function Xft({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs(Ys,{label:"Target insight",description:"Select the saved insight to navigate to",children:[l.jsx(Gft,{value:e.targetInsightId,onChange:(n,r)=>{const o={...e,targetInsightId:n};!e.label&&r&&(o.label=r),t(o)}}),!e.targetInsightId&&l.jsxs("p",{className:"flex items-center gap-1.5 text-[12px] text-muted-foreground",children:[l.jsx(Ca,{className:"h-3.5 w-3.5 shrink-0"}),"Select a target insight to finish this interaction"]})]}),l.jsx(Ys,{label:"Propagate filters",description:"Choose what filters to pass to the insight",children:l.jsxs(p.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsxs(p.SelectValue,{placeholder:"Choose context mode…",children:[e.contextMode==="interactionFilters"&&"Interaction filters",(e.contextMode==="full"||!e.contextMode)&&"All filters",e.contextMode==="none"&&"None"]})}),l.jsx(p.SelectContent,{children:Zft.map(n=>l.jsx(p.SelectItem,{value:n.value,className:lv,children:l.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-[13px] font-medium leading-[1.35]",children:n.label}),l.jsx("span",{className:"text-[12px] leading-[1.35] text-muted-foreground",children:n.description})]})},n.value))})]})}),l.jsx(Ys,{label:"Display mode",description:"Choose how the insight should be displayed",children:l.jsxs(p.Select,{value:e.displayMode||"modal",onValueChange:n=>t({...e,displayMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsx(p.SelectValue,{placeholder:"Choose display mode…"})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"modal",children:"Open in modal"}),l.jsx(p.SelectItem,{value:"replace-card",children:"Replace the card"})]})]})}),l.jsx(Ys,{label:"Menu label",description:"How this interaction appears when multiple actions are available",children:l.jsx(p.Input,{size:"sm",value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:op(e.mode)})})]})}function Qft(e){return e.filter(t=>t.role==="groupby"||t.role==="pivotby").map(t=>({id:t.name,label:t.label||t.name,category:"attribute",field:t}))}function Jft(){return[{id:"card_id",label:"Card ID",category:"identifier"},{id:"frame_id",label:"Frame ID",category:"identifier"},{id:"sheet_id",label:"Sheet ID",category:"identifier"}]}function eht(e,t){const n=`{{${t}}}`;return e.includes(n)}function tht(e,t){return t.filter(n=>eht(e,n.id))}function nht(e,t,n){const r=`{{${t}}}`,o=e.slice(0,n)+r+e.slice(n),s=n+r.length;return{newTemplate:o,newCursorPosition:s}}function rht(e,t){let n=e;return t.forEach(r=>{const o=`{{${r.id}}}`;let s;if(r.category==="identifier")s=`${r.id.toUpperCase()}-abc123`;else{const i=r.label.toLowerCase();i.includes("name")?s="Example Name":i.includes("region")||i.includes("location")?s="California":i.includes("id")?s="ID-12345":i.includes("category")?s="Category A":s="Sample Value"}n=n.replace(new RegExp(o,"g"),s)}),n}const r2="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function oht({open:e,onOpenChange:t,interaction:n,availableFields:r,onSave:o}){const[s,i]=v.useState(n.urlTemplate||""),[a,c]=v.useState(0),[u,d]=v.useState(n.encodeParameters!==!1),[f,h]=v.useState(n.label||""),m=v.useRef(null);v.useEffect(()=>{e&&(i(n.urlTemplate||""),d(n.encodeParameters!==!1),h(n.label||""),c(0))},[e,n.urlTemplate,n.encodeParameters,n.label]);const g=Qft(r),b=Jft(),x=[...g,...b],y=tht(s,x),w=p.validateURLTemplate(s),C=s&&w.valid?rht(s,y):"",N=I=>{i(I.target.value),c(I.target.selectionStart)},S=I=>{const E=I.target;c(E.selectionStart)},j=I=>{const E=I.target;c(E.selectionStart)},_=I=>{const{newTemplate:E,newCursorPosition:D}=nht(s,I.id,a);i(E),c(D),m.current&&(m.current.focus(),setTimeout(()=>{m.current&&m.current.setSelectionRange(D,D)},0))},k=()=>{w.valid&&(o({...n,urlTemplate:s,parameters:y,encodeParameters:u,label:f}),t(!1))},T=()=>{t(!1)};return l.jsx(Mo,{open:e,onOpenChange:t,children:l.jsxs(go,{className:"flex max-h-[90vh] max-w-5xl flex-col gap-0 overflow-hidden p-0",onOpenAutoFocus:I=>{I.preventDefault(),setTimeout(()=>{var E;(E=m.current)==null||E.focus()},0)},children:[l.jsxs(Is,{className:"space-y-1 border-b border-border px-5 pb-3.5 pt-4 text-left",children:[l.jsx(bo,{className:"text-[15px] font-semibold tracking-tight",children:"Configure drill to URL"}),l.jsx(Ro,{className:"text-[12px] leading-[1.5] text-muted-foreground",children:"Build a custom URL with dynamic parameters that opens when users click on chart elements."})]}),l.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto px-5 py-4",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-5",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Label,{htmlFor:"url-template",className:"text-[13px] font-medium",children:"URL"}),l.jsx(p.TooltipProvider,{children:l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsx(p.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-[12px]",children:"Enter your URL and click parameters from the right panel to insert them. Parameters will be replaced with actual values when the URL is opened."})})]})})]}),l.jsx(zm,{ref:m,id:"url-template",value:s,onChange:N,onClick:S,onKeyUp:j,placeholder:"https://example.com/product/{{product_id}}?region={{region}}",className:"min-h-[200px] font-mono text-[12px] leading-[1.55]"}),!w.valid&&s&&l.jsx("div",{className:"space-y-0.5 text-[12px] text-destructive",children:w.errors.map((I,E)=>l.jsx("div",{children:I},E))}),C&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:r2,children:"Preview"}),l.jsx("p",{className:"break-all rounded-control border border-border/70 bg-muted/40 px-2 py-1.5 font-mono text-[11px] text-muted-foreground",children:C})]})]}),l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Parameters"}),l.jsx(p.TooltipProvider,{children:l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsx(p.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-[12px]",children:"Click any parameter to insert it into your URL at the cursor position. Attributes come from your chart data, identifiers are system values."})})]})})]}),l.jsxs("div",{className:"flex flex-col gap-4 rounded-card border border-border/60 p-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:r2,children:"Attributes"}),l.jsxs("div",{className:"space-y-0.5",children:[g.map(I=>l.jsx(JW,{parameter:I,isUsed:y.some(E=>E.id===I.id),onClick:()=>_(I)},I.id)),g.length===0&&l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"No attributes available"})]})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:r2,children:"Identifiers"}),l.jsx("div",{className:"space-y-0.5",children:b.map(I=>l.jsx(JW,{parameter:I,isUsed:y.some(E=>E.id===I.id),onClick:()=>_(I)},I.id))})]})]})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Tn,{id:"encode-params",checked:u,onCheckedChange:I=>d(I===!0)}),l.jsx(p.Label,{htmlFor:"encode-params",className:"cursor-pointer text-[13px] font-normal",children:"URL encode parameters"}),l.jsx(p.TooltipProvider,{children:l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsx(p.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-[12px]",children:"Recommended. Encodes special characters in parameter values to ensure valid URLs (e.g., spaces become %20)."})})]})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Menu label"}),l.jsx(p.TooltipProvider,{children:l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})}),l.jsx(p.TooltipContent,{children:l.jsx("p",{className:"max-w-xs text-[12px]",children:"How this interaction appears when multiple actions are available"})})]})})]}),l.jsx(p.Input,{size:"sm",value:f,onChange:I=>h(I.target.value),placeholder:op("drillToURL")})]}),l.jsxs("p",{className:"flex items-start gap-1.5 text-[12px] text-muted-foreground",children:[l.jsx(p.Info,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"URLs always open in a new browser tab when clicked."]})]}),l.jsxs(tl,{className:"gap-1.5 border-t border-border px-5 py-3 sm:space-x-0",children:[l.jsx(p.Button,{size:"xs",variant:"outline",onClick:T,children:"Cancel"}),l.jsx(p.Button,{size:"xs",onClick:k,disabled:!w.valid,children:"Save"})]})]})})}function JW({parameter:e,isUsed:t,onClick:n}){var s,i;const r=e.category==="attribute"?OZ:ub,o=((s=e.field)==null?void 0:s.qualifiedFieldName)||((i=e.field)==null?void 0:i.name);return l.jsxs(p.Button,{type:"button",variant:"ghost",className:"h-auto w-full justify-start gap-2 px-2 py-1.5 font-normal hover:bg-muted/60",onClick:n,children:[l.jsx(r,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/70"}),l.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-start gap-0.5",children:[l.jsx("span",{className:"w-full truncate text-[13px]",children:e.label}),o&&l.jsx("span",{className:"w-full truncate font-mono text-[11px] text-muted-foreground",children:o})]}),t&&l.jsx(p.Check,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground"})]})}function sht({interaction:e,availableFields:t,onUpdate:n}){const[r,o]=v.useState(!1),s=!!e.urlTemplate;return l.jsxs("div",{className:"flex flex-col gap-4",children:[s?l.jsxs("div",{className:"flex flex-col gap-3 rounded-card border border-border/60 p-3",children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(Ld,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"text-[13px] font-medium",children:"URL template"})]}),l.jsx("p",{className:"break-all rounded-control border border-border/70 bg-muted/40 px-2 py-1.5 font-mono text-[11px] text-muted-foreground",children:e.urlTemplate})]}),l.jsxs(p.Button,{variant:"outline",size:"xs",onClick:()=>o(!0),children:[l.jsx(DO,{className:"h-3.5 w-3.5"}),"Edit"]})]}),l.jsxs("p",{className:"text-[12px] text-muted-foreground",children:[e.parameters&&e.parameters.length>0?`${e.parameters.length} parameter${e.parameters.length!==1?"s":""} · `:"","URL encoding"," ",e.encodeParameters!==!1?"enabled":"disabled"]})]}):l.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[l.jsx(Ld,{className:"h-8 w-8 text-muted-foreground/40",strokeWidth:1.5}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"No URL configured"}),l.jsx(p.Button,{variant:"outline",size:"xs",onClick:()=>o(!0),children:"Add custom URL"})]}),l.jsx(oht,{open:r,onOpenChange:o,interaction:e,availableFields:t,onSave:n})]})}function iht({interaction:e,onUpdate:t}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs(Ys,{label:"Fetch mode",description:"Choose when to load the detailed data",children:[l.jsxs(p.Select,{value:e.fetchMode||"lazy",onValueChange:n=>t({...e,fetchMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsx(p.SelectValue,{placeholder:"Choose fetch mode…"})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"lazy",className:lv,children:l.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-[13px] font-medium leading-[1.35]",children:"Lazy loading"}),l.jsx("span",{className:"text-[12px] leading-[1.35] text-muted-foreground",children:"Fetch data only when user clicks"})]})}),l.jsx(p.SelectItem,{value:"preloaded",className:lv,children:l.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[l.jsx("span",{className:"text-[13px] font-medium leading-[1.35]",children:"Preloaded"}),l.jsx("span",{className:"text-[12px] leading-[1.35] text-muted-foreground",children:"Fetch all data when dashboard loads"})]})})]})]}),l.jsxs("p",{className:"flex gap-1.5 text-[12px] leading-[1.5] text-muted-foreground",children:[l.jsx(p.Info,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),l.jsx("span",{children:e.fetchMode==="lazy"?"Data is fetched on-demand when the user clicks. Best for large datasets or when detailed data isn't always needed.":"Data is fetched when the dashboard loads. Best for small datasets or when instant drill-down is required."})]})]}),l.jsx(Ys,{label:"Record limit",description:"Maximum number of detailed records to show (0 for unlimited)",children:l.jsx(p.Input,{size:"sm",type:"number",min:"0",placeholder:"100",value:e.inlineLimit??100,onChange:n=>{const r=parseInt(n.target.value)||0;t({...e,inlineLimit:r})}})}),l.jsx(Ys,{label:"Display mode",description:"How to display the detailed records",children:l.jsxs(p.Select,{value:e.displayMode||"table",onValueChange:n=>t({...e,displayMode:n}),children:[l.jsx(p.SelectTrigger,{size:"sm",children:l.jsx(p.SelectValue,{placeholder:"Choose display mode…"})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"table",children:"Table view"}),l.jsx(p.SelectItem,{value:"list",children:"List view"}),l.jsx(p.SelectItem,{value:"cards",children:"Card view"})]})]})}),l.jsxs("div",{className:"divide-y divide-border/60 border-y border-border/60",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3 py-2.5",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Show in modal"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Display detailed records in a modal overlay"})]}),l.jsx(p.Switch,{checked:e.showInModal??!1,onCheckedChange:n=>t({...e,showInModal:n})})]}),l.jsxs("div",{className:"flex items-center justify-between gap-3 py-2.5",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx(p.Label,{className:"text-[13px] font-medium",children:"Allow export"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Enable users to export the detailed records"})]}),l.jsx(p.Switch,{checked:e.allowExport??!0,onCheckedChange:n=>t({...e,allowExport:n})})]})]}),l.jsx(Ys,{label:"Menu label",description:"How this interaction appears when multiple actions are available",children:l.jsx(p.Input,{size:"sm",value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:op(e.mode)})})]})}function aht({interaction:e,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onUpdate:i,onRemove:a}){const c=e.trigger!==void 0,u=e.mode!==void 0,d=c&&u,[f,h]=v.useState(!d),m=()=>{var y;if(!c)return"Configure interaction";const b=`When ${((y=e.trigger)==null?void 0:y.field.label)||"..."}`;if(!u)return`${b} → Choose action`;const x=e.label||op(e.mode);return`${b} → ${x}`},g=u?Vj(e.mode):null;return l.jsxs("div",{className:"relative rounded-card border border-border bg-card text-card-foreground",children:[l.jsx(p.Button,{variant:"ghost",size:"xs",className:"absolute right-1.5 top-1.5 z-10 h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:a,"aria-label":"Remove interaction",children:l.jsx(je.X,{className:"h-3.5 w-3.5"})}),l.jsxs(vu,{open:f,onOpenChange:h,children:[l.jsx(wu,{asChild:!0,children:l.jsxs(p.Button,{variant:"ghost",className:"h-auto w-full justify-between gap-3 rounded-card px-3 py-2.5 pr-10 hover:bg-muted/50",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[g&&l.jsx(g,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate text-left text-[13px] font-medium",children:m()})]}),l.jsx(je.ChevronDown,{className:p.cn("h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",f&&"rotate-180")})]})}),l.jsx(Cu,{children:l.jsxs("div",{className:"space-y-5 border-t border-border/60 p-4",children:[l.jsx("div",{className:"space-y-3",children:c?l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"text-[13px] font-medium",children:["When I click on"," ",l.jsx("span",{className:"text-muted-foreground",children:"(value of)"})]}),e.trigger&&l.jsxs("button",{type:"button","aria-label":`Change trigger field (currently ${e.trigger.field.label})`,className:"inline-flex h-6 items-center gap-1 rounded-control border border-transparent bg-muted/60 pl-1 pr-1.5 text-[11px] font-medium text-foreground transition-colors hover:border-border/60 hover:bg-muted [&_svg]:h-3 [&_svg]:w-3",onClick:()=>{i({...e,trigger:void 0})},children:[ek(e.trigger.field.dataType),l.jsx("span",{children:e.trigger.field.label})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"text-[13px] font-medium",children:"When I click on"}),l.jsx(put,{value:e.trigger,onChange:b=>{i({...e,trigger:b})},metrics:t,attributes:n})]})}),c&&l.jsx(l.Fragment,{children:l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"text-[13px] font-medium",children:"I want to"}),l.jsx(gut,{value:e.mode,onChange:b=>{if(!e.trigger){console.error("Trigger must be defined before selecting action");return}const x={mode:b,trigger:e.trigger};switch(b){case"clickFilter":i({...x,mode:"clickFilter",filterFields:[]});break;case"drillDown":i({...x,mode:"drillDown",filterFields:[]});break;case"dynamicDrill":i({...x,mode:"dynamicDrill",availableFields:[]});break;case"drillThrough":i({...x,mode:"drillThrough",filterFields:[],targetDashboardId:""});break;case"drillToDetail":i({...x,mode:"drillToDetail",filterFields:[]});break;case"drillToURL":i({...x,mode:"drillToURL",filterFields:[],urlTemplate:"",parameters:[],encodeParameters:!0});break;case"inlineDrill":i({...x,mode:"inlineDrill",filterFields:[]});break}}})]})}),c&&u&&l.jsxs(l.Fragment,{children:[l.jsx(p.Separator,{}),l.jsx(lht,{interaction:e,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onUpdate:i})]})]})})]})]})}function lht({interaction:e,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onUpdate:i}){switch(e.mode){case"clickFilter":return l.jsx(xut,{interaction:e,onUpdate:a=>i(a)});case"drillDown":return l.jsx(zft,{interaction:e,onUpdate:a=>i(a),card:o,availableFields:r,onUpdateHierarchies:s});case"dynamicDrill":return l.jsx(Hft,{interaction:e,onUpdate:a=>i(a),availableFields:r});case"drillThrough":return l.jsx(Kft,{interaction:e,onUpdate:a=>i(a)});case"drillToDetail":return l.jsx(Xft,{interaction:e,onUpdate:a=>i(a)});case"drillToURL":return l.jsx(sht,{interaction:e,availableFields:[...t,...n],onUpdate:a=>i(a)});case"inlineDrill":return l.jsx(iht,{interaction:e,onUpdate:a=>i(a)});default:return l.jsx("div",{className:"text-[13px] text-muted-foreground",children:"Unknown interaction type"})}}function cht({interactions:e,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onChange:i}){const[a,c]=v.useState(null),u=()=>{const h=_et().id,m={id:h};i([...e,m]),c(h)},d=(h,m)=>{const g=e[h],b={...m,id:m.id||(g==null?void 0:g.id)},x=[...e];x[h]=b,i(x)},f=h=>{var g;const m=e.filter((b,x)=>x!==h);i(m),a===((g=e[h])==null?void 0:g.id)&&c(null)};return l.jsxs("div",{className:"space-y-4",children:[e.length>0?l.jsx("div",{className:"space-y-3",children:e.map((h,m)=>l.jsx(aht,{interaction:h,metrics:t,attributes:n,availableFields:r,card:o,onUpdateHierarchies:s,onUpdate:g=>d(m,g),onRemove:()=>f(m)},h.id||m))}):l.jsxs("div",{className:"flex flex-col items-center gap-3 py-10 text-center",children:[l.jsx(Ive,{className:"h-8 w-8 text-muted-foreground/40",strokeWidth:1.5}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-[13px] font-medium",children:"No interactions yet"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Add one to make this chart respond to clicks."})]}),l.jsxs(p.Button,{onClick:u,size:"xs",variant:"outline",children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Add interaction"]})]}),e.length>0&&l.jsx("div",{className:"flex justify-start pt-2",children:l.jsxs(p.Button,{onClick:u,size:"xs",variant:"outline",children:[l.jsx(Tr,{className:"h-3.5 w-3.5"}),"Add interaction"]})})]})}function Mhe(e){const t=p.fromSemanticFormat(e.format);if((t==null?void 0:t.type)==="temporal_bucket"){if(!e.granularity)return{};const n=va.resolveApplicableTemporalBucketFormat(t,e.granularity);return n?{granularity:e.granularity,semanticTemporalPresentation:{granularity:e.granularity,format:n}}:{}}return{...e.granularity?{granularity:e.granularity}:{},...t?{format:t}:{}}}const uht=[],dht=[],fht=[];function o2(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function hht(e){return e.flatMap(t=>t.columns.map(n=>({...n,id:n.id||`${t.entityId}-${n.name}`,name:n.name,qualifiedFieldName:n.qualifiedFieldName||n.name,dataType:n.dataType,qualifiedEntityName:n.qualifiedEntityName||t.qualifiedEntityName,label:n.label||p.toTitleCase(n.name),description:n.description,entityId:n.entityId||t.entityId,entityName:n.entityName||t.entityName,entityType:n.entityType||t.entityType})))}function Vz(e){var N;const{tokenProps:t}=It(),n=p.useDashboardStore(S=>S.authToken)||e,{selectedConnection:r,hasSchemaSupport:o}=Eee(e),s=p.useEditorStore(S=>{var j;return(j=S.card.dataSource)==null?void 0:j.connectionId}),i=p.useEditorStore(S=>{var j;return(j=S.card.dataSource)==null?void 0:j.semanticDomainId}),a=p.useEditorStore(S=>{var j;return(j=S.card.dataSource)==null?void 0:j.selectedEntities}),c=v.useMemo(()=>(a==null?void 0:a.filter(S=>S.type==="model"))||uht,[a]),u=v.useMemo(()=>(a==null?void 0:a.filter(S=>dt.DATABASE_ENTITY_TYPES.includes(S.type)))||dht,[a]),d=v.useMemo(()=>(a==null?void 0:a.filter(S=>S.type==="dataset"))||fht,[a]);function f(S){var j;if(S.type==="dataset")return!!s&&!!S.domainId&&!!S.name;if(S.type==="model")return!!s&&!!S.id;if(dt.DATABASE_ENTITY_TYPES.includes(S.type)){const _=((j=r==null?void 0:r.capabilities)==null?void 0:j.path)||[],k=_.includes("database"),T=_.includes("schema")||o;return!(!s||!S.name||k&&!S.database||T&&!S.schema)}return!1}const h=[...c,...u,...d],m=ib({queries:h.map(S=>{let j={};return S.type==="model"?j=o2({connection_id:s,datamodel_id:S.id,database_name:"",schema_name:"",table_name:""}):S.type==="dataset"?j=o2({connection_id:S.connectionId,domain_id:S.domainId,dataset_name:S.name,database_name:S.database,schema_name:S.schema,table_name:S.table}):j=o2({connection_id:s,datamodel_id:"",database_name:S.database,schema_name:S.schema,table_name:S.name}),{queryKey:["columns",s,S,i||null],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",j),enabled:!!s&&f(S)}})}),g=m.some(S=>S.isPending&&S.fetchStatus==="fetching"),b=m.some(S=>S.isError),x=(N=m.find(S=>S.isError))==null?void 0:N.error,y=m.map((S,j)=>{var D,R;const _=h[j],k=((D=S.data)==null?void 0:D.columns)||[],T=_.type==="dataset"?(R=k.find(A=>A.entityName))==null?void 0:R.entityName:void 0,I=T||_.name,E=p.getQualifiedEntityName(_.type==="dataset"&&T?{..._,name:T}:_);return{entityId:_.id||_.name,entityType:_.type,entityName:I,label:_.label,description:_.description,qualifiedEntityName:E,columns:k.map(A=>{const F=_.type==="dataset"?A.entityName||I:_.name,z=A.qualifiedEntityName||(_.type==="dataset"&&F?p.getQualifiedEntityName({..._,name:F}):E);return{id:`${F}-${A.column_name}`,name:A.column_name,qualifiedFieldName:A.qualifiedFieldName||A.column_name,dataType:A.data_type,label:A.label||p.toLabel(A.column_name),description:A.description||"",qualifiedEntityName:z,entityId:A.entityId||_.id||_.id||F,entityName:F,entityType:A.entityType||_.type,role:A.role,expression:A.expression,calculatedFormula:A.calculatedFormula,derivedField:A.derivedField,...Mhe(A),aggregate:A.aggregate}})}}).filter(S=>{var j;return((j=S==null?void 0:S.columns)==null?void 0:j.length)>0})||[],w=m.flatMap(S=>{var j;return((j=S.data)==null?void 0:j.calculatedFields)||[]}).map(S=>({...S,id:p.getStableDomainCalculatedFieldId({...S}),fieldScope:"domain"}));if(w.length>0){const S=new Map;w.forEach(j=>{const _=p.getStableDomainCalculatedFieldId(j);S.has(_)||S.set(_,j)}),y.unshift({entityId:dt.CALCULATED_FIELDS_GROUP_ID,entityType:"dataset",entityName:dt.CALCULATED_FIELDS_GROUP_NAME,label:"Calculated Fields",description:"Domain-level calculated metrics and dimensions",qualifiedEntityName:dt.CALCULATED_FIELDS_GROUP_NAME,columns:Array.from(S.values())})}const C=hht(y);return{columnGroups:y,columns:C,isLoading:g,hasError:b,error:x,refetch:async()=>{await Promise.all(m.map(S=>S.refetch()))}}}function mht(e){const t=n=>{if(!n||typeof n!="object")return!1;const r=n;return Array.isArray(r.cards)};if(!e)return null;if(typeof e=="string")try{const n=JSON.parse(e);return t(n)?n:null}catch{return null}return t(e)?e:null}function ak(e){return Array.isArray(e)?e.map(t=>ak(t)):e&&typeof e=="object"?Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).reduce((t,[n,r])=>(t[n]=ak(r),t),{}):e}function s2(e,t){return JSON.stringify(ak(e))===JSON.stringify(ak(t))}function pht(){var Y,O,q,U,V,K,Q,se,oe;const{open:e,frameId:t,cardId:n,closePopover:r,anchorPosition:o}=K5(),{authToken:s,tokenProps:i}=It(),a=Wr(),{updateCurrentDashboardCard:c,updateFrameCard:u}=p.useDashboardActions(),{setCard:d}=p.useEditorActions(),f=p.useDashboardStore(me=>me.dashboard),h=((Y=f==null?void 0:f.sheets)==null?void 0:Y.flatMap(me=>me.frames||[]).find(me=>(me==null?void 0:me.id)===t))||null,m=h&&n?h.cards.find(me=>me.id===n):null,g=!!(h!=null&&h.visualId&&m),b=Bk((h==null?void 0:h.visualId)||"",{enabled:e&&g&&!!(s!=null&&s.accessToken)&&!!(i!=null&&i.apiServiceUrl)}),x=((O=b.data)==null?void 0:O.frameObject)||((U=(q=b.data)==null?void 0:q.visual)==null?void 0:U.frameObject),y=v.useMemo(()=>mht(x),[x]),w=((V=b.data)==null?void 0:V.lastModified)||((Q=(K=b.data)==null?void 0:K.visual)==null?void 0:Q.lastModified),C=v.useMemo(()=>{if(!m||!h||!y)return null;const me=m.linkedSourceCardId&&y.cards.find(ue=>ue.id===m.linkedSourceCardId);if(me)return me;const le=h.cards.findIndex(ue=>ue.id===m.id);return le>=0&&y.cards[le]||null},[m,h,y]),N=v.useMemo(()=>{const me=new Map;return!h||!y||h.cards.forEach((le,ue)=>{var de;const ne=le.linkedSourceCardId||((de=y.cards[ue])==null?void 0:de.id);ne&&me.set(ne,le.id)}),me},[h,y]),S=v.useMemo(()=>{var le;if(!C)return[];const me=Qf((le=C.interactionConfig)==null?void 0:le.interactions);return H1(me,N)},[C,N]),j=v.useMemo(()=>m?jM(S,m.linkedInteractionTargetOverrides):[],[m,S]),_=g?C:m,k=g&&!!x&&!y&&!b.isFetching;v.useEffect(()=>{if(!e)return;const me=g&&C||m;me&&d(me)},[e,g,C,m,d]);const{columns:T}=Vz(),I=_==null?void 0:_.config,E=T,D=(I==null?void 0:I.metricColumns)||[],R=[...(I==null?void 0:I.groupByColumns)||[],...(I==null?void 0:I.pivotByColumns)||[]],[A,F]=v.useState(((se=_==null?void 0:_.interactionConfig)==null?void 0:se.drillHierarchies)||[]),[z,L]=v.useState(((oe=_==null?void 0:_.interactionConfig)==null?void 0:oe.allowedDrillTargets)||[]),[$,H]=v.useState([]),[M,B]=v.useState(!1),W=v.useRef(null),P=v.useMemo(()=>`${e}-${t}-${n}-${g?(C==null?void 0:C.id)||"loading":(m==null?void 0:m.id)||"none"}`,[e,t,n,g,C==null?void 0:C.id,m==null?void 0:m.id]);v.useEffect(()=>{e||(W.current=null)},[e]),v.useEffect(()=>{var me,le,ue;!e||!_||g&&!C||W.current!==P&&(F(((me=_.interactionConfig)==null?void 0:me.drillHierarchies)||[]),L(((le=_.interactionConfig)==null?void 0:le.allowedDrillTargets)||[]),H(g?j:Qf((ue=_.interactionConfig)==null?void 0:ue.interactions)),W.current=P)},[e,_,P,g,C,j]);const G=async()=>{var me,le,ue,ne,de;if(m){B(!0);try{const Ce=Qf(p.normalizeInteractionsForSave($));if(!g||!(h!=null&&h.visualId)||!y||!C){const Ke={...m,interactionConfig:{...m.interactionConfig,drillHierarchies:A,allowedDrillTargets:z,interactions:Ce}},We=(le=(me=f==null?void 0:f.sheets)==null?void 0:me.find(Qe=>(Qe.frames||[]).some(xe=>xe.id===(h==null?void 0:h.id))))==null?void 0:le.id;We&&(h!=null&&h.id)&&u?u(We,h.id,Ke):c(Ke),d(Ke),r();return}const ce=Qf((ue=C.interactionConfig)==null?void 0:ue.interactions),ie=jet(Ce,ce),we=((ne=C.interactionConfig)==null?void 0:ne.drillHierarchies)||[],fe=((de=C.interactionConfig)==null?void 0:de.allowedDrillTargets)||[],ae=!s2(A,we)||!s2(z,fe)||!s2(ie,ce),ee={...C,interactionConfig:{...C.interactionConfig,drillHierarchies:A,allowedDrillTargets:z,interactions:ie}},J={...y,cards:y.cards.map(Ke=>Ke.id===C.id?ee:Ke)};if(ae){if(!(i!=null&&i.apiServiceUrl)||!(s!=null&&s.accessToken))throw new Error("Missing authentication context for visual update");const Ke=await fetch(`${i.apiServiceUrl}/management/v1/visuals/${h.visualId}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(s==null?void 0:s.accessToken)||""}`},body:JSON.stringify({frameObject:J,expectedLastModified:w})});if(!Ke.ok){const Qe=await Ke.json().catch(()=>({})),xe=new Error((Qe==null?void 0:Qe.error)||"Failed to update visual");throw xe.status=Ke.status,xe}const We=await Ke.json();a.setQueryData(["resource-by-id","visual",h.visualId],We)}const re=H1(Qf(ie),N),pe=re.filter(Ke=>Ke.id).map(Ke=>Ke.id),Ee=hU(ket(Ce,re),pe),Te=jM(re,Ee),ze={...m,linkedSourceCardId:m.linkedSourceCardId||C.id,linkedInteractionTargetOverrides:Ee,interactionConfig:{...m.interactionConfig,drillHierarchies:A,allowedDrillTargets:z,interactions:Te}},Pe=Ke=>{const We=new Map;return Ke.cards.forEach((Qe,xe)=>{var Ae;const Ve=Qe.linkedSourceCardId||((Ae=y.cards[xe])==null?void 0:Ae.id);Ve&&We.set(Ve,Qe.id)}),We},He=Ke=>{const We=Ke.cards.find(xe=>xe.linkedSourceCardId===C.id);if(We)return We;const Qe=y.cards.findIndex(xe=>xe.id===C.id);return Qe>=0&&Ke.cards[Qe]||null},ye=[];if((f.sheets||[]).forEach(Ke=>{(Ke.frames||[]).forEach(We=>{if(We.visualId!==h.visualId)return;const Qe=He(We);if(!Qe)return;const xe=Pe(We),Ve=H1(Qf(ie),xe),Ae=Ve.filter($e=>$e.id).map($e=>$e.id),ke=We.id===h.id&&Qe.id===m.id?Ee:Qe.linkedInteractionTargetOverrides,Be=hU(ke,Ae),Ie=jM(Ve,Be);ye.push({sheetId:Ke.id,frameId:We.id,isCurrentCard:We.id===h.id&&Qe.id===m.id,card:{...Qe,linkedSourceCardId:Qe.linkedSourceCardId||C.id,linkedInteractionTargetOverrides:Be,interactionConfig:{...Qe.interactionConfig,drillHierarchies:A,allowedDrillTargets:z,interactions:Ie}}})})}),ye.length>0&&u){ye.forEach(We=>{u(We.sheetId,We.frameId,We.card)});const Ke=ye.find(We=>We.isCurrentCard);Ke||c(ze),d((Ke==null?void 0:Ke.card)||ze)}else c(ze),d(ze);r()}catch(Ce){Ce.status===409?(lt.error("This saved visual was updated by another editor. Refresh and retry."),W.current=null,await b.refetch()):lt.error(Ce.message||"Failed to save interactions")}finally{B(!1)}}},Z=()=>{W.current=null,r()};if(!e||!t||!n||!m||!o)return null;const X={position:"fixed",left:`${o.left}px`,top:`${o.top}px`,width:`${o.width}px`,height:`${o.height}px`};return l.jsxs(p.Popover,{modal:!1,open:e,onOpenChange:me=>!me&&r(),children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsx("div",{style:X,className:"pointer-events-none invisible","aria-hidden":"true"})}),l.jsxs(p.PopoverContent,{onEscapeKeyDown:me=>me.preventDefault(),className:"mt-5 flex max-h-[70vh] w-[600px] max-w-4xl flex-col overflow-hidden p-0",align:"start",side:"right",sideOffset:20,children:[l.jsx(p.Arrow2,{className:"fill-border",width:12,height:8}),l.jsxs("div",{className:"flex flex-col border-b border-border px-5 pb-3.5 pt-4",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("h2",{className:"text-[15px] font-semibold tracking-tight",children:"Configure interactions"}),$.length>0&&l.jsx("span",{className:"text-[11px] tabular-nums text-muted-foreground/70",children:$.length})]}),l.jsxs("p",{className:"mt-1 text-[12px] leading-[1.5] text-muted-foreground",children:["Set up drill behaviors for ",(m==null?void 0:m.title)||"this chart"]}),g&&l.jsx("p",{className:"mt-2 text-[12px] leading-[1.5] text-muted-foreground",children:"Logic is owned by the saved visual. Filter target routing is saved per dashboard instance."})]}),l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:l.jsx("div",{className:"space-y-6 px-5 py-4",children:g&&!C?l.jsx("p",{className:"text-[13px] text-muted-foreground",children:b.isFetching?"Loading saved visual interaction config...":k?"Unable to load interaction settings for this saved visual. Please refresh or relink the visual.":"Unable to map this dashboard card to its source card in the saved visual. Re-link the visual to continue."}):l.jsx("div",{children:l.jsx("div",{className:"grid grid-cols-1 gap-4",children:l.jsx(cht,{interactions:$,metrics:D,attributes:R,availableFields:E,card:{..._||m,interactionConfig:{...(_==null?void 0:_.interactionConfig)||m.interactionConfig,drillHierarchies:A}},onUpdateHierarchies:F,onChange:me=>H(me)})})})})}),l.jsxs("div",{className:"flex justify-end gap-1.5 border-t border-border px-5 py-3",children:[l.jsx(p.Button,{size:"xs",variant:"outline",onClick:Z,children:"Cancel"}),l.jsx(p.Button,{size:"xs",onClick:G,disabled:M||g&&!C,children:M?"Saving…":g?"Save to library":"Save"})]})]})]})}function jF(e,t){return Ho.serializeLayoutsForDirtyCheck(e)!==Ho.serializeLayoutsForDirtyCheck(t)}function ght(e,t){return t&&jF(e,t)?t:null}function bht(e){return!!e.expression}function xht(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function yht(e){const t=xht(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function Rhe(e){return e.fieldScope==="domain"&&e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===dt.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===dt.CALCULATED_FIELDS_GROUP_NAME}function vht(e){return Rhe(e)}function wht(e){return e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER||(e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card")&&yht(e.id)&&!e.entityName}function rf(e){return bht(e)?vht(e)?"domain_calculated":wht(e)?"user_calculated":"inline_expression":"none"}function nx(e){return rf(e)!=="none"}function Qa(e){if(!nx(e))return!1;const t=rf(e);return t==="domain_calculated"||t==="user_calculated"?!0:e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card"}function Ahe(e){return Qa(e)&&e.fieldScope!=="card"}function Phe(e,t,n){return nx(e)?t==="editor"?!0:t==="filter"?Qa(e)&&e.fieldScope!=="card":Qa(e)&&(n==null?void 0:n.isValuePickSafe)!==!1:!1}function i2(e,t){return e.map(n=>({...n,fieldScope:t}))}function Fhe(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:o,refetch:s}=Vz(),i=p.useEditorStore(_=>_.frame.calculatedFields),a=p.useEditorStore(_=>_.card.calculatedFields),c=p.useEditorStore(_=>_.card.config),u=p.useDashboardStore(_=>_.dashboard),d=p.useDashboardStore(_=>_.visualEditPendingDashboardCalculatedFields),f=p.useDashboardStore(_=>_.selectedSheetId),h=p.useDashboardStore(_=>_.selectedFrameId),m=p.useDashboardStore(_=>_.isVisualEditing),g=v.useMemo(()=>e.filter(_=>rf(_)==="domain_calculated"),[e]),b=v.useMemo(()=>e.filter(_=>rf(_)!=="domain_calculated"),[e]),x=v.useMemo(()=>{var k;if(m)return i||[];const _=(k=u==null?void 0:u.sheets)==null?void 0:k.find(T=>T.id===f);return p.getSheetCalculatedFields(_)},[u==null?void 0:u.sheets,i,m,h,f]),y=v.useMemo(()=>{const _=d??(u==null?void 0:u.calculatedFields)??[];return _.length?i2(_,"dashboard"):[]},[u==null?void 0:u.calculatedFields,d]),w=v.useMemo(()=>x.length?i2(x,"sheet"):[],[x]),C=v.useMemo(()=>p.buildCalculatedFieldComparableKeySet([...y,...w]),[y,w]),N=v.useMemo(()=>{const _=(a||[]).filter(D=>Qa(D)&&D.fieldScope!=="domain"),k=((c==null?void 0:c.metricColumns)||[]).filter(D=>Qa(D)&&D.fieldScope!=="domain"),T=((c==null?void 0:c.groupByColumns)||[]).filter(D=>Qa(D)&&D.fieldScope!=="domain"),E=p.dedupeCalculatedFields([..._,...k,...T]).filter(D=>!C.has(p.getCalculatedFieldComparableKey(D)));return i2(E,"card").map(D=>({...D,id:`card-source-${D.id}`}))},[a,c==null?void 0:c.groupByColumns,c==null?void 0:c.metricColumns,C]),S=v.useMemo(()=>[...g,...y,...w,...N,...b],[N,b,y,g,w]),j=v.useMemo(()=>t.filter(_=>_.entityId!==dt.CALCULATED_FIELDS_GROUP_ID),[t]);return{columns:e,columnGroups:j,rawColumnGroups:t,columnFields:b,domainCalculatedFields:g,dashboardCalculatedFields:y,sheetCalculatedFields:w,cardCalculatedFields:N,scopedFields:S,isLoading:n,hasError:r,error:o,refetch:s}}function Cht(e){const t="expression"in e&&e.expression||"",n=e.qualifiedEntityName||e.entityName||"",r=e.fieldScope||"unscoped",o=e.qualifiedFieldName||e.name;return t?["calculated",r,e.role||"field",n,o,t].join("::"):["calculated",r,e.role||"field",n,p.normalizeCalculatedFieldId(e.id)||o].join("::")}function Sht(e){return["physical",e.fieldScope||"physical",e.role||"field",e.qualifiedEntityName||"",e.qualifiedFieldName||e.name,e.name].join("::")}function $p(e){const t=new Map;return e.forEach(n=>{const r=nx(n)?Cht(n):Sht(n);t.has(r)||t.set(r,n)}),Array.from(t.values())}function Hz(e){return!xr.isCalculatedMetric(e)}function a2(e,t){return $p(e.filter(n=>Phe(n,t,{isValuePickSafe:Hz(n)})))}function Nht(e){return!nx(e)||Phe(e,"inline-filter",{isValuePickSafe:Hz(e)})}function jht(e){return!nx(e)||Ahe(e)}function Ohe(){const e=Fhe(),t=v.useMemo(()=>$p(e.scopedFields),[e.scopedFields]),n=v.useMemo(()=>$p([...e.columns,...e.dashboardCalculatedFields,...e.sheetCalculatedFields]),[e.columns,e.dashboardCalculatedFields,e.sheetCalculatedFields]),r=v.useMemo(()=>$p(n.filter(jht)),[n]),o=v.useMemo(()=>a2(t,"editor"),[t]),s=v.useMemo(()=>a2(n.filter(Ahe),"filter"),[n]),i=v.useMemo(()=>$p(t.filter(Hz)),[t]),a=v.useMemo(()=>$p(i.filter(Nht)),[i]),c=v.useMemo(()=>a2(a,"inline-filter"),[a]);return{...e,filterableFields:t,sharedFilterableFields:n,dashboardFilterableFields:r,inlineFilterableFields:a,scopedCalculatedFields:o,sharedCalculatedFields:s,inlineCalculatedFields:c,valuePickFilterableFields:i}}const Lhe=te.forwardRef(function({icon:t,label:n,asButton:r,disabled:o,labelWrapper:s,inQuery:i,trailing:a,kebab:c,showKebab:u,onKebabClick:d,selected:f,dragging:h,disableHover:m,className:g,...b},x){const y=l.jsx("span",{className:"block min-w-0 flex-1 truncate text-[13px] text-foreground/90",children:n}),w=p.cn("group/field-row relative flex h-7 items-center gap-2 px-4 transition-colors",h&&"opacity-40",f?"bg-muted":i?"bg-foreground/[0.06] hover:bg-foreground/[0.09]":!m&&"hover:bg-muted/60",r&&"w-full text-left disabled:cursor-not-allowed",g),C=l.jsxs(l.Fragment,{children:[t,s?s(y):y,i&&l.jsx("span",{className:"sr-only",children:"In query"}),a,(c||u)&&l.jsx("button",{type:"button","aria-label":"Field actions",onClick:N=>{N.stopPropagation(),d==null||d(N)},onPointerDown:N=>N.stopPropagation(),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:opacity-100 group-focus-within/field-row:opacity-100 [@media(hover:none)]:opacity-100",children:c??l.jsx(Ci,{className:"h-3 w-3"})})]});return r?l.jsx("button",{ref:x,type:"button",disabled:o,"data-selected":f?"true":void 0,className:w,...b,children:C}):l.jsx("div",{ref:x,"data-selected":f?"true":void 0,className:w,...b,children:C})});function qz(e){const{tokenProps:t,authToken:n}=It(),r=t==null?void 0:t.apiServiceUrl;return Un({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const o=`${r}/v1/domains/${e}/joinability`;return p.getRequest(o,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:o=>Math.min(1e3*2**o,3e4)})}function $he(e,t,n){if(t==="source")return{isValid:!0};const r=p.getDataType(e.dataType);if(n==="detailTable"&&t!=="detailColumns"&&t!=="sortBy")return{isValid:!1,reason:"Detail tables only accept columns"};if(n==="kpi"){if(t==="groupBy"&&r!=="date")return{isValid:!1,reason:"KPI Trend By only accepts date fields"};if(t==="metrics"&&r==="date")return{isValid:!1,reason:"KPI metrics cannot be date fields"}}return{isValid:!0}}function zhe(e,t,n,r,o){if(e!=="kpi"||o.length<3)return;const s=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=o.some(a=>{var c;return((c=a.comparison)==null?void 0:c.mode)==="explicit"});!s&&!i||n(r,{groupByColumns:[],metricColumns:o.map(a=>({...a,comparison:void 0}))})}function kht(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const _ht=new Set(["COUNT","DISTINCT"]),Iht=new Set(["running_total","moving_average","previous_period_delta"]);function Tht(e){return p.getDataType(e.dataType||"")==="number"?!0:e.aggregate?_ht.has(e.aggregate.toUpperCase()):!1}function Eht(e,t){var r,o;return!!((o=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:o.function)}function Uz(e,t){var n,r;return e==="aggregateTable"&&((((n=t.rowAggregates)==null?void 0:n.length)??0)>0||(((r=t.columnAggregates)==null?void 0:r.length)??0)>0)}function Bhe({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,c;if(e==="detailTable"||e==="kpi")return{supported:!1,reason:"Metric transforms are not supported for this card type."};if((((i=t.groupByColumns)==null?void 0:i.length)??0)===0)return{supported:!1,reason:"Metric transforms require at least one grouped dimension."};if(!Tht(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const o=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,s=e==="pivotTable"||Uz(e,t);return o&&!s?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:Iht.has(r)&&(((c=t.groupByColumns)==null?void 0:c.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function Dht(e){return e.find(t=>p.getDataType(t.dataType||"")==="date")}function Mht(e){return e}function l0({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(s=>s.id&&s.id!==n).map(s=>s.id),o=[];if(e==="pivotTable"||Uz(e,t))for(const s of t.pivotByColumns||[])s.id&&o.push(s.id);return Array.from(new Set([...r,...o]))}function Rht({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const o=r||((i=Dht(n.groupByColumns||[]))==null?void 0:i.id),s=l0({cardType:t,cardConfig:n,orderByFieldId:o});return e==="moving_average"?{function:"moving_average",...o?{orderBy:{fieldId:o,direction:"asc"}}:{},partitionByFieldIds:s,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...o?{orderBy:{fieldId:o,direction:"asc"}}:{},partitionByFieldIds:s,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...o?{orderBy:{fieldId:o,direction:"asc"}}:{},partitionByFieldIds:s,frame:"unbounded_preceding"}}const Aht=new Set(["table","aggregateTable","pivotTable","detailTable"]);function Pht(e){return e.alias||e.label||e.name}function Vhe(e,t,n){var a,c,u;if(!e)return null;const r=p.fromSemanticFormat(t.format);if(!r)return null;const o=n||{};let s=o,i=!1;if(Aht.has(e.type)){const d=p.toColumnNumberFormat(r),f=Pht(t);if(d&&!((c=(a=o.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:c[f])){const m=To();s={...s,tablePrefs:{...s.tablePrefs||{},columnSettingsMap:{...((u=s.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...m,type:"number",textAlign:"right",numberFormat:{...m.numberFormat,...d}}}}},i=!0}if(!o.formatNumber){const h=p.toLegacyFormatNumber(r);h&&(s={...s,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?s:null}const Hhe=e=>{var X;const t=(X=e==null?void 0:e.dataSource)==null?void 0:X.semanticDomainId,{data:n}=qz(t),{updateCardConfig:r,updateGroupByColumn:o,updateMetricColumn:s,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:c,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=p.useEditorActions(),m=p.useEditorStore(Y=>Y.card.type),g=e==null?void 0:e.id,b=(Y,O)=>p.resolveShelfFieldId(Y,O),x=v.useCallback(Y=>{if(!(e!=null&&e.config))return[];switch(Y){case"groupBy":return(e.config.groupByColumns||[]).map(O=>({...O,id:b(O,"groupBy"),label:O.label!==void 0?O.label:O.name}));case"metrics":return(e.config.metricColumns||[]).map(O=>({...O,id:b(O,"metrics"),label:O.label!==void 0?O.label:O.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map(O=>({...O,id:b(O,"pivotBy"),label:O.label!==void 0?O.label:O.name}));case"sortBy":return(e.config.sortByColumns||[]).map(O=>({id:b(O,"sortBy"),name:O.name,dataType:O.dataType,label:O.label!==void 0?O.label:O.name,qualifiedEntityName:O.qualifiedEntityName,entityId:O.entityId,entityName:O.entityName,entityType:O.entityType,direction:O.direction}));case"detailColumns":return kht(e.config.detailColumns,O=>b(O,"detailColumns"));case"source":return[];default:return[]}},[e]),y=v.useCallback((Y,O)=>{if(g)switch(Y){case"groupBy":{r(g,{groupByColumns:O});break}case"metrics":{r(g,{metricColumns:O});break}case"pivotBy":{r(g,{pivotByColumns:O});break}case"sortBy":{r(g,{sortByColumns:O});break}case"detailColumns":{r(g,{detailColumns:O});break}}},[g,r]),w=v.useCallback((Y,O,q)=>{if(!g)return;const U=x(Y),V=U[O];if(V)switch(Y){case"groupBy":o(g,V.id,{label:q});break;case"metrics":s(g,V.id,{label:q});break;case"pivotBy":i(g,V.id,{label:q});break;case"sortBy":a(g,V.id,{label:q});break;case"detailColumns":{const K=U.map((Q,se)=>se===O?{...Q,label:q}:Q);r(g,{detailColumns:K});break}}},[g,x,o,s,i,a,r]),C=v.useCallback((Y,O)=>{if(!g)return;const U=x("metrics")[Y];U&&s(g,U.id,{aggregate:O,label:qre(U.name,O)})},[g,x,s]),N=v.useCallback((Y,O,q)=>{if(!g)return;const U=x("detailColumns");if(!U[Y])return;const K={dateFormat:O,customFormat:O==="custom"&&q?q:void 0},Q=U.map((se,oe)=>oe===Y?{...se,...K}:se);r(g,{detailColumns:Q})},[g,x,r]),S=v.useCallback((Y,O)=>{if(!g)return;const q=x("groupBy")[Y];if(!q)return;const U=p.readTemporalBucketAuthoringState({fieldId:q.id,dataType:q.dataType,granularity:q.granularity,format:q.format,dateFormat:q.dateFormat,customFormat:q.customFormat,semanticTemporalPresentation:q.semanticTemporalPresentation});U.ok&&o(g,q.id,{granularity:U.granularity,format:O,dateFormat:void 0,customFormat:void 0})},[g,x,o]),j=v.useCallback((Y,O)=>{if(!g)return;const U=x("groupBy")[Y];if(!U)return;const V=O,K=p.readTemporalBucketAuthoringSelection({fieldId:U.id,dataType:U.dataType,granularity:V,format:U.format,dateFormat:U.dateFormat,customFormat:U.customFormat,semanticTemporalPresentation:U.semanticTemporalPresentation}).format;o(g,U.id,{granularity:V,format:qc.reconcileTemporalBucketAuthoringFormat(K,V),dateFormat:void 0,customFormat:void 0})},[g,x,o]),_=v.useCallback((Y,O)=>{if(!g)return;const U=x("metrics")[Y];U&&s(g,U.id,{aliasTemplate:O})},[g,x,s]),k=v.useCallback((Y,O)=>{if(!g)return;const U=x("pivotBy")[Y];U&&i(g,U.id,{memberOrder:O})},[g,x,i]),T=v.useCallback((Y,O)=>{if(console.log("handleValueAliasesChange",Y,O),!g)return;console.log("handleValueAliasesChange",Y,O);const U=x("metrics")[Y];U&&(console.log("handleValueAliasesChange",O),s(g,U.id,{valueAliases:O}))},[g,x,s]),I=v.useCallback((Y,O)=>{var V,K;if(!g)return;const U=x("metrics")[Y];U&&(s(g,U.id,{format:O}),m==="kpi"&&((K=(V=e==null?void 0:e.preferences)==null?void 0:V.kpiVisualOptions)!=null&&K.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,g,m,x,h,s]),E=v.useCallback((Y,O)=>{var Q,se;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=O!=="inherit"&&O!=="off"&&((Q=U.parameters)==null?void 0:Q.windowTransform),K=O==="inherit"?void 0:O==="off"?{mode:"off"}:O==="target"?{mode:"explicit",spec:{kind:"target",targetValue:((se=U.comparison)==null?void 0:se.mode)==="explicit"&&U.comparison.spec.kind==="target"?U.comparison.spec.targetValue:0}}:{mode:"explicit",spec:{kind:O}};s(g,U.id,{comparison:K,...V?{parameters:{...U.parameters||{},windowTransform:void 0}}:{}})},[g,x,s]),D=v.useCallback((Y,O)=>{if(!g)return;const q=x("metrics")[Y];q&&s(g,q.id,{comparison:{mode:"explicit",spec:O}})},[g,x,s]),R=v.useCallback((Y,O)=>{if(!g)return;const q=x("metrics")[Y];!q||q.semanticComparisonPolarity||s(g,q.id,{comparisonPolarity:O})},[g,x,s]),A=v.useCallback((Y,O)=>{var me,le,ue;if(!g||!(e!=null&&e.config))return;const U=x("metrics")[Y];if(!U)return;if(O==="none"){s(g,U.id,{parameters:{...U.parameters||{},windowTransform:void 0}});return}const V=Bhe({cardType:m,cardConfig:e.config,metric:U,transformMode:O});if(!V.supported){lt.error(V.reason||"Metric transform is not supported here.");return}const K=new Set((e.config.groupByColumns||[]).map(ne=>ne.id)),Q=(ue=(le=(me=U.parameters)==null?void 0:me.windowTransform)==null?void 0:le.orderBy)==null?void 0:ue.fieldId,se=Q&&K.has(Q)?Q:void 0,oe=Rht({transformMode:O,cardType:m,cardConfig:e.config,fallbackOrderByFieldId:se});s(g,U.id,{comparison:void 0,parameters:{...U.parameters||{},windowTransform:oe}})},[e,g,m,x,s]),F=v.useCallback((Y,O)=>{var oe,me;if(!g||!(e!=null&&e.config))return;const U=x("metrics")[Y];if(!U)return;const V=(oe=U.parameters)==null?void 0:oe.windowTransform;if(!V||!["running_total","moving_average","previous_period_delta"].includes(V.function))return;const K=l0({cardType:m,cardConfig:e.config,orderByFieldId:O}),se=(V.partitionByFieldIds||K).filter(le=>le!==O);s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,orderBy:{fieldId:O,direction:((me=V.orderBy)==null?void 0:me.direction)||"asc"},partitionByFieldIds:se}}})},[e,g,m,x,s]),z=v.useCallback((Y,O)=>{var K;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(K=U.parameters)==null?void 0:K.windowTransform;!V||!["running_total","moving_average","previous_period_delta"].includes(V.function)||s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,orderBy:V.orderBy?{...V.orderBy,direction:O}:V.orderBy}}})},[g,x,s]),L=v.useCallback((Y,O)=>{var se,oe;if(!g||!(e!=null&&e.config))return;const U=x("metrics")[Y];if(!U)return;const V=(se=U.parameters)==null?void 0:se.windowTransform;if(!V)return;const K=l0({cardType:m,cardConfig:e.config,orderByFieldId:(oe=V.orderBy)==null?void 0:oe.fieldId}),Q=new Set(V.partitionByFieldIds||K);Q.has(O)?Q.delete(O):Q.add(O),s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,partitionByFieldIds:Array.from(Q)}}})},[e,g,m,x,s]),$=v.useCallback((Y,O)=>{var oe,me;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(oe=U.parameters)==null?void 0:oe.windowTransform;if(!V||V.function!=="moving_average")return;const K=Math.max(1,Math.floor(O||1)),Q=((me=V.movingAverage)==null?void 0:me.minPeriods)||1,se=Math.min(Q,K);s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,movingAverage:{windowSize:K,minPeriods:se}}}})},[g,x,s]),H=v.useCallback((Y,O)=>{var se,oe;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(se=U.parameters)==null?void 0:se.windowTransform;if(!V||V.function!=="moving_average")return;const K=((oe=V.movingAverage)==null?void 0:oe.windowSize)||7,Q=Math.max(1,Math.min(Math.floor(O||1),K));s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,movingAverage:{windowSize:K,minPeriods:Q}}}})},[g,x,s]),M=v.useCallback((Y,O)=>{var K;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(K=U.parameters)==null?void 0:K.windowTransform;!V||V.function!=="previous_period_delta"||s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,previousPeriodDelta:{mode:O}}}})},[g,x,s]),B=v.useCallback((Y,O)=>{var Q;if(!g||!(e!=null&&e.config))return;const U=x("metrics")[Y];if(!U)return;const V=(Q=U.parameters)==null?void 0:Q.windowTransform;if(!V||V.function!=="percent_of_total")return;const K=O==="grand_total"?[]:(V.partitionByFieldIds||[]).length>0?V.partitionByFieldIds||[]:l0({cardType:m,cardConfig:e.config,orderByFieldId:void 0});s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,partitionByFieldIds:K,percentOfTotal:{...V.percentOfTotal||{},scope:O}}}})},[e,g,m,x,s]),W=v.useCallback((Y,O)=>{var K;if(!g)return;const U=x("metrics")[Y];if(!U)return;const V=(K=U.parameters)==null?void 0:K.windowTransform;!V||V.function!=="percent_of_total"||s(g,U.id,{parameters:{...U.parameters||{},windowTransform:{...V,percentOfTotal:{...V.percentOfTotal||{},output:O}}}})},[g,x,s]),P=v.useCallback((Y,O)=>{if(!g)return;const U=x("metrics")[Y];U&&s(g,U.id,{comparison:O===void 0?{mode:"explicit",spec:{kind:"target",targetValue:0}}:{mode:"explicit",spec:{kind:"target",targetValue:O}}})},[g,x,s]),G=v.useCallback(async Y=>{var oe;if(!g)return;const O=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy"),...x("detailColumns")],q=Y,U=p3e(q,O,{joinPlan:(oe=e==null?void 0:e.config)==null?void 0:oe.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t,datasetAliases:n==null?void 0:n.datasets});if(!U.isValid){U.showError&&$re();return}const V=j3e(q,O,m);if(!V){lt.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const K=$he(q,V,m);if(!K.isValid){lt.error("Invalid Field Type",{description:K.reason,position:"top-center",duration:3e3});return}const Q=x(V);if(zre(q,Q))return;const se=Ure(q,V,Q);if(se){const me=[...Q,se];if(y(V,me),V==="metrics"){const le=Vhe(e,se,e==null?void 0:e.preferences);le&&h(le),zhe(m,e==null?void 0:e.config,r,g,me)}}},[g,e,x,y,t,n,m,r,h]),Z=v.useCallback((Y,O)=>{if(!g)return;const U=x(Y)[O];if(U){if(Y!=="sortBy"){const V=x("sortBy"),K=V.filter(Q=>!(Q.name===U.name&&Q.qualifiedEntityName===U.qualifiedEntityName));K.length!==V.length&&r(g,{sortByColumns:K})}switch(Y){case"groupBy":c(g,U.id);break;case"metrics":u(g,U.id);break;case"pivotBy":d(g,U.id);break;case"sortBy":f(g,U.id);break;case"detailColumns":{r(g,{detailColumns:(x("detailColumns")||[]).filter((V,K)=>K!==O)});break}}}},[g,x,c,u,d,f,r]);return{getFieldsForContainer:x,setFieldsForContainer:y,updateLabel:w,handleAggregationChange:C,handleDetailDateFormatChange:N,handleTemporalBucketFormatChange:S,handleGranularityChange:j,handleAliasTemplateChange:_,handlePivotMemberOrderChange:k,handleValueAliasesChange:T,handleMetricFormatChange:I,removeField:Z,handleFieldClick:G,handleMetricComparisonChange:E,handleMetricComparisonSpecChange:D,handleMetricComparisonPolarityChange:R,handleMetricWindowTransformChange:A,handleMetricWindowOrderByChange:F,handleMetricWindowDirectionChange:z,handleMetricWindowPartitionToggle:L,handleMetricMovingAverageWindowSizeChange:$,handleMetricMovingAverageMinPeriodsChange:H,handleMetricPreviousPeriodDeltaModeChange:M,handleMetricPercentOfTotalScopeChange:B,handleMetricPercentOfTotalOutputChange:W,handleMetricTargetValueChange:P,cardType:m}};function qhe(e){var y;const{tokenProps:t}=It(),n=p.useDashboardStore(w=>w.authToken)||e,r=p.useEditorStore(w=>w.selectedConnectionId),o=p.useEditorStore(w=>w.selectedDatabaseName),s=p.useEditorStore(w=>w.selectedDatamodelId),i=p.useEditorStore(w=>w.selectedSchemaName),a=p.useEditorStore(w=>w.selectedTableName),{selectedConnection:c}=Au(),u=c==null?void 0:c.type,{data:d,isLoading:f,isFetching:h,isError:m,refetch:g}=Un({queryKey:["columns",r,o,s,i,a],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",{connection_id:r,datamodel_id:s||"",database_name:o,schema_name:i,table_name:a}),enabled:b(u)});function b(w){var _;if(!(n!=null&&n.accessToken))return!1;if(s&&s)return!0;if(!r||!w)return!1;const C=((_=c==null?void 0:c.capabilities)==null?void 0:_.path)||[],N=C.includes("database"),S=C.includes("schema"),j=C.includes("table");return!(N&&(!o||o==="NA")||S&&!i||j&&!a)}return{columns:(y=d==null?void 0:d.columns)==null?void 0:y.map(w=>({...w,data_type:w.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:m,refetchColumns:g}}function Fht(e){const t=p.useDashboardStore(w=>w.dashboard),n=p.useDashboardStore(w=>{var C;return((C=w.reportContext)==null?void 0:C.calendar)??null}),r=p.useDashboardStore(w=>w.selectedLensId),o=p.useFinalFilterGroupKey(e)||"",s=JL(e),{cardFilterValues:i,controlValues:a,queryRelevantConfig:c}=s,u=p.useDashboardStore(w=>w.dashboardInputReferenceTime),d=v.useMemo(()=>p.getDashboardCards(t),[t]),f=v.useMemo(()=>d.length>0?d:[e],[e,d]),h=v.useMemo(()=>Object.fromEntries(f.map(w=>[w.id,w.id===e.id?c:w.config])),[e.id,c,f]),m=u_(f,{authority:"editor",queryRelevantConfigsByCardId:h}).payload,g=p.resolveCardPrimaryDateField({card:e,cardConfig:c,semanticExecutionPayload:m}),b=(e==null?void 0:e.sql)||"",x=p.getGlobalDateFilterCoverage(t,m);return{queryKey:n?E5(e,{...s,finalFiltersKey:o},{selectedLensId:r,resolvedPrimaryDateField:g,calendarContext:n,allowGlobalDateMinutePrecision:x.allEligibleTargetsAreDateTime,globalDateComparisonReferenceTime:u}).queryKey:[],sql:b,cardFilterValues:i,controlValues:a}}function mT(e,t){var Te,ze,Pe,He,ye,Ke,We,Qe;const{tokenProps:n}=It(),r=Wr(),o=It().authToken||e,s=p.useEditorStore(xe=>xe.selectedConnectionId),i=p.useEditorStore(xe=>xe.card),{queryKey:a}=Fht(i),c=p.useEditorStore(xe=>xe.selectedDatamodelId),u=p.useEditorStore(xe=>xe.isDevMode),d=p.useEditorStore(xe=>xe.selectedDatabaseName),f=p.useEditorStore(xe=>xe.selectedSchemaName),h=p.useEditorStore(xe=>xe.selectedTableName),m=p.useEditorStore(xe=>xe.actions.setSelectedConnectionId),g=p.useEditorStore(xe=>xe.actions.setSelectedDatamodelId),b=p.useEditorStore(xe=>xe.actions.setSelectedDatabaseName),x=p.useEditorStore(xe=>xe.actions.setSelectedSchemaName),y=p.useEditorStore(xe=>xe.actions.setSelectedTableName);p.useEditorStore(xe=>xe.actions.setCardSql);const{setQueryConfig:w}=p.useEditorActions();function C(xe){var Ie;if(!s||!xe)return!1;const Ve=((Ie=T==null?void 0:T.capabilities)==null?void 0:Ie.path)||[],Ae=Ve.includes("database"),ke=Ve.includes("schema");return!(!Ve.includes("table")||Ae&&(!d||d==="NA")||ke&&!f)}function N(xe){var Ve;return!s||!xe?!1:!!((Ve=T==null?void 0:T.capabilities)!=null&&Ve.path.includes("database"))}const{refetchConnections:S,connectionsData:j,isConnectionsLoading:_,isConnectionsError:k,selectedConnection:T}=Au(e),{refetch:I,data:E,isLoading:D,isError:R}=Un({queryKey:["models",s],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/datamodels`,(o==null?void 0:o.accessToken)||"",{connection_id:s}),enabled:!!(o!=null&&o.accessToken)&&!!s}),A=T==null?void 0:T.type,F=((Te=T==null?void 0:T.capabilities)==null?void 0:Te.path.includes("schema"))??!1,z=((ze=T==null?void 0:T.capabilities)==null?void 0:ze.path.length)===1&&((Pe=T==null?void 0:T.capabilities)==null?void 0:Pe.path[0])==="table",L=z,{data:$,isLoading:H,isFetching:M,isError:B,refetch:W}=Un({queryKey:["databases",s],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/databases`,(o==null?void 0:o.accessToken)||"",{connection_id:s}),enabled:N(A)}),{data:P,isLoading:G,isFetching:Z,isError:X,refetch:Y}=Un({queryKey:["schemas",s,d],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/schemas`,(o==null?void 0:o.accessToken)||"",{connection_id:s,database_name:d}),enabled:!!s&&!!d&&F&&d!=="NA"}),{data:O,isLoading:q,isFetching:U,isError:V,refetch:K}=Un({queryKey:["tables",s,d,f],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/tables`,(o==null?void 0:o.accessToken)||"",{connection_id:s,database_name:d,schema_name:f}),enabled:C(A)}),{columns:Q,isColumnsLoading:se,isColumnsFetching:oe,isColumnsError:me,refetchColumns:le}=qhe(e);v.useEffect(()=>{z&&(b(""),x(""),g(""),A==="API"&&y("api"))},[A,y,b,x,g,z]);const ue=(T==null?void 0:T.type)==="API"?(He=T==null?void 0:T.type)==null?void 0:He.toLowerCase():h||"",ne=F&&f||"";function de(xe){y(xe),w(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ce(xe){x(xe),y("")}function ce(xe){b(xe==="none"?"":xe),x(""),y(""),xe!=="none"&&xe!==""&&g("")}function ie(xe){m(xe)}function we(xe){g(xe==="none"?"":xe),xe!=="none"&&xe!==""&&b("")}$&&((ye=$==null?void 0:$.databases)==null?void 0:ye.length)>0,P&&((Ke=P==null?void 0:P.schemas)==null?void 0:Ke.length)>0;const fe=j==null?void 0:j.connections.map(xe=>({id:xe.id,name:xe.name,type:xe.type})),ae=(We=E==null?void 0:E.datamodels)==null?void 0:We.map(xe=>({id:xe.id,name:xe.name})),ee=$==null?void 0:$.databases.map(xe=>({id:xe.database_name,name:xe.database_name})),J=P==null?void 0:P.schemas.map(xe=>({id:xe.schema_name,name:xe.schema_name})),re=O==null?void 0:O.tables.map(xe=>({id:xe.table_name,name:xe.table_name})),pe=(Qe=E==null?void 0:E.datamodels.find(xe=>xe.id===c))==null?void 0:Qe.name,Ee=T!=null&&T.capabilities?p.getFormattedTableNameForQuery({schemaName:ne,tableName:ue,modelName:pe,databaseName:d||"",capabilities:T.capabilities}):ue;return{connectionItems:fe,selectedConnectionId:s,selectedConnection:T,isConnectionsLoading:_,isConnectionsError:k,modelItems:ae,selectedDatamodelId:c,selectedDatamodelName:pe,isModelsLoading:D,isModelsError:R,selectedDatabaseName:d,databaseItems:ee,isDatabasesLoadingOrFetching:H||M,isDatabaseError:B,schemaItems:J,selectedSchemaName:f,isSchemaLoadingOrFetching:G||Z,isSchemaError:X,tableItems:re,selectedTableName:h,isTableLoadingOrFetching:q||U,isTableError:V,columns:Q,isColumnsLoadingOrFetching:se||oe,isColumnsError:me,isNonDbConnection:L,connectionType:A,tableName:ue,formattedTableName:Ee,schemaName:ne,refetchConnections:S,refetchModels:I,refetchDatabases:W,refetchSchemas:Y,refetchTables:K,refetchColumns:le,handleConnectionChange:ie,handleDatamodelChange:we,handleDatabaseChange:ce,handleSchemaChange:Ce,handleTableChange:de}}function ZS(e){return`${e}-${dt.v4()}`}function eK(e,t){const n=p.toTitleCase(e.replace(/_/g," "));switch(t){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Oht(e,t){const n=p.toTitleCase(e.replace(/_/g," "));switch(t){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"quarter":return`Quarter of ${n}`;case"year":return`Year of ${n}`;case"hour":return`Hour of ${n}`;case"minute":return`Minute of ${n}`;case"second":return`Second of ${n}`;default:return n}}function Wz(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 Uhe(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Whe(){const e=p.useEditorStore(_=>_.sqlGen),t=p.useEditorStore(_=>_.isDevMode),n=p.useEditorStore(_=>_.card.dataSource),r=p.useEditorStore(_=>{var k,T;return(T=(k=_.card)==null?void 0:k.queryConfig)==null?void 0:T.metricColumns}),{tableName:o,schemaName:s,databaseName:i}=Wz(n),a=Uhe(n),c=p.useEditorStore(_=>_.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:g}=p.useEditorActions(),{modelItems:b,selectedDatamodelName:x}=mT(),{selectedConnection:y}=Au(),w=y==null?void 0:y.capabilities,C=_=>({column_name:_.name,data_type:_.dataType,label:_.label,description:_.description});return{handleDevModeFieldClick:_=>{var T;if(!t)return;const k=C(_);if(t&&a&&o&&w){const I=p.createSqlGenConfig(k,e);m(I);const E=(T=b==null?void 0:b.find(R=>R.id===c))==null?void 0:T.name,D=p.getSql(I,s||"",o,E||"",i||"",w,_.qualifiedEntityName);D&&(f(D),h(!0))}else if(!t){if(p.isTextDataType(k.data_type))if(r&&r.length>0){const I={...k,role:"groupby",id:ZS(k.column_name),name:k.column_name,type:k.data_type};d(I)}else{const I={...k,role:"metric",id:ZS(k.column_name),name:k.column_name,label:eK(k.column_name,"COUNT"),type:k.data_type,aggregate:"COUNT"};u(I)}if(p.isDateDataType(k.data_type)){const I={...k,role:"groupby",id:ZS(k.column_name),name:k.column_name,type:k.data_type,label:Oht(k.column_name,"month"),granularity:"month"};d(I)}if(p.isNumberDataType(k.data_type)){const I={...k,role:"metric",id:ZS(k.column_name),name:k.column_name,label:eK(k.column_name,"SUM"),type:k.data_type,aggregate:"SUM"};u(I)}}},handleShowSample:()=>{if(!a||!o||!w){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=p.getFormattedTableNameForQuery({schemaName:s||"",tableName:o,modelName:x,databaseName:i||"",capabilities:w});g(!1);const T=(y==null?void 0:y.type)==="MSSQL"?`SELECT top 10 * FROM ${_}`:`SELECT * FROM ${_} LIMIT 10`;f(T),h(!0)},handleShowCount:()=>{if(!a||!o||!w){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=p.getFormattedTableNameForQuery({schemaName:s||"",tableName:o,modelName:x,databaseName:i||"",capabilities:w});f(`SELECT COUNT(*) as count FROM ${_}`),h(!0)},isNumberField:_=>p.isNumberDataType(_.dataType)}}function Khe(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(s=>p.fmt(s)).join("."),o=p.fmt(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:o}}function Kz(e){const t=e;return{id:e.id,name:e.name,qualifiedFieldName:e.qualifiedFieldName,qualifiedEntityName:e.qualifiedEntityName,entityName:e.entityName,entityId:e.entityId,entityType:e.entityType,dataType:e.dataType,role:e.role,fieldScope:e.fieldScope,expression:t.expression,calculatedFormula:t.calculatedFormula}}function Gz(e,t){if(!(!e&&!t))return{semanticDomainId:e==null?void 0:e.semanticDomainId,selectedEntities:(e==null?void 0:e.selectedEntities)||[],connectionId:(e==null?void 0:e.connectionId)||(t==null?void 0:t.connectionId),connectionType:(e==null?void 0:e.connectionType)||(t==null?void 0:t.connectionType)}}function tK(e){var t,n;return e?!!(e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function nK(e){return e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e}function rb(e,t){var b,x,y,w,C,N,S;if(!e.fieldMeta)return e.column===t.qualifiedFieldName||e.column===t.name;const n=nK((b=e.fieldMeta)==null?void 0:b.id),r=nK(t.id),o=((x=e.fieldMeta)==null?void 0:x.qualifiedFieldName)||e.column,s=o===t.qualifiedFieldName||o===t.name,i=(y=e.fieldMeta)==null?void 0:y.qualifiedEntityName,a=!i||!t.qualifiedEntityName||i===t.qualifiedEntityName,c=(w=e.fieldMeta)==null?void 0:w.entityId,u=!c||!t.entityId||c===t.entityId,d=(C=e.fieldMeta)==null?void 0:C.fieldScope;if(d&&t.fieldScope&&d!==t.fieldScope)return!1;const f=(N=e.fieldMeta)==null?void 0:N.role;if(f&&t.role&&f!==t.role)return!1;const h=tK(e.fieldMeta)||tK(t);if(h&&n&&r&&n===r)return!0;if(!h&&(!a||!u))return!1;const m=(S=e.fieldMeta)==null?void 0:S.expression,g=t.expression;return m||g?s&&a&&u&&m===g:s&&a&&u}function Lht(){const e=p.useDashboardStore(c=>c.dashboard.filters)||[],t=p.useDashboardStore(c=>c.selectedSheetId),n=p.useDashboardStore(c=>c.actions.addFilter),r=p.useDashboardStore(c=>c.actions.removeFilter),{removeFilterValues:o}=p.useDashboardActions(),s=p.useEditorStore(c=>c.card.dataSource),{selectedConnection:i}=Au();function a(c,u="sheet"){const{qualifiedColumnName:d,qualifiedTableName:f}=Khe(c);let h;if(u==="sheet"&&t){const m=pf(e,t);h=m.find(g=>g.fieldMeta&&rb(g,c))||zTe(m.filter(g=>!g.fieldMeta),d,f,t)}else h=e==null?void 0:e.find(m=>rb(m,c)||!m.fieldMeta&&Lg(m.column)===Lg(d));if(h)o(h.id),r(h.id);else{const m=dt.v4(),g=Kz(c),b=Gz(s,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),x=u==="sheet"&&t?[t]:void 0,y=p.getDataType(c.dataType)==="date"?"between":"in";return n({id:m,location:u,column:d,title:c.label||c.name,dataType:c.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:y,applyToSheetIds:x,sql:"",fieldMeta:g,semanticContext:b}),m}}return{assignFilter:a}}function $ht({column:e}){const[t,n]=v.useState(!1),r=p.useEditorStore(C=>C.isDevMode),o=p.useEditorStore(C=>C.card.dataSource),{tableName:s,schemaName:i,databaseName:a}=Wz(o),c=p.useEditorStore(C=>C.selectedDatamodelId),u=p.useEditorStore(C=>C.sqlGen),{modelItems:d,selectedConnection:f}=mT(),h=f==null?void 0:f.capabilities,m=p.useEditorStore(C=>C.actions.setSqlGen),g=p.useEditorStore(C=>C.actions.setCardSql),b=p.useEditorStore(C=>C.actions.setRunSql),x=Uhe(o);function y(C,N){var T,I;if(!x||!s){console.warn("Cannot generate SQL: missing table metadata");return}const S=p.createSqlGenConfig(C,u,N),j=(T=d==null?void 0:d.find(E=>E.id===c))==null?void 0:T.name;if(m(S),!h){console.warn("Cannot generate SQL: missing connection capabilities");return}const _=(I=C.qualifiedFieldName)==null?void 0:I.split(".").slice(0,-1).join("."),k=p.getSql(S,i||"",s,j||"",a||"",h,_);k&&(g(k),b(!0)),n(!1)}function w(){return l.jsxs("ul",{className:"text-xs",children:[l.jsx("li",{onClick:()=>y(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),l.jsx("li",{onClick:()=>y(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),l.jsx("li",{onClick:()=>y(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),l.jsx("li",{onClick:()=>y(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),l.jsx("li",{onClick:()=>y(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return!r||!x?null:l.jsxs(Xm,{openDelay:0,open:t,onOpenChange:n,children:[l.jsx(Yd,{asChild:!0,children:l.jsx(Rm,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),l.jsx(bu,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:w()})]})}const rK="bg-emerald-500/90 text-white",zht="bg-blue-500/90 text-white";function Yz(e){const t=rf(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:rK}:{label:"fx",badgeClassName:e.role==="metric"?rK:zht}}function Bht(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),"prefix"in e&&e.prefix&&t.push({label:"Prefix",value:e.prefix}),"suffix"in e&&e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="temporal_bucket")return t.push({label:"Presentation",value:e.presentation.mode}),t;if(e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const o=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:o})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function Vht(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,o)=>{const s=t[Number(o)];return s?`{${s.name||s.label}}`:r}):e.expression}function Hht({field:e,fieldState:t}){var s;const n=Vht(e),r=Bht(((s=e.semanticTemporalPresentation)==null?void 0:s.format)??e.format),o=!!Yz(e);return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-start gap-1.5 px-3 pt-2.5",children:[l.jsx("span",{className:"flex h-[18px] shrink-0 items-center",children:l.jsx(Yw,{dataType:e.dataType,calculated:o})}),l.jsx("p",{className:"min-w-0 flex-1 break-words text-[13px] font-semibold leading-[18px] text-foreground",children:e.label||e.name})]}),l.jsx("div",{className:"px-3 pb-2 pt-0.5",children:l.jsx("code",{className:"font-mono text-[11px] text-muted-foreground",children:e.dataType})}),e.description&&l.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[12px] leading-[1.55] text-muted-foreground",children:e.description}),n&&l.jsxs("div",{className:"border-t border-border/60 bg-muted/40 px-3 py-2",children:[l.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Expression"}),l.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-[11px] leading-[1.55] text-foreground/90",children:n})]}),r.length>0&&l.jsxs("div",{className:"border-t border-border/60 px-3 py-2",children:[l.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Format"}),l.jsx("dl",{className:"grid grid-cols-[64px_1fr] gap-x-3 gap-y-1 text-[11px]",children:r.map(i=>l.jsxs("div",{className:"contents",children:[l.jsx("dt",{className:"font-medium uppercase tracking-[0.08em] text-muted-foreground",children:i.label}),l.jsx("dd",{className:"truncate font-mono tabular-nums text-foreground/90",children:i.value})]},`${i.label}-${i.value}`))})]}),t&&t.tooltip&&l.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[11px] text-muted-foreground",children:t.tooltip}),l.jsx("div",{className:"border-t border-border/60 px-3 py-2",children:l.jsx("code",{className:"block break-all font-mono text-[11px] leading-[1.45] text-muted-foreground",children:e.name})})]})}function oK({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:o,actions:s,onHover:i}){const a=p.useEditorStore(U=>U.isDevMode),c=t==="inline-filter"||t==="document-filter",u=t==="filter"||c,d=a||u||(n==null?void 0:n.state)==="unreachable"&&!u,f=p.useDashboardStore(U=>U.dashboard.filters),h=p.useDashboardStore(U=>U.selectedSheetId),m=p.useDashboardStore(U=>U.actions.removeFilter),{removeFilterValues:g}=p.useDashboardActions(),{assignFilter:b}=Lht(),x=t==="filter"?pf(f,h):f,y=t==="filter"?x==null?void 0:x.find(U=>{if(rb(U,e))return!0;if(U.fieldMeta)return!1;const V=Lg(U.column||""),K=Lg(e.name);return V.endsWith(`.${K}`)||V===K}):void 0,w=!!y,C=c&&(o==null?void 0:o.some(U=>rb(U,e))),N=w||C,S=y&&u?f==null?void 0:f.find(U=>U.id===y.id):void 0,j=S&&(S.applyToSheetIds&&S.applyToSheetIds.length>1||S.excludeSheetIds&&S.excludeSheetIds.length>0||!S.applyToSheetIds&&!S.excludeSheetIds&&!S.sheetId),[_,k]=v.useState(!1),[,T]=v.useState(null),{attributes:I,listeners:E,setNodeRef:D,transform:R,transition:A,isDragging:F}=tx({id:e.id,disabled:d}),z=p.useEditorStore(U=>U.card),{handleFieldClick:L}=Hhe(z),{handleDevModeFieldClick:$,isNumberField:H}=Whe(),M=()=>{S&&(console.log("[SourceField] Removing multi-sheet filter:",S.id),g(S.id),m(S.id)),T(null),k(!1)},B=()=>{if(c&&r){r(e);return}t==="filter"?N&&j?(T(e),k(!0)):b(e,"sheet"):a?$(e):L(e)},W={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},P={transform:Ki.Transform.toString(R),transition:A};function G(U){return U==="domain"?{label:"Semantic domain",Icon:Dve}:U==="sheet"?{label:"Sheet",Icon:em}:U==="dashboard"?{label:"Dashboard",Icon:em}:{label:"Card",Icon:MO}}const Z=Yz(e),X=e.fieldScope,Y=X&&!Z?G(X):null,O=(n==null?void 0:n.state)==="unreachable",q=(n==null?void 0:n.state)==="indirect";return l.jsxs(l.Fragment,{children:[l.jsx(Lhe,{ref:D,style:P,...d?{}:I,...d?{}:E,onClick:B,onMouseEnter:U=>i==null?void 0:i(!0,U.currentTarget),onMouseLeave:()=>i==null?void 0:i(!1),title:n==null?void 0:n.tooltip,selected:w,dragging:F,disableHover:O,inQuery:!u&&!!(n!=null&&n.isSelected),icon:l.jsx(Yw,{dataType:e.dataType,calculated:!!Z}),label:e.label||e.name,trailing:l.jsxs(l.Fragment,{children:[a&&!u&&H(e)&&l.jsx("span",{onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),children:l.jsx($ht,{column:W})}),s?l.jsx("span",{className:"pointer-events-none inline-flex items-center opacity-0 transition-opacity group-hover/field-row:pointer-events-auto group-hover/field-row:opacity-100 group-focus-within/field-row:pointer-events-auto group-focus-within/field-row:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),children:s}):t==="editor"?l.jsxs(Uo,{children:[l.jsx(Wo,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Field actions",onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),className:"pointer-events-none inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:pointer-events-auto group-hover/field-row:opacity-100 group-focus-within/field-row:pointer-events-auto group-focus-within/field-row:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100",children:l.jsx(Ci,{className:"h-3 w-3"})})}),l.jsx(Do,{align:"end",className:"w-44",children:l.jsx(kn,{onClick:U=>{U.stopPropagation(),navigator.clipboard.writeText(e.name).then(()=>{lt.success(`Copied "${e.name}"`)}).catch(()=>{lt.error("Could not copy field name")})},children:"Copy field name"})})]}):null,t==="editor"&&Y&&l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx("span",{"aria-label":`${Y.label} calculated field`,className:"inline-flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground/70 transition-colors hover:text-foreground",onClick:U=>U.stopPropagation(),onPointerDown:U=>U.stopPropagation(),children:l.jsx(Y.Icon,{className:"h-3 w-3"})})}),l.jsxs(p.TooltipContent,{side:"top",align:"end",children:[Y.label," calculated field"]})]})]}),className:p.cn((a||u)&&"cursor-pointer",!d&&!a&&!u&&"cursor-grab active:cursor-grabbing",O&&"cursor-not-allowed opacity-50",q&&"text-muted-foreground/80",C&&"bg-primary/10 hover:bg-primary/15")}),l.jsx(ff,{open:_,onOpenChange:k,children:l.jsxs(ku,{children:[l.jsxs(_u,{children:[l.jsx(Tu,{children:"Remove Filter from Multiple Sheets?"}),l.jsx(Eu,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),l.jsxs(Iu,{children:[l.jsx(Mu,{children:"Cancel"}),l.jsx(Du,{onClick:M,children:"Remove Filter"})]})]})})]})}var bl="Accordion",qht=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[Zz,Uht,Wht]=p.createCollection(bl),[pT]=p.createContextScope(bl,[Wht,fue]),Xz=fue(),Ghe=v.forwardRef((e,t)=>{const{type:n,...r}=e,o=r,s=r;return l.jsx(Zz.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?l.jsx(Zht,{...s,ref:t}):l.jsx(Yht,{...o,ref:t})})});Ghe.displayName=bl;var[Yhe,Kht]=pT(bl),[Zhe,Ght]=pT(bl,{collapsible:!1}),Yht=v.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:o=()=>{},collapsible:s=!1,...i}=e,[a,c]=p.useControllableState({prop:n,defaultProp:r??"",onChange:o,caller:bl});return l.jsx(Yhe,{scope:e.__scopeAccordion,value:v.useMemo(()=>a?[a]:[],[a]),onItemOpen:c,onItemClose:v.useCallback(()=>s&&c(""),[s,c]),children:l.jsx(Zhe,{scope:e.__scopeAccordion,collapsible:s,children:l.jsx(Xhe,{...i,ref:t})})})}),Zht=v.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:o=()=>{},...s}=e,[i,a]=p.useControllableState({prop:n,defaultProp:r??[],onChange:o,caller:bl}),c=v.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=v.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return l.jsx(Yhe,{scope:e.__scopeAccordion,value:i,onItemOpen:c,onItemClose:u,children:l.jsx(Zhe,{scope:e.__scopeAccordion,collapsible:!0,children:l.jsx(Xhe,{...s,ref:t})})})}),[Xht,gT]=pT(bl),Xhe=v.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:o,orientation:s="vertical",...i}=e,a=v.useRef(null),c=p.useComposedRefs(a,t),u=Uht(n),f=p.useDirection(o)==="ltr",h=p.composeEventHandlers(e.onKeyDown,m=>{var k;if(!qht.includes(m.key))return;const g=m.target,b=u().filter(T=>{var I;return!((I=T.ref.current)!=null&&I.disabled)}),x=b.findIndex(T=>T.ref.current===g),y=b.length;if(x===-1)return;m.preventDefault();let w=x;const C=0,N=y-1,S=()=>{w=x+1,w>N&&(w=C)},j=()=>{w=x-1,w<C&&(w=N)};switch(m.key){case"Home":w=C;break;case"End":w=N;break;case"ArrowRight":s==="horizontal"&&(f?S():j());break;case"ArrowDown":s==="vertical"&&S();break;case"ArrowLeft":s==="horizontal"&&(f?j():S());break;case"ArrowUp":s==="vertical"&&j();break}const _=w%y;(k=b[_].ref.current)==null||k.focus()});return l.jsx(Xht,{scope:n,disabled:r,direction:o,orientation:s,children:l.jsx(Zz.Slot,{scope:n,children:l.jsx(p.Primitive.div,{...i,"data-orientation":s,ref:c,onKeyDown:r?void 0:h})})})}),lk="AccordionItem",[Qht,Qz]=pT(lk),Qhe=v.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...o}=e,s=gT(lk,n),i=Kht(lk,n),a=Xz(n),c=p.useId(),u=r&&i.value.includes(r)||!1,d=s.disabled||e.disabled;return l.jsx(Qht,{scope:n,open:u,disabled:d,triggerId:c,children:l.jsx(pue,{"data-orientation":s.orientation,"data-state":ome(u),...a,...o,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Qhe.displayName=lk;var Jhe="AccordionHeader",eme=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,o=gT(bl,n),s=Qz(Jhe,n);return l.jsx(p.Primitive.h3,{"data-orientation":o.orientation,"data-state":ome(s.open),"data-disabled":s.disabled?"":void 0,...r,ref:t})});eme.displayName=Jhe;var kF="AccordionTrigger",tme=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,o=gT(bl,n),s=Qz(kF,n),i=Ght(kF,n),a=Xz(n);return l.jsx(Zz.ItemSlot,{scope:n,children:l.jsx(vJe,{"aria-disabled":s.open&&!i.collapsible||void 0,"data-orientation":o.orientation,id:s.triggerId,...a,...r,ref:t})})});tme.displayName=kF;var nme="AccordionContent",rme=v.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,o=gT(bl,n),s=Qz(nme,n),i=Xz(n);return l.jsx(wJe,{role:"region","aria-labelledby":s.triggerId,"data-orientation":o.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}})});rme.displayName=nme;function ome(e){return e?"open":"closed"}var Jht=Ghe,emt=Qhe,tmt=eme,sme=tme,ime=rme;const Jz=Jht,fv=te.forwardRef(({className:e,...t},n)=>l.jsx(emt,{ref:n,className:p.cn("border-b",e),...t}));fv.displayName="AccordionItem";const hv=te.forwardRef(({className:e,children:t,...n},r)=>l.jsx(tmt,{className:"flex",children:l.jsxs(sme,{ref:r,className:p.cn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,l.jsx(je.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));hv.displayName=sme.displayName;const mv=te.forwardRef(({className:e,children:t,...n},r)=>l.jsx(ime,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:l.jsx("div",{className:p.cn("pb-4 pt-0",e),children:t})}));mv.displayName=ime.displayName;let ame=(e=21)=>crypto.getRandomValues(new Uint8Array(e)).reduce((t,n)=>(n&=63,n<36?t+=n.toString(36):n<62?t+=(n-26).toString(36).toUpperCase():n>62?t+="-":t+="_",t),"");const bT=[{id:"sum",label:"Sum",symbol:"+",description:"Add two metrics together",template:()=>"({field_0} + {field_1})",insertTemplate:()=>"({a} + {b})",insertHint:"A + B",requiresTwoInputs:!0},{id:"difference",label:"Difference",symbol:"−",description:"Subtract one metric from another",template:()=>"({field_0} - {field_1})",insertTemplate:()=>"({a} - {b})",insertHint:"A − B",requiresTwoInputs:!0},{id:"product",label:"Product",symbol:"×",description:"Multiply two metrics",template:()=>"({field_0} * {field_1})",insertTemplate:()=>"({a} * {b})",insertHint:"A × B",requiresTwoInputs:!0},{id:"ratio",label:"Ratio",symbol:"÷",description:"Divide one metric by another",template:()=>"({field_0} / NULLIF({field_1}, 0))",insertTemplate:()=>"({a} / NULLIF({b}, 0))",insertHint:"A ÷ B (null-safe)",requiresTwoInputs:!0},{id:"change",label:"Change",symbol:"Δ",description:"Calculate percentage change from A to B",template:()=>"(({field_1} - {field_0}) / NULLIF({field_0}, 0))",insertTemplate:()=>"(({b} - {a}) / NULLIF({a}, 0))",insertHint:"% change A → B",requiresTwoInputs:!0},{id:"percentage",label:"Percentage",symbol:"%",description:"Calculate (A / B) × 100",template:()=>"(({field_0} / NULLIF({field_1}, 0)) * 100)",insertTemplate:()=>"(({a} / NULLIF({b}, 0)) * 100)",insertHint:"(A ÷ B) × 100",requiresTwoInputs:!0},{id:"scale",label:"Scale",symbol:"×n",description:"Multiply a metric by a constant factor",template:()=>"({field_0} * {constant})",insertTemplate:()=>"({a} * 1.0)",insertHint:"A × constant",requiresTwoInputs:!1},{id:"custom",label:"Custom Expression",symbol:"{}",description:"Drag fields to create custom expression with tokens",requiresTwoInputs:!1,allowsCustomExpression:!0}],nmt=bT.filter(e=>e.id!=="custom"&&!!e.insertTemplate),e4=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),ck=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function lme(e,t){e.forEach(n=>{var i;const r=n.id||n.qualifiedFieldName||n.name;if(r&&t.visited.has(r))return;if(r&&t.visited.add(r),Rhe(n)){t.disqualified=!0;return}const o=(i=n.calculatedFormula)==null?void 0:i.inputFields;if(o!=null&&o.length){lme(o,t);return}if(n.expression&&!(rf(n)==="inline_expression"&&Qa(n)&&n.fieldScope==="domain")){t.disqualified=!0;return}if(!n.entityName||!n.entityId){t.disqualified=!0;return}const s=n.qualifiedEntityName||n.entityId||n.entityName;t.entities.has(s)||t.entities.set(s,{entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName})})}function t4(e){const t={entities:new Map,disqualified:!1,visited:new Set};if(lme(e,t),t.disqualified||t.entities.size!==1)return{kind:"multi-entity"};const[n]=Array.from(t.entities.values());return!(n!=null&&n.entityName)||!n.entityId?{kind:"multi-entity"}:{kind:"inline",entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName}}const sK="calculated_fields";function rmt(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function omt(e){return e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===sK||e.qualifiedEntityName===sK||rmt(e.id)}function smt(e){return e.aggregate?e.aggregate:YL(e.dataType)}function imt(e,t){const n=smt(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function amt(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const o=Number(r),s=t[o];return!s||omt(s)||typeof s.expression=="string"&&Bre(s.expression)?n:imt(n,s)})}function lmt(e,t,n,r,o,s,i,a,c,u){if(!bT.find(w=>w.id===t))throw new Error(`Unknown operation: ${t}`);let f,h=[],m;{if(!(a!=null&&a.trim()))throw new Error("Custom expression is required");f=a.trim(),h=u||[]}const g={operation:t,inputFields:h,...m!==void 0},b=e4(e),x=t4(h);return{id:i||`calc_${ame(10)}`,name:b,label:e,alias:b,qualifiedFieldName:b,dataType:"number",role:"metric",expression:f,calculatedFormula:g,entityId:x.kind==="inline"?x.entityId:s,entityName:x.kind==="inline"?x.entityName:xr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:x.kind==="inline"?x.qualifiedEntityName:void 0,entityType:x.kind==="inline"?"dataset":"table",description:`Calculated field: ${e}`}}function cmt(e){var r,o;const t=bT.find(s=>s.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const s=((r=e.inputFields[0])==null?void 0:r.label)||((o=e.inputFields[0])==null?void 0:o.name)||"A",i=e.constant??1;return`${s} × ${i}`}return e.inputFields.map(s=>s.label||s.name).join(` ${t.symbol} `)}function umt(e,t,n,r,o,s){const i=e4(e),a=t4(n);return Vre({id:s||`calc_dim_${ame(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(c=>c.role==="metric"?{...c,role:"metric"}:{...c,role:"groupby"})},entityId:a.kind==="inline"?a.entityId:o,entityName:a.kind==="inline"?a.entityName:xr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:a.kind==="inline"?a.qualifiedEntityName:void 0,entityType:a.kind==="inline"?"dataset":"table",description:`Calculated field: ${e.trim()}`})}function cme(e){return e==="metric"?"Calculated Metric":"Calculated Column"}function dmt(e){return e==="inline"?"Single dataset":"Cross-entity"}function yy(e){switch(e){case"card":return"This card";case"sheet":return"This sheet";case"dashboard":return"This dashboard";case"domain":return"Semantic domain"}}function iK(e){return e.replace(/\s+/g,"")}function fmt(e){var o;const t=e.calculatedFormula;if(!t||t.operation==="custom")return;const n=bT.find(s=>s.id===t.operation),r=(o=n==null?void 0:n.template)==null?void 0:o.call(n);if(r)return t.operation!=="scale"?r:r.replace("{constant}",String(t.constant??1))}function hmt(e){var r;const t=e.expression||"",n=fmt(e);return!n||iK(t)!==iK(n)?t:amt(t,((r=e.calculatedFormula)==null?void 0:r.inputFields)||[])}function mmt(e){const t=new Set,n=/\{field_(\d+)\}/g;let r=n.exec(e);for(;r;)t.add(Number(r[1])),r=n.exec(e);return[...t].sort((o,s)=>o-s)}function pmt(e){var s;const t=e.expression||"",n=mmt(t);if(n.length===0)return{readOnly:!1};const r=((s=e.calculatedFormula)==null?void 0:s.inputFields)||[];return n[n.length-1]<r.length?{readOnly:!1}:{readOnly:!0,reason:"This legacy metric uses saved field tokens but is missing the input metadata needed to reopen it safely. It can be viewed, but editing is disabled to avoid changing query semantics."}}function gmt(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function bmt(e){var r;const t=new Map;return(((r=e==null?void 0:e.calculatedFormula)==null?void 0:r.inputFields)||[]).forEach(o=>{const s=ck(o.id);s&&t.set(s,o),o.qualifiedFieldName&&t.set(o.qualifiedFieldName,o),o.name&&t.set(o.name,o)}),t}function xmt(e,t){const n=ck(e.id);return n&&t.get(n)||e.qualifiedFieldName&&t.get(e.qualifiedFieldName)||t.get(e.name)}function ymt(e){const t=YL(e.dataType);if(e.role==="metric"){const n=e;return n.aggregate||n.expression||n.calculatedFormula?n:{...n,aggregate:t}}return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}}function vmt(e,t){const n=bmt(t);return e.map(r=>{const o=xmt(r,n);return(o==null?void 0:o.role)==="metric"?o:ymt(r)})}function wmt({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:o,targetQualifiedEntityName:s}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=rf(i);if(r==="inline"){const c=p.getCalculatedFieldNamespace(i),u=s||o;return a==="inline_expression"&&!!u&&c===u}return a==="domain_calculated"})}function Cmt({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const o=r.length>0?r:["dimension","metric"],s=["dimension","metric"].filter(c=>o.includes(c)),i=n||s.length<=1,a=s.includes(e)?e:s[0];return l.jsx(p.Tabs,{value:a,onValueChange:c=>t(c),className:"w-fit shrink-0",children:l.jsx(p.TabsList,{size:"xs",children:s.map(c=>l.jsx(p.TabsTrigger,{value:c,disabled:i,children:cme(c)},c))})})}const n4=te.forwardRef(({className:e,sideOffset:t=8,...n},r)=>l.jsx(p.Portal$2,{children:l.jsx(Kb,{children:l.jsx(p.Content2$1,{ref:r,sideOffset:t,className:p.cn("z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n})})}));n4.displayName="ValidationTooltipContent";const ume=p.Arrow2$1;function l2(e,t){return`${e} ${t}${e===1?"":"s"}`}function Smt({result:e}){const t=e.errors.length>0,n=l2(e.tokens.length,"token"),r=e.errors.length>0?l2(e.errors.length,"error"):null,o=e.warnings.length>0?l2(e.warnings.length,"warning"):null,s=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
|
|
1294
1294
|
`);return l.jsxs(p.Tooltip,{delayDuration:120,children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":t?"Validation failed. Hover to view details.":"Validation passed. Hover to view details.",className:p.cn("inline-flex h-5 w-5 items-center justify-center rounded-full transition-colors",t?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-emerald-600 text-white hover:bg-emerald-700"),children:t?l.jsx(je.X,{className:"h-3 w-3","aria-hidden":!0}):l.jsx(p.Check,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(n4,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[l.jsxs("div",{className:"space-y-2.5 p-3 text-xs",children:[l.jsx("div",{className:p.cn("font-semibold",t?"text-destructive":"text-emerald-700"),children:t?"Validation failed":"Validation passed"}),l.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:n}),r&&l.jsx("span",{children:r}),o&&l.jsx("span",{children:o}),e.inferredDataType&&l.jsxs("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&l.jsxs("div",{className:"space-y-1.5 border-t pt-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),l.jsx("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((i,a)=>l.jsxs("div",{className:"flex items-start gap-1.5",children:[l.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${i.token}}`}),l.jsx(Bv,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),i.field?l.jsx("span",{className:"break-all text-muted-foreground",children:i.field.qualifiedFieldName||i.field.name}):l.jsx("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${i.token}-${a}`))})]}),e.errors.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),l.jsx(Pd,{text:s,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.warnings.length>0&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),l.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-amber-700 select-text",children:e.warnings.map((i,a)=>l.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.inferredDataType&&l.jsxs("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),l.jsx(ume,{className:"fill-popover"})]})]})}function Nmt({onValidate:e,isValidating:t,validationResult:n,error:r,disabled:o}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:e,disabled:t||o,className:"text-[11px]",children:t?"Validating…":"Validate"}),n&&l.jsx(Smt,{result:n}),!n&&r&&l.jsxs(p.Tooltip,{delayDuration:120,children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Validation failed. Hover to view details.",className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90",children:l.jsx(je.X,{className:"h-3 w-3","aria-hidden":!0})})}),l.jsxs(n4,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-semibold text-destructive",children:"Validation failed"}),l.jsx(Pd,{text:r,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),l.jsx("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:r})]}),l.jsx(ume,{className:"fill-popover"})]})]})]})}const jmt={metric:["Average revenue per order","Profit margin %","Active customers last 30 days"],dimension:["Order month from created_at","Bucket revenue into 'Large' / 'Small'","Country and state combined"]};function kmt({mode:e,fieldType:t,prompt:n,onPromptChange:r,generated:o,explanation:s,isGenerating:i,error:a,onGenerate:c,onTryAgain:u,onCancel:d,onUseDraft:f,disabled:h}){const m=e==="result",g=e==="loading"||i,b=jmt[t],x=t==="metric"?"e.g. average revenue per order, in dollars":"e.g. bucket orders into 'Large' / 'Small' by amount";return l.jsxs("div",{"data-testid":"ai-compose-panel","data-mode":e,className:"rounded-[6px] border border-blue-200 bg-blue-50/40 dark:border-blue-900/40 dark:bg-blue-950/20",children:[l.jsxs("div",{className:"flex items-center gap-2 border-b border-blue-200/60 px-3 py-2 dark:border-blue-900/30",children:[l.jsx(p0,{className:"h-3 w-3 text-blue-600 dark:text-blue-400","aria-hidden":!0}),l.jsx("span",{className:"text-[11px] font-medium text-zinc-900 dark:text-zinc-100",children:m?"AI draft — ready to use":"Compose with AI"}),l.jsx("span",{className:"text-[10px] text-zinc-500 dark:text-zinc-400",children:m?"Review before using.":"Describe in plain English. AI knows your fields."}),l.jsx("button",{type:"button","aria-label":"Close AI compose",onClick:d,disabled:h,className:"ml-auto text-blue-700/70 hover:text-blue-900 disabled:opacity-50 dark:text-blue-300/70 dark:hover:text-blue-100",children:l.jsx(je.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"space-y-2 p-3",children:m?l.jsxs(l.Fragment,{children:[n.trim()&&l.jsxs("div",{className:"flex items-start gap-1.5 rounded-[4px] bg-white px-2 py-1.5 text-[11px] dark:bg-zinc-950",children:[l.jsx("span",{className:"shrink-0 text-zinc-400",children:"›"}),l.jsxs("span",{className:"italic text-zinc-600 dark:text-zinc-400",children:["“",n.trim(),"”"]})]}),l.jsx("div",{className:"overflow-hidden rounded-[5px] border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950",children:l.jsx("div",{className:"max-h-[180px]",children:l.jsx(p.CodeEditor,{value:o,language:"sql-jinja",readOnly:!0,embedded:!0,hideLineNumbers:!0,dense:!0,ariaLabel:"Generated expression"})})}),s?l.jsx("p",{className:"text-[11px] text-zinc-500 dark:text-zinc-400",children:s}):null]}):l.jsxs(l.Fragment,{children:[l.jsx(p.Label,{htmlFor:"ai-compose-prompt",className:"sr-only",children:"Describe what you want to calculate"}),l.jsx(zm,{id:"ai-compose-prompt",value:n,onChange:y=>r(y.target.value),placeholder:x,rows:2,disabled:g||h,className:"resize-none border-zinc-200 bg-white text-[13px] text-zinc-900 shadow-none placeholder:text-zinc-400 focus:border-zinc-400 focus-visible:ring-0 disabled:opacity-60 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50"}),!g&&l.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[l.jsx("span",{className:"mr-1 text-[10px] uppercase tracking-[0.08em] text-zinc-400",children:"Try"}),b.map(y=>l.jsx("button",{type:"button",onClick:()=>r(y),disabled:h,className:"inline-flex h-5 items-center rounded-[4px] border border-zinc-200 bg-white px-1.5 text-[11px] text-zinc-600 hover:bg-zinc-50 hover:text-zinc-900 disabled:opacity-50 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-400 dark:hover:bg-zinc-900 dark:hover:text-zinc-100",children:y},y))]}),a&&l.jsx("p",{className:"whitespace-pre-wrap text-[11px] text-destructive",children:a})]})}),l.jsx("div",{className:"flex items-center justify-end gap-1.5 border-t border-blue-200/60 px-3 py-2 dark:border-blue-900/30",children:m?l.jsxs(l.Fragment,{children:[l.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:u,disabled:h,children:"Try again"}),l.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:d,disabled:h,children:"Cancel"}),l.jsx(p.Button,{type:"button",size:"xs",onClick:f,disabled:h||!o.trim(),children:"Use draft"})]}):l.jsxs(l.Fragment,{children:[l.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:d,disabled:h,children:"Cancel"}),l.jsx(p.Button,{type:"button",size:"xs",onClick:c,disabled:g||h||!n.trim(),className:p.cn("gap-1.5",g&&"pointer-events-none"),children:g?l.jsxs(l.Fragment,{children:[l.jsx(p.LoaderCircle,{className:"h-3 w-3 animate-spin","aria-hidden":!0}),"Generating…"]}):l.jsxs(l.Fragment,{children:[l.jsx(p0,{className:"h-3 w-3","aria-hidden":!0}),"Generate"]})})]})})]})}function _mt({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:o,disabled:s}){const i=new Set(o||[]),a=e.length>0||t.length>0,c=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),g=h.toLowerCase();return m.startsWith(`${g}.`)?f.slice(h.length+1):f},d=(f,h)=>{const g=(f.name||f.baseLabel||f.label||f.tokenLabel||"").trim(),b=[h,f.qualifiedEntityName,f.entityName].filter(Boolean);for(const x of b){const y=u(g,x);if(y!==g)return y}return g.includes(".")&&g.split(".").pop()||g};return l.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2",children:[a&&l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[l.jsx(Ft.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("input",{type:"text",value:t,onChange:f=>n(f.target.value),placeholder:"Search fields",className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),t&&l.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>n(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(je.X,{className:"h-3 w-3"})})]}),l.jsx(hl,{className:"min-h-0 flex-1",children:e.length===0?l.jsx("div",{className:"rounded-[5px] border border-dashed border-border px-3 py-6 text-center text-[12px] text-muted-foreground",children:"No fields match your search."}):l.jsx(Jz,{type:"multiple",defaultValue:c,className:"space-y-1",children:e.map(f=>l.jsxs(fv,{value:f.id,className:"border-none",children:[l.jsx(hv,{className:"group flex w-full items-center gap-1.5 rounded-[4px] px-1.5 py-1.5 text-left hover:bg-muted hover:no-underline [&>svg]:order-first [&>svg]:h-3 [&>svg]:w-3 [&>svg]:-rotate-90 [&>svg]:text-muted-foreground/70 data-[state=open]:[&>svg]:rotate-90",children:l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l.jsx("span",{className:"max-w-[180px] truncate text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:f.label}),l.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:f.fields.length})]})}),l.jsx(mv,{className:"pb-1",children:l.jsx("div",{children:f.fields.map(h=>{const m=i.has(h.id),g=!h.isCompatible||s,b=d(h,f.label);return l.jsx(Lhe,{asButton:!0,disabled:g,icon:l.jsx(Yw,{dataType:h.dataType,calculated:h.isCalculated}),label:b,selected:m,disableHover:g,onClick:()=>{r(h)},className:p.cn(g?"cursor-not-allowed opacity-50":"cursor-pointer"),trailing:m?l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Selected"}):void 0},h.id)})})})]},f.id))})})]})}function Imt({groups:e,searchTerm:t,onSearchTermChange:n,onFieldSelect:r,selectedFieldIds:o,disabled:s}){const[i,a]=v.useState(!1);return l.jsxs(p.Popover,{open:i,onOpenChange:a,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsxs(p.Button,{type:"button",variant:"outline",size:"xs",disabled:s,className:"gap-1.5",children:[l.jsx(Tr,{className:"h-3 w-3","aria-hidden":!0}),"Insert field"]})}),l.jsx(p.PopoverContent,{align:"end",sideOffset:6,className:"z-[51] w-[320px] max-w-[min(320px,calc(100vw-32px))] p-2",children:l.jsx("div",{className:"flex h-[360px] min-h-0 flex-col",children:l.jsx(_mt,{groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:c=>{r(c),a(!1)},selectedFieldIds:o,disabled:s})})})]})}function Tmt({onInsert:e,disabled:t}){return l.jsxs(Uo,{children:[l.jsx(Wo,{asChild:!0,children:l.jsxs(p.Button,{type:"button",variant:"outline",size:"xs",disabled:t,className:"gap-1.5",children:["Templates",l.jsx(je.ChevronDown,{className:"h-3 w-3","aria-hidden":!0})]})}),l.jsx(Do,{align:"end",className:"w-[300px]",children:nmt.map(n=>{var r;return l.jsxs(kn,{onSelect:o=>{var i;o.preventDefault();const s=(i=n.insertTemplate)==null?void 0:i.call(n);s&&e(s)},className:"flex items-start justify-between gap-3 py-2",children:[l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"font-mono text-[12px] text-muted-foreground",children:n.symbol}),l.jsx("span",{className:"text-[12px] font-medium",children:n.label})]}),l.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-muted-foreground",children:(r=n.insertTemplate)==null?void 0:r.call(n)})]}),n.insertHint?l.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:n.insertHint}):null]},n.id)})})]})}const Emt="Calculated fields";function Dmt(e){var t;if(e.kind==="inline"){const n=(t=e.entityName)==null?void 0:t.trim();if(n)return`${n} dataset`}return Emt}function Mmt({fieldType:e,inlineAnalysis:t,availability:n,hasInputFields:r=!0}){const o=[{label:"Type",value:cme(e)}];return e==="metric"&&o.push({label:"Compute",value:"After aggregation"}),r&&(o.push({label:"Uses",value:dmt(t.kind)}),o.push({label:"Stored with",value:Dmt(t)})),o.push({label:"Available in",value:yy(n)}),o}function Rmt(e){const t=Mmt(e);return l.jsxs("div",{className:"flex items-center justify-between gap-3 border-t bg-muted/40 px-5 py-2","data-testid":"calculated-field-summary-ribbon",children:[l.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:t.map(n=>l.jsxs("span",{className:"inline-flex items-baseline gap-1.5 rounded-[4px] border bg-background px-1.5 py-0.5 text-[11px]",children:[l.jsx("span",{className:"text-[9px] font-medium uppercase tracking-[0.06em] text-muted-foreground/80",children:n.label}),l.jsx("span",{className:"text-foreground",children:n.value})]},n.label))}),l.jsx("span",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"Derived"})]})}function Amt(e){var r;const t=p.getRequestErrorMessage(e,"AI generation failed"),n=(r=p.getRequestErrorViolations(e))==null?void 0:r[0];return n?n.hint?`${n.message} Hint: ${n.hint}`:n.message||t:t}function Pmt({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:o}=It(),[s,i]=v.useState(!1),[a,c]=v.useState(null),u=v.useCallback(async f=>{var h;if(!e)return c("AI generation is not available"),null;if(!f.trim())return c("Describe what you want to calculate"),null;i(!0),c(null);try{const m={type:"calculated-field-expression",context:{userQuery:f,availableFields:t.map(b=>({name:b.tokenLabel,dataType:b.dataType,...b.role==="metric"||b.role==="groupby"?{role:b.role}:{}})),fieldType:n},options:{dialect:r}},g=await p.postRequestRegular(e,(o==null?void 0:o.accessToken)||"",m);if(!g.success||!((h=g.result)!=null&&h.generated))throw new Error(g.error||"No expression generated");return{generated:g.result.generated,explanation:g.result.explanation}}catch(m){return c(Amt(m)),null}finally{i(!1)}},[e,t,n,r,o==null?void 0:o.accessToken]),d=v.useCallback(()=>c(null),[]);return{generateExpression:u,isGenerating:s,error:a,resetError:d}}const Fmt=/\{([^}]+)\}/g;function xT(e){return e.trim().toLowerCase()}function dme(e){return Array.from(e.matchAll(Fmt)).map(t=>t[1]).filter(Boolean)}function Omt(e){const t=new Set,n=[];return e.forEach(r=>{const o=xT(r);t.has(o)||(t.add(o),n.push(r))}),n}function r4(e){const t=new Map,n=(r,o)=>{const s=xT(r),i=t.get(s)||[];i.some(a=>a.id===o.id)||t.set(s,[...i,o])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function Z1(e,t){const n=dme(e),r=Omt(n),o=r4(t),s=r.map(a=>{const c=o.get(xT(a))||[];return c.length===1?c[0]:null}),i=r.filter((a,c)=>!s[c]);return{orderedTokens:r,orderedFields:s,unresolvedTokens:i}}function _F(e,t){return t.reduce((n,r,o)=>{const s=new RegExp(`\\{${Lmt(r)}\\}`,"gi");return n.replace(s,`{field_${o}}`)},e)}function Lmt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const $mt=e=>e.entityName===dt.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===dt.CALCULATED_FIELDS_GROUP_NAME||e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER?"Calculated Fields":e.qualifiedEntityName?p.toLabel(e.entityName||e.qualifiedEntityName):p.toLabel(e.entityName||"Other");function zmt(e){return e.entityName===dt.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===dt.CALCULATED_FIELDS_GROUP_NAME||e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER?dt.CALCULATED_FIELDS_GROUP_NAME:e.qualifiedEntityName||e.entityName||"Other"}function Bmt(e){return e.role!=="metric"?!1:e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===xr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===dt.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===dt.CALCULATED_FIELDS_GROUP_NAME}function Vmt(e,t){const n=new Set((t||[]).map(r=>ck(r)));return e.filter(r=>{const o=ck(r.id);return!(o&&n.has(o))})}function Hmt(e){const t=new Map,n=new Map;return e.forEach(r=>{let s=r.entityName&&r.entityName!==xr.CALCULATED_FIELD_ENTITY_MARKER?`${r.entityName}.${r.name}`:r.name;const i=s.toLowerCase(),a=n.get(i)||0;a>0&&(s=`${s} ${a+1}`),n.set(i,a+1),t.set(r.id,s)}),t}function qmt(e,t,n,r){return t==="dimension"?e.map(o=>({...o,isCompatible:!Bmt(o)})).filter(o=>r):t!=="metric"?e.map(o=>({...o,isCompatible:!0})):e.map(o=>({...o,isCompatible:!0}))}function Umt(e,t){if(!t)return e;const n=t.toLowerCase();return e.filter(r=>r.name.toLowerCase().includes(n)||r.baseLabel.toLowerCase().includes(n)||r.tokenLabel.toLowerCase().includes(n)||r.dataType.toLowerCase().includes(n)||(r.qualifiedEntityName||r.entityName||"").toLowerCase().includes(n))}function Wmt(e){const t=new Map;return e.forEach(n=>{var o;const r=zmt(n);t.has(r)||t.set(r,{id:r,label:$mt(n),fields:[]}),(o=t.get(r))==null||o.fields.push(n)}),Array.from(t.values())}function Kmt({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:o,showIncompatible:s}){const i=v.useMemo(()=>Vmt(e,r),[e,r]),a=v.useMemo(()=>Hmt(i),[i]),c=v.useMemo(()=>i.map(g=>{const b=g.label||g.name,x=g.role==="metric"&&xr.isCalculatedMetric(g)||g.role==="groupby"&&xr.isCalculatedDimension(g);return{...g,baseLabel:b,tokenLabel:a.get(g.id)||b,isCalculated:x,isCompatible:!0}}),[i,a]),u=v.useMemo(()=>qmt(c,t,o,s),[c,t,o,s]),d=v.useMemo(()=>Umt(u,n),[u,n]),f=v.useMemo(()=>u.filter(g=>g.isCompatible),[u]),h=v.useMemo(()=>r4(f),[f]),m=v.useMemo(()=>Wmt(d),[d]);return{allFields:c,filteredFields:d,groups:m,tokenCandidates:h,tokenFields:f}}const Gmt=e=>p.getDataType(e.dataType||"")==="number",aK=e=>Gmt(e)?"SUM":"COUNT",Ymt=e=>{if(e.role==="metric"){const n=e;return{...n,aggregate:n.aggregate||aK(e)}}const t=aK(e);return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}},Zmt=(e,t)=>{var r;const n=e.trim();if(n){if(/\bDATE_TRUNC\b/i.test(n))return"date";if(/\bTIMESTAMP\b/i.test(n))return"datetime";if(/\bDATE\b/i.test(n)&&!/\bUPDATE\b/i.test(n))return"date";if(/['"]/.test(n))return"string";if(/[+\-*/]/.test(n))return"number";if(t.length===1)return p.getDataType(((r=t[0])==null?void 0:r.dataType)||"")}};function Xmt({expression:e,availableFields:t,validationEndpoint:n,connectionId:r,dialect:o,fieldType:s,outputType:i,validationContext:a}){const{authToken:c}=It(),[u,d]=v.useState(null),[f,h]=v.useState(!1),[m,g]=v.useState(null),b=v.useMemo(()=>r4(t),[t]),x=v.useMemo(()=>dme(e).map(S=>{const j=b.get(xT(S))||[];return{token:S,field:j.length===1?j[0]:null}}),[e,b]),y=v.useCallback((N,S)=>{const j=[{code:"SQL_VALIDATION_ERROR",message:N,suggestion:(S==null?void 0:S.suggestion)||(S==null?void 0:S.errorCode)}];return{isValid:!1,tokens:x,errors:j,warnings:[]}},[x]),w=v.useCallback(async()=>{var A;g(null);const N=n==null?void 0:n.trim();if(!N){const F=y("Validation endpoint is not configured");return d(F),F}if(!!!(a!=null&&a.cardConfig&&(a!=null&&a.cardDataSource)&&(a!=null&&a.cardId)&&(a!=null&&a.connectionId||r))){const F=y("Validation context is incomplete for server-side validation");return d(F),F}const{orderedTokens:j,orderedFields:_}=Z1(e,t),k=[],T=[];j.forEach((F,z)=>{const L=_[z];L&&(k.push(F),T.push(L))});const I=s==="metric"?T.map(Ymt):T,E=Zmt(e,T),D=_F(e,k),R={type:"calculated-field-expression",fieldType:s,expression:D,inputFields:I,outputType:i,options:{validateWithExplain:!0},context:{connectionId:(a==null?void 0:a.connectionId)||r,cardId:a==null?void 0:a.cardId,cardConfig:a==null?void 0:a.cardConfig,cardDataSource:a==null?void 0:a.cardDataSource,activeFilters:(a==null?void 0:a.activeFilters)||[],cardType:(a==null?void 0:a.cardType)||"table",dialect:o}};h(!0);try{const F=await p.postRequestRegular(N,(c==null?void 0:c.accessToken)||"",R),z=F==null?void 0:F.status,L=F==null?void 0:F.error,$=F==null?void 0:F.errorCode,H=[],M=[];z==="invalid"?H.push({code:"SQL_VALIDATION_ERROR",message:L||"Expression failed SQL validation",suggestion:$?`Validation code: ${$}`:void 0}):z==="unverified"?M.push({code:"EXECUTION_UNVERIFIED",message:L||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):z!=="valid"&&H.push({code:"SQL_VALIDATION_ERROR",message:L||"Unexpected SQL validation response from server",suggestion:$?`Validation code: ${$}`:void 0});const B={isValid:(z==="valid"||z==="unverified")&&H.length===0,tokens:x,errors:H,warnings:M,inferredDataType:(F==null?void 0:F.inferredDataType)??((A=F==null?void 0:F.metadata)==null?void 0:A.inferredDataType)??E??i??void 0};return d(B),B}catch(F){const z=(F==null?void 0:F.error)||(F==null?void 0:F.message)||"Expression validation failed";g(z);const L=y(z);return d(L),L}finally{h(!1)}},[n,a,r,e,t,s,i,o,c==null?void 0:c.accessToken,y,x]),C=v.useCallback(()=>{d(null),g(null)},[]);return{validationResult:u,isValidating:f,serverError:m,validateExpression:w,resetValidation:C}}const lK=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],Qmt=[],Jmt="https://docs.semaphor.cloud/docs/concepts/calculated-fields/metrics",ept="https://docs.semaphor.cloud/docs/concepts/calculated-fields/dimensions",tpt="SUM({revenue}) / NULLIF(COUNT({order_id}), 0)",npt="DATE_TRUNC('month', {created_at})";function fme({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:o,onSave:s,onSaveToSheet:i,onSaveToDashboard:a,cardId:c,initialFieldType:u="metric",allowedFieldTypes:d}){var Dt,nt,ge;const{tokenProps:f}=It(),h=((nt=(Dt=f.config)==null?void 0:Dt.projectFeatures)==null?void 0:nt.features.aiWritingHelpers)!==!1,{selectedConnection:m}=Eee(),g=p.useEditorStore(Se=>{var Oe;return(Oe=Se.card)==null?void 0:Oe.config}),b=p.useEditorStore(Se=>{var Oe;return(Oe=Se.card)==null?void 0:Oe.dataSource}),x=p.useEditorStore(Se=>{var Oe;return(Oe=Se.card)==null?void 0:Oe.type}),w=p.useEditorStore(Se=>Se.filterValues)??Qmt,[C,N]=v.useState(u),[S,j]=v.useState(""),[_,k]=v.useState(""),[T,I]=v.useState(null),[E,D]=v.useState("card"),[R,A]=v.useState({}),[F,z]=v.useState(""),[L,$]=v.useState(!1),[H,M]=v.useState(""),[B,W]=v.useState(""),[P,G]=v.useState(void 0),[Z,X]=v.useState(null),[Y,O]=v.useState(!1),[q,U]=v.useState(!1),[V,K]=v.useState(null),Q=v.useId(),se=v.useRef(!1),oe=v.useRef(null),{userContext:me}=ti(),le=v.useMemo(()=>n.filter(Se=>Se.fieldScope==="domain"&&!!Se.expression),[n]),ue=v.useMemo(()=>le.filter(Se=>Se.role==="metric"),[le]),ne=v.useMemo(()=>le.filter(Se=>Se.role==="groupby"),[le]),Ce=!((me==null?void 0:me.type)==="organization"),ce=!!V,ie=Ce||ce,we=!!i,fe=!!a,ae=(ge=f==null?void 0:f.apiServiceUrl)==null?void 0:ge.replace(/\/$/,""),ee=ae?`${ae}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",J=ae?`${ae}/v1/ai/generate`:"/v1/ai/generate",re=v.useMemo(()=>{var Ye;const Se=[...n];return(((Ye=r==null?void 0:r.calculatedFormula)==null?void 0:Ye.inputFields)||[]).forEach(bt=>{Se.some(on=>on.id===bt.id||on.qualifiedFieldName===bt.qualifiedFieldName||on.name===bt.name)||Se.push(bt)}),Se},[n,r]),{tokenFields:pe,groups:Ee}=Kmt({fields:re,mode:C,searchTerm:F,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:void 0,showIncompatible:!0}),Te=pe,{generateExpression:ze,isGenerating:Pe,error:He,resetError:ye}=Pmt({endpoint:J,availableFields:Te,fieldType:C,dialect:m==null?void 0:m.dialect}),Ke=Pe?"loading":B?"result":"prompt",{validationResult:We,validateExpression:Qe,isValidating:xe,serverError:Ve,resetValidation:Ae}=Xmt({expression:_,availableFields:Te,validationEndpoint:ee,connectionId:m==null?void 0:m.id,dialect:m==null?void 0:m.dialect,fieldType:C,outputType:T||void 0,validationContext:{connectionId:(m==null?void 0:m.id)||(b==null?void 0:b.connectionId),cardId:c,cardConfig:g||{},cardDataSource:b||null,activeFilters:w,cardType:x}}),ke=We==null?void 0:We.inferredDataType,Be=T||ke||"string",Ie=v.useCallback(()=>{$(!1),M(""),W(""),G(void 0),ye()},[ye]),$e=v.useCallback(()=>{ie||!h||(W(""),G(void 0),ye(),$(!0))},[h,ie,ye]),st=v.useCallback(async()=>{if(!H.trim())return;const Se=await ze(H);Se&&(W(Se.generated),G(Se.explanation))},[H,ze]),ct=v.useCallback(()=>{W(""),G(void 0),ye()},[ye]),rt=v.useCallback(()=>{B.trim()&&(k(B),Ae(),Ie())},[B,Ie,Ae]),Ct=v.useMemo(()=>{const{orderedFields:Se}=Z1(_,Te);return Se.filter(Oe=>!!Oe)},[Te,_]),Lt=v.useMemo(()=>t4(Ct),[Ct]),vt=v.useMemo(()=>{if(!S.trim())return!1;const Se=e4(S);return wmt({fields:C==="metric"?ue:ne,normalizedName:Se,existingFieldId:o==="domain"?r==null?void 0:r.id:void 0,targetKind:Lt.kind==="inline"?"inline":"root",targetEntityName:Lt.kind==="inline"?Lt.entityName:void 0,targetQualifiedEntityName:Lt.kind==="inline"?Lt.qualifiedEntityName:void 0})},[Lt,ne,ue,r,o,C,S]),Tt=v.useMemo(()=>Ct.map(Se=>Se.id),[Ct]),Me=Se=>{ie||r||N(Se)},Je=v.useCallback(()=>{j(""),k(""),I(null),D("card"),A({}),z(""),$(!1),M(""),W(""),G(void 0),K(null),X(null),O(!1),Ae(),ye(),t(!1)},[t,Ae,ye]),kt=v.useCallback((Se,Oe)=>Se.replace(/\{field_(\d+)\}/g,(Ye,bt)=>{var sn;const St=Oe[Number(bt)];return St?`{${((sn=Te.find(Le=>Le.id===St.id))==null?void 0:sn.tokenLabel)||St.label||St.name}}`:Ye}),[Te]),mt=v.useCallback(Se=>{var bt;const Oe=((bt=Se.calculatedFormula)==null?void 0:bt.inputFields)||[],Ye=Se.role==="metric"?hmt(Se):Se.expression||"";k(kt(Ye,Oe))},[kt]);v.useEffect(()=>{if(!e){se.current=!1,oe.current=null;return}const Se=r?`${r.role}-${r.id||r.name}`:"new";if(se.current&&oe.current===Se)return;if(se.current=!0,oe.current=Se,A({}),z(""),Ae(),r){if(r.role==="metric"){const St=pmt(r);N("metric"),j(r.label||r.name),D(o||"card"),K(St.reason||null),mt(r),I(null);return}K(null),N("dimension");const Ye=r;j(Ye.label||Ye.name),D(o||"card"),mt(Ye);const bt=lK.some(St=>St.value===Ye.dataType)?Ye.dataType:"string";I(bt);return}const Oe=d&&d.length>0?d.includes(u)?u:d[0]:u;N(Oe),j(""),k(""),I(null),K(null),D("card")},[e,r,o,u,d,mt,Ae]);const _t=v.useCallback(Se=>{const Oe=typeof document<"u"?document.getElementById(Q):null;if(!Oe){k(St=>St+Se);return}const Ye=Oe.selectionStart||0,bt=Oe.selectionEnd||0;k(St=>`${St.slice(0,Ye)}${Se}${St.slice(bt)}`),requestAnimationFrame(()=>{Oe.focus();const St=Ye+Se.length;Oe.setSelectionRange(St,St)})},[Q]),Rt=Se=>{if(ie)return;const Oe=Se.tokenLabel||Se.label||Se.name;_t(`{${Oe}}`)},Pt=Se=>{ie||_t(Se)},wt=async()=>{const Se={};return S.trim()||(Se.name="Name is required"),_.trim()||(Se.expression="Expression is required"),Se.expression||(await Qe()).isValid||(Se.expression="Fix validation errors before saving"),A(Se),Object.keys(Se).length===0},Et=()=>{const{orderedTokens:Se,orderedFields:Oe}=Z1(_,Te),Ye=Oe.filter(on=>!!on),bt=_F(_,Se),St=umt(S,bt,Ye,Be,c,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...St}:St},Bt=()=>{const{orderedTokens:Se,orderedFields:Oe}=Z1(_,Te),Ye=Oe.filter(sn=>!!sn),bt=vmt(Ye,(r==null?void 0:r.role)==="metric"?r:void 0),St=_F(_,Se),on=lmt(S,"custom",null,null,{},c,r==null?void 0:r.id,St,void 0,bt);return r&&r.role==="metric"?gmt(r,on):on},un=async Se=>{if(Se==="domain"){A(Ye=>({...Ye,scope:"Domain scope is not available in this explorer."}));return}const Oe=C==="dimension"?Et():Bt();if(Se==="sheet"){if(!i){A(Ye=>({...Ye,scope:"Sheet scope is not available"}));return}await i(Oe),Je();return}if(Se==="dashboard"){if(!a){A(Ye=>({...Ye,scope:"Dashboard scope is not available"}));return}await a(Oe),Je();return}await s(Oe),Je()},Ge=async()=>{if(ie||(A({}),!await wt()))return;const Se=we||fe?E:o||"card";if(C==="metric"&&Se!=="domain"&&vt&&!r){X(Se),O(!0);return}U(!0);try{await un(Se)}finally{U(!1)}},Re=C==="metric"?Jmt:ept,De=C==="metric"?tpt:npt,he=C==="metric"?"Metric formula":"Column expression",Fe=we||fe,ot=d||["metric","dimension"];return l.jsxs(l.Fragment,{children:[l.jsxs(Mo,{modal:!1,open:e,onOpenChange:Se=>{Se?t(!0):Je()},children:[e&&l.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),l.jsxs(go,{className:"max-w-3xl max-h-[90vh] overflow-hidden p-0",onInteractOutside:Se=>{Se.preventDefault()},children:[l.jsxs(Is,{className:"space-y-2 border-b py-3 pl-5 pr-12",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(bo,{className:"shrink-0 text-[14px] font-semibold",children:r?"Edit field":"New field"}),l.jsx(Cmt,{value:C,onChange:Me,disabled:ie||!!r,options:ot}),l.jsx(p.Input,{id:"calculated-name",value:S,onChange:Se=>j(Se.target.value),placeholder:"Field name","aria-label":"Field name","aria-invalid":!!R.name,className:`h-7 flex-1 ${R.name?"border-destructive":""}`,disabled:ie})]}),l.jsx(Ro,{className:"sr-only",children:"Build a calculated metric or column using expressions."}),R.name&&l.jsx("p",{className:"text-xs text-destructive",children:R.name}),V&&l.jsxs("div",{className:"rounded-control border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:[l.jsx("p",{className:"font-medium text-foreground",children:"Read-only legacy metric"}),l.jsx("p",{children:V})]})]}),l.jsxs("div",{className:"flex max-h-[calc(80vh-180px)] min-h-0 flex-col gap-4 overflow-y-auto px-5 py-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs("div",{className:"flex items-baseline gap-2 whitespace-nowrap",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:he}),C==="metric"&&l.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground",title:"Phase 1 metrics run on aggregated values such as SUM(revenue) / COUNT(orders). Per-row metrics aren't saveable yet — use Calculated Column for row-level math.",children:[l.jsx("span",{className:"text-muted-foreground/70",children:"·"}),l.jsx("span",{className:"font-medium text-foreground",children:"After aggregation"}),l.jsx(p.Info,{className:"h-2.5 w-2.5 text-muted-foreground/70","aria-hidden":!0})]})]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(Imt,{groups:Ee,searchTerm:F,onSearchTermChange:z,onFieldSelect:Rt,selectedFieldIds:Tt,disabled:ie||L}),C==="metric"&&l.jsx(Tmt,{onInsert:Pt,disabled:ie||L}),!!J&&h&&!ie&&l.jsxs(p.Button,{type:"button",variant:L?"default":"outline",size:"xs",onClick:$e,disabled:L,className:"gap-1.5",children:[l.jsx(p0,{className:"h-3 w-3","aria-hidden":!0}),L?"Composing…":"Generate"]}),l.jsxs("a",{href:Re,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground",children:["Docs ",l.jsx(Ld,{className:"h-2.5 w-2.5"})]})]})]}),L?l.jsx(kmt,{mode:Ke,fieldType:C,prompt:H,onPromptChange:M,generated:B,explanation:P,isGenerating:Pe,error:He,onGenerate:()=>void st(),onTryAgain:ct,onCancel:Ie,onUseDraft:rt}):l.jsxs(l.Fragment,{children:[l.jsx("div",{"aria-invalid":!!R.expression,className:`overflow-hidden rounded-control border ${R.expression?"border-destructive":"border-input"}`,children:l.jsx("div",{className:"h-[160px]",children:l.jsx(p.CodeEditor,{value:_,onValueChange:k,language:"sql-jinja",placeholder:De,ariaLabel:C==="metric"?"Metric formula":"Column expression",textareaId:Q,readOnly:ie,embedded:!0,flushGutter:!0,dense:!0})})}),l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx(Nmt,{onValidate:Qe,isValidating:xe,validationResult:We,error:Ve,disabled:ie}),l.jsx("span",{className:"text-[11px] text-muted-foreground",children:C==="metric"?"Aggregate functions allowed":"Aggregate functions not allowed"})]}),R.expression&&l.jsx("p",{className:"text-xs text-destructive",children:R.expression})]})]}),C==="dimension"&&l.jsxs("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Output type"}),l.jsxs(p.Select,{value:Be,onValueChange:Se=>I(Se),disabled:ie,children:[l.jsx(p.SelectTrigger,{className:"h-7 w-44 text-[12px]",children:l.jsx(p.SelectValue,{placeholder:"Select output type"})}),l.jsx(p.SelectContent,{children:lK.map(Se=>l.jsx(p.SelectItem,{value:Se.value,children:Se.label},Se.value))})]}),ke&&!T&&l.jsxs("p",{className:"col-start-2 text-[11px] text-muted-foreground",children:["Suggested type: ",ke]})]}),Fe&&l.jsxs("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Availability"}),l.jsx(p.Tabs,{value:E,onValueChange:Se=>D(Se),className:"w-fit",children:l.jsxs(p.TabsList,{size:"xs",children:[l.jsx(p.TabsTrigger,{value:"card",disabled:ie,children:yy("card")}),we&&l.jsx(p.TabsTrigger,{value:"sheet",disabled:ie,children:yy("sheet")}),fe&&l.jsx(p.TabsTrigger,{value:"dashboard",disabled:ie,children:yy("dashboard")})]})}),R.scope&&l.jsx("p",{className:"col-start-2 text-xs text-destructive",children:R.scope})]})]}),l.jsx(Rmt,{fieldType:C,inlineAnalysis:Lt,availability:Fe?E:o||"card",hasInputFields:Ct.length>0}),l.jsxs(tl,{className:"gap-1.5 border-t px-5 py-2.5",children:[l.jsx(p.Button,{variant:"outline",size:"xs",onClick:Je,disabled:q,children:"Cancel"}),l.jsx(p.Button,{size:"xs",onClick:()=>void Ge(),disabled:q||xe||ie,children:q?l.jsxs(l.Fragment,{children:[l.jsx(p.LoaderCircle,{className:"mr-1.5 h-3 w-3 animate-spin"}),"Applying…"]}):ce?"Read-only":"Apply"})]})]})]}),l.jsx(ff,{open:Y,onOpenChange:O,children:l.jsxs(ku,{children:[l.jsxs(_u,{children:[l.jsx(Tu,{children:"Name conflict"}),l.jsxs(Eu,{children:['A domain metric named "',S.trim(),'" already exists. Your local version will override it for the selected availability:'," ",yy(Z||"card"),". Continue?"]})]}),l.jsxs(Iu,{children:[l.jsx(Mu,{onClick:()=>{X(null)},children:"Choose different name"}),l.jsx(Du,{onClick:async()=>{if(Z){O(!1),U(!0);try{await un(Z)}finally{U(!1),X(null)}}},children:"Continue"})]})]})})]})}function rpt(e,t){const n=e.fieldScope==="sheet"||e.fieldScope==="dashboard";if(e.role==="metric"){const r=t.metricFields.find(o=>p.matchesCalculatedField(o,e,{allowComparableFallback:n}));if(r)return r}if(e.role==="groupby"){const r=t.groupByFields.find(o=>p.matchesCalculatedField(o,e,{allowComparableFallback:n}));if(r)return r}return t.storedCalculatedFields.find(r=>p.matchesCalculatedField(r,e,{allowComparableFallback:n}))}function opt(e,t){const n={...e,fieldScope:"domain"};return t.find(r=>r.fieldScope==="domain"&&p.matchesCalculatedField(r,n))}function yT(e,t){var n,r,o,s;if(e.role==="metric"&&t.role==="metric"){const i=e,a=t;return{...a,parameters:i.parameters||a.parameters?{filters:((n=i.parameters)==null?void 0:n.filters)??((r=a.parameters)==null?void 0:r.filters),windowTransform:((o=i.parameters)==null?void 0:o.windowTransform)??((s=a.parameters)==null?void 0:s.windowTransform)}:void 0,aliasTemplate:i.aliasTemplate??a.aliasTemplate,valueAliases:i.valueAliases??a.valueAliases,customFormat:i.customFormat??a.customFormat,comparison:i.comparison??a.comparison,comparisonPolarity:i.comparisonPolarity??a.comparisonPolarity}}if(e.role==="groupby"&&t.role==="groupby"){const i=e,a=t,c=i.granularity??a.granularity,u=c&&p.getDataType(i.dataType)==="date"?p.readTemporalBucketAuthoringSelectionWithOverride({fieldId:a.id,dataType:a.dataType,granularity:c,format:a.format,dateFormat:a.dateFormat,customFormat:a.customFormat,semanticTemporalPresentation:i.semanticTemporalPresentation??a.semanticTemporalPresentation},{format:i.format,dateFormat:i.dateFormat,customFormat:i.customFormat}).format:i.format??a.format;return{...a,granularity:c,format:u,dateFormat:void 0,customFormat:void 0,timeDrillPath:i.timeDrillPath??a.timeDrillPath}}return t}function o4(e,t,n,r){if(!n)return null;const o=n||t,s=p.findCalculatedFieldIndex(e,o,r);if(n&&s<0)return null;if(s>=0){const i=e[s],a=i==null?void 0:i.id,c=r!=null&&r.mergeMatchedField?r.mergeMatchedField(i,t):t,d=a&&a!==c.id&&!((i==null?void 0:i.fieldScope)==="domain"&&c.fieldScope==="domain")?{...c,id:a}:c;return e.map((f,h)=>h===s?d:f)}return null}function s4(e,t){return{...e,fieldScope:t}}function spt(e,t,n){return p.matchesCalculatedField(e,t,n)?!0:e.role&&t.role&&e.role!==t.role?p.matchesCalculatedField(e,{...t,role:e.role},n):!1}function ipt(e,t,n,r){if(!(e!=null&&e.length)||!n)return null;const o=e.findIndex(u=>spt(u,n,r));if(o<0)return null;const s=e[o],i=yT(s,{...t,role:s.role}),a=(()=>{if(s.role==="sortby")return{...i,role:"sortby",direction:s.direction};if(s.role==="detail"){const u=s;return{...i,role:"detail",dateFormat:u.dateFormat??i.dateFormat,customFormat:u.customFormat??i.customFormat}}return i})(),c=s.id&&s.id!==i.id?{...a,id:s.id}:a;return e.map((u,d)=>d===o?c:u)}function IF(e){const t=s4(e.updatedField,"card"),n=o4(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard",mergeMatchedField:yT}),r=p.upsertCalculatedField(e.storedFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard"}),o=(e.previousScope==="sheet"||e.previousScope==="dashboard")&&e.editingField?p.removeCalculatedField(e.sharedFields,e.editingField,{allowComparableFallback:!0}):e.sharedFields,s=i4({sortByFields:e.sortByFields,updatedField:t,editingField:e.editingField,previousScope:e.previousScope});return{nextActiveFields:n,nextSortByFields:s,nextStoredFields:r,nextSharedFields:o}}function TF(e){const t=s4(e.updatedField,"sheet"),n=o4(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard",mergeMatchedField:yT}),r=p.upsertCalculatedField(e.sheetFields,t,e.editingField,{allowComparableFallback:!0}),o=e.previousScope==="card"&&e.editingField?p.removeCalculatedField(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields,s=e.previousScope==="dashboard"&&e.editingField&&e.dashboardFields?p.removeCalculatedField(e.dashboardFields,e.editingField,{allowComparableFallback:!0}):e.dashboardFields,i=i4({sortByFields:e.sortByFields,updatedField:t,editingField:e.editingField,previousScope:e.previousScope});return{nextActiveFields:n,nextSortByFields:i,nextStoredFields:o,nextSheetFields:r,nextDashboardFields:s}}function hme(e){const t=s4(e.updatedField,"dashboard"),n=o4(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard",mergeMatchedField:yT}),r=p.upsertCalculatedField(e.sharedFields,t,e.editingField,{allowComparableFallback:!0}),o=e.previousScope==="card"&&e.editingField?p.removeCalculatedField(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields,s=e.previousScope==="sheet"&&e.editingField&&e.sheetFields?p.removeCalculatedField(e.sheetFields,e.editingField,{allowComparableFallback:!0}):e.sheetFields,i=i4({sortByFields:e.sortByFields,updatedField:t,editingField:e.editingField,previousScope:e.previousScope});return{nextActiveFields:n,nextSortByFields:i,nextStoredFields:o,nextSharedFields:r,nextSheetFields:s}}function i4(e){return ipt(e.sortByFields||[],e.updatedField,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard"})}function Jf(e){const{nextSharedFields:t,currentSharedFields:n,isVisualEditing:r,selectedSheetId:o,updateFrame:s,updateSheetCalculatedFields:i,currentFrame:a,nextFramePatch:c,persistFrame:u,persistFrames:d}=e,f=c?{...c,calculatedFields:t}:{calculatedFields:t};(t!==n||c)&&s(f),o&&(r||(u&&(d!=null&&d.length)?d.forEach(h=>{u(o,{...h,calculatedFields:void 0})}):u&&a&&c&&u(o,{...a,...c,calculatedFields:void 0}),i&&i(o,t)))}const apt=[];function XS({label:e,count:t,active:n,onClick:r,ariaLabel:o}){return l.jsxs("button",{type:"button",onClick:r,"aria-label":o,"aria-pressed":n,className:p.cn("-mb-px inline-flex items-center gap-1 border-b-2 px-0.5 pb-2 pt-1 text-[12px] transition-colors",n?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:[l.jsx("span",{children:e}),l.jsx("span",{className:p.cn("font-mono text-[10px] tabular-nums",n?"text-muted-foreground":"text-muted-foreground/70"),children:t})]})}const a4=v.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var Fe,ot,Dt,nt;const[o,s]=v.useState(""),[i,a]=v.useState("all"),c=v.useRef(null),[u,d]=v.useState(null),[f,h]=v.useState(!1),m=280,g=(ge,Se)=>(Oe,Ye)=>{if(!Oe){d(sn=>sn&&sn.field.id===ge.id?null:sn);return}if(f){d(null);return}if(!Ye||!c.current)return;const bt=Ye.getBoundingClientRect(),St=c.current.getBoundingClientRect(),on=Math.max(0,St.bottom-m);d({field:ge,fieldState:Se,top:Math.min(bt.top,on),left:St.right+12})},[b,x]=v.useState(!1),[y,w]=v.useState(null),[C,N]=v.useState("card"),[S,j]=v.useState("metric"),[_,k]=v.useState(null),[T,I]=v.useState(!1);p.useEditorStore(ge=>ge.isDevMode);const E=p.useEditorStore(ge=>ge.card.dataSource),D=p.useEditorStore(ge=>ge.card.config),R=p.useEditorStore(ge=>ge.card),A=p.useEditorStore(ge=>ge.frame),F=p.useEditorStore(ge=>ge.actions.updateCardConfig),z=p.useEditorStore(ge=>ge.actions.updateCard),L=p.useEditorStore(ge=>ge.actions.updateFrame),$=p.useDashboardStore(ge=>ge.isVisualEditing),H=p.useDashboardStore(ge=>ge.selectedSheetId),M=p.useDashboardStore(ge=>ge.actions.updateSheetCalculatedFields),B=p.useDashboardStore(ge=>ge.actions.updateDashboardCalculatedFields),P=p.useDashboardStore(ge=>{var Se;return ge.visualEditPendingDashboardCalculatedFields??((Se=ge.dashboard)==null?void 0:Se.calculatedFields)})??apt,{userContext:G}=ti(),{autoJoinMetadata:Z}=pb(R),{rawColumnGroups:X,scopedFields:Y,filterableFields:O,dashboardFilterableFields:q,inlineFilterableFields:U,scopedCalculatedFields:V,sharedCalculatedFields:K,inlineCalculatedFields:Q,isLoading:se,error:oe}=Ohe(),me=(E==null?void 0:E.mode)==="semanticDomain"?E.semanticDomainId:void 0,{data:le}=qz(me),ue=v.useMemo(()=>[...(D==null?void 0:D.groupByColumns)||[],...(D==null?void 0:D.metricColumns)||[],...(D==null?void 0:D.detailColumns)||[]],[D==null?void 0:D.groupByColumns,D==null?void 0:D.metricColumns,D==null?void 0:D.detailColumns]);(ot=(Fe=D==null?void 0:D.joinPlan)==null?void 0:Fe.baseEntity)==null||ot.name,(nt=(Dt=Z==null?void 0:Z.resolvedJoinPlan)==null?void 0:Dt.baseEntity)==null||nt.name,Whe();const ne=t==="editor"?V:t==="filter"||t==="document-filter"?K:Q,de=t==="editor"?ne.filter(ge=>p.getCalculatedFieldNamespace(ge)==="root"):ne,Ce=de.length>0,ce=(G==null?void 0:G.type)==="organization",ie=t==="editor"?O||Y:t==="filter"||t==="document-filter"?q:U,we=X,fe=o.toLowerCase(),ae=(D==null?void 0:D.metricColumns)||[],ee=(D==null?void 0:D.groupByColumns)||[],J=(D==null?void 0:D.sortByColumns)||[],re=R.calculatedFields||[],pe=ge=>ge.name.toLowerCase().includes(fe)||ge.label&&ge.label.toLowerCase().includes(fe)||ge.dataType.toLowerCase().includes(fe)||ge.description&&ge.description.toLowerCase().includes(fe)||ge.qualifiedEntityName&&ge.qualifiedEntityName.toLowerCase().includes(fe),Ee=v.useCallback(ge=>(ge.label||ge.name).toLowerCase().trim(),[]),Te=v.useCallback((ge,Se)=>Ee(ge).localeCompare(Ee(Se),void 0,{numeric:!0,sensitivity:"base"}),[Ee]),ze=ie.filter(pe).sort(Te),Pe=v.useCallback(ge=>t==="editor"?nx(ge):Qa(ge),[t]),He=ge=>{if(Pe(ge))return"calculated";if(ge.dataType==="number"||ge.dataType==="integer"||ge.dataType==="float"||ge.dataType==="decimal"||ge.dataType==="currency")return"metrics";const Se=p.getDataType(ge.dataType);return["date","string","boolean"].includes(Se)?"dimensions":Se==="number"?"metrics":"dimensions"},ye=ge=>{const Se=ge.filter(pe);return i==="all"?Se:Se.filter(Oe=>He(Oe)===i)},Ke=i==="all"?ze:ze.filter(ge=>He(ge)===i),We=Ce?ye(de).sort(Te):[],Qe=v.useCallback(ge=>Pe(ge)&&(t!=="editor"||p.getCalculatedFieldNamespace(ge)==="root"),[t,Pe]),xe=ie.filter(ge=>!Qe(ge)),Ae=ye(xe).sort(Te).reduce((ge,Se)=>{const Oe=Se.qualifiedEntityName||"Other Fields";return ge[Oe]||(ge[Oe]={label:p.toLabel(Se.entityName),fields:[]}),ge[Oe].fields.push(Se),ge},{}),ke=v.useMemo(()=>Object.entries(Ae).map(([ge,Se])=>{const Oe=we.find(bt=>bt.entityName===ge)||{entityName:ge,label:Se.label},Ye=ge===dt.CALCULATED_FIELDS_GROUP_NAME?"Domain Calculated Fields":Oe.label||Oe.entityName;return{groupName:ge,groupLabel:Ye,fields:[...Se.fields].sort(Te)}}).sort((ge,Se)=>ge.groupLabel.localeCompare(Se.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[Ae,we,Te]),Be=ge=>ge.id||`${ge.entityName}-${ge.qualifiedEntityName}-${ge.name}-${ge.role||"field"}`,Ie=v.useMemo(()=>{const ge=new Map;return ie.forEach(Oe=>{ge.set(Be(Oe),GL(Oe,{joinabilityMap:(le==null?void 0:le.joinabilityMap)||null,selectedFields:ue,cardConfig:D,autoJoinMetadata:Z,datasetAliases:le==null?void 0:le.datasets}))}),ge},[ie,le==null?void 0:le.joinabilityMap,le==null?void 0:le.datasets,ue,D,Z]),$e=i==="calculated"&&ce&&t==="editor"&&de.length===0,st=We.length>0?[{key:"scope-calculated",label:"Calculated Fields",fields:We}]:$e?[{key:"scope-calculated",label:"Calculated Fields",fields:[]}]:[],rt=[...st.map(ge=>ge.key),...ke.map(ge=>ge.groupName)],Ct=ze.filter(ge=>He(ge)==="dimensions").length,Lt=ze.filter(ge=>He(ge)==="metrics").length,vt=ze.filter(ge=>He(ge)==="calculated").length,Tt=ze.length>0&&t!=="inline-filter"&&t!=="document-filter",Me=t==="inline-filter"||t==="document-filter"?"w-full":"w-[290px]";if(se)return l.jsx("div",{className:p.cn("flex h-full flex-col items-center justify-center py-8",Me),children:l.jsx(xu,{size:"md",color:"muted","aria-label":"Loading data"})});if(oe)return l.jsxs("div",{className:p.cn("flex h-full flex-col items-center justify-center py-8",Me),children:[l.jsx(ss,{className:"mb-3 h-8 w-8 text-destructive/40"}),l.jsx("p",{className:"mb-1 text-[12px] text-destructive",children:"Error loading fields"}),l.jsx("p",{className:"px-4 text-center text-[11px] leading-[1.45] text-muted-foreground",children:oe.message||"Failed to load column data"})]});if(!E||!E.selectedEntities||E.selectedEntities.length===0)return l.jsxs("div",{className:p.cn("flex flex-col items-center justify-center py-8 text-center",Me),children:[l.jsx(ss,{className:"mb-3 h-8 w-8 text-muted-foreground/40"}),l.jsx("p",{className:"mb-1 text-[12px] text-foreground",children:"No data source selected"}),l.jsx("p",{className:"px-4 text-[11px] leading-[1.45] text-muted-foreground",children:t==="filter"||t==="inline-filter"||t==="document-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const Je=t==="inline-filter"||t==="document-filter"?"pb-3":"pb-2",kt=t==="inline-filter"||t==="document-filter"?"overflow-hidden":"",mt=ge=>rpt(ge,{storedCalculatedFields:re,metricFields:ae,groupByFields:ee}),_t=ge=>p.resolveLocalCalculatedFieldScope({field:ge,sheetFields:(A==null?void 0:A.calculatedFields)||[],dashboardFields:P}),Rt=(ge,Se)=>{z(R.id,{calculatedFields:p.removeCalculatedField(re,ge,Se)})},Pt=ge=>{var Se;return(Se=A==null?void 0:A.calculatedFields)==null?void 0:Se.find(Oe=>p.matchesCalculatedField(Oe,ge))},wt=ge=>P.find(Se=>p.matchesCalculatedField(Se,ge,{allowComparableFallback:!0})),Et=(ge,Se)=>{if(ge.role==="metric"){F(R.id,{metricColumns:p.removeCalculatedField(ae,ge,Se)});return}ge.role==="groupby"&&F(R.id,{groupByColumns:p.removeCalculatedField(ee,ge,Se)})},Bt=ge=>{B(p.removeCalculatedField(P,ge,{allowComparableFallback:!0}))},un=ge=>{if(!A)return;const Se=p.removeCalculatedField(A.calculatedFields||[],ge);Jf({nextSharedFields:Se,currentSharedFields:A.calculatedFields||[],isVisualEditing:$,selectedSheetId:H,updateFrame:L,updateSheetCalculatedFields:M})},Ge=ge=>{if(!ce)return;if(d(null),ge.fieldScope==="domain"){lt.error("Domain calculated fields are read-only in this explorer.");return}const Se=_t(ge);if(Se.scope==="sheet"){const Ye=Se.matchedField||Pt(ge);if(!Ye)return;w(Ye),N("sheet"),j(Ye.role==="metric"?"metric":"dimension"),x(!0);return}if(Se.scope==="dashboard"){const Ye=Se.matchedField||wt(ge);if(!Ye)return;w(Ye),N("dashboard"),j(Ye.role==="metric"?"metric":"dimension"),x(!0);return}const Oe=mt(ge);Oe&&(w(Oe),N("card"),j(Oe.role==="metric"?"metric":"dimension"),x(!0))},Re=async ge=>{if(!ce)return;if(ge.fieldScope==="domain"){lt.error("Domain calculated fields are read-only in this explorer.");return}const Se=_t(ge),Oe={allowComparableFallback:Se.scope!=="card"};if(Se.scope==="sheet"){un(Se.matchedField||ge),Et(ge,Oe);return}if(Se.scope==="dashboard"){Bt(Se.matchedField||ge),Et(ge,Oe);return}Et(ge,Oe),Rt(ge,Oe)},De=async()=>{if(_){I(!0);try{await Re(_),k(null)}catch{}finally{I(!1)}}},he=ge=>{if(!ce)return null;const Se=ge.fieldScope==="domain",Oe=Se;return l.jsxs(Uo,{onOpenChange:Ye=>{h(Ye),Ye&&d(null)},children:[l.jsx(Wo,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":"Calculated field actions",className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(Ci,{className:"h-3 w-3"})})}),l.jsx(Do,{align:"end",className:"w-36",children:Se?l.jsx(kn,{disabled:!0,children:"Read-only"}):l.jsxs(l.Fragment,{children:[l.jsx(kn,{onClick:()=>Ge(ge),children:"Edit"}),l.jsx(kn,{className:"text-destructive focus:text-destructive",disabled:Oe,onClick:()=>k(ge),children:"Delete"})]})})]})};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{ref:c,className:p.cn("relative flex h-full w-full grow flex-col",Je,kt),children:[l.jsxs("div",{className:"flex-shrink-0 space-y-2 px-4 pt-2",children:[ie.length>0&&l.jsxs("div",{className:"flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[l.jsx(Ft.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),l.jsx("input",{type:"text",placeholder:"Search fields",value:o,onChange:ge=>s(ge.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),o&&l.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>s(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(je.X,{className:"h-3 w-3"})})]}),Tt&&l.jsxs("div",{className:"-mx-4 flex items-center gap-4 border-b border-border px-4",children:[l.jsx(XS,{label:"All",count:ze.length,active:i==="all",onClick:()=>a("all")}),l.jsx(XS,{label:"Dim",count:Ct,active:i==="dimensions",onClick:()=>a(ge=>ge==="dimensions"?"all":"dimensions"),ariaLabel:"Dimensions"}),l.jsx(XS,{label:"Metric",count:Lt,active:i==="metrics",onClick:()=>a(ge=>ge==="metrics"?"all":"metrics"),ariaLabel:"Metrics"}),l.jsx(XS,{label:"Calc",count:vt,active:i==="calculated",onClick:()=>a(ge=>ge==="calculated"?"all":"calculated"),ariaLabel:"Calculated"})]})]}),l.jsxs(hl,{className:"min-h-0 flex-1 [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:w-full",children:[l.jsxs(Jz,{type:"multiple",defaultValue:rt,className:"space-y-2",children:[st.map(ge=>l.jsxs(fv,{value:ge.key,className:"border-none",children:[l.jsxs(hv,{className:"group flex w-full items-center gap-1.5 rounded-[4px] px-4 py-1.5 text-left hover:bg-muted hover:no-underline [&>svg]:order-first [&>svg]:h-3 [&>svg]:w-3 [&>svg]:-rotate-90 [&>svg]:text-muted-foreground/70 data-[state=open]:[&>svg]:rotate-90",children:[l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l.jsx("span",{className:"max-w-[180px] truncate text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:ge.label}),l.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:ge.fields.length})]}),t==="editor"&&ce&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Add calculated field",title:"Add calculated field",onClick:Se=>{Se.stopPropagation(),w(null),N("card"),j("dimension"),x(!0)},onKeyDown:Se=>{(Se.key==="Enter"||Se.key===" ")&&(Se.preventDefault(),Se.stopPropagation(),w(null),N("card"),j("dimension"),x(!0))},className:"inline-flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(Tr,{className:"h-3 w-3"})})]}),l.jsx(mv,{className:"pb-1",children:l.jsxs("div",{children:[ge.fields.length===0&&$e&&l.jsx("p",{className:"px-4 py-2 text-[11px] text-muted-foreground",children:"No calculated fields yet — click + to add."}),ge.fields.map(Se=>{const Oe=Ie.get(Be(Se)),Ye=t==="editor"&&ce&&Qa(Se);return l.jsx(oK,{field:Se,context:t,fieldState:Oe,onFieldSelect:n,inlineFilters:t==="inline-filter"||t==="document-filter"?r:void 0,actions:Ye?he(Se):void 0,onHover:g(Se,Oe)},Se.id)})]})})]},ge.key)),ke.map(({groupName:ge,groupLabel:Se,fields:Oe})=>l.jsxs(fv,{value:ge,className:"border-none",children:[l.jsx(hv,{className:"group flex w-full items-center gap-1.5 rounded-[4px] px-4 py-1.5 text-left hover:bg-muted hover:no-underline [&>svg]:order-first [&>svg]:h-3 [&>svg]:w-3 [&>svg]:-rotate-90 [&>svg]:text-muted-foreground/70 data-[state=open]:[&>svg]:rotate-90",children:l.jsxs("div",{title:Se,className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l.jsx("span",{className:"max-w-[180px] truncate text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:Se}),l.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:Oe.length})]})}),l.jsx(mv,{className:"pb-2",children:l.jsx("div",{className:"space-y-1",children:Oe.map(Ye=>{const bt=Ie.get(Be(Ye)),St=t==="editor"&&ce&&Qa(Ye);return l.jsx(oK,{field:Ye,context:t,fieldState:bt,onFieldSelect:n,inlineFilters:t==="inline-filter"||t==="document-filter"?r:void 0,actions:St?he(Ye):void 0,onHover:g(Ye,bt)},Ye.id)})})})]},ge))]}),ie.length===0&&l.jsxs("div",{className:"px-4 py-6 text-center",children:[l.jsx("p",{className:"text-[12px] text-foreground",children:"No fields found for selected data source"}),l.jsx("p",{className:"mt-1 text-[11px] leading-[1.45] text-muted-foreground",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),ie.length>0&&Ke.length===0&&!$e&&l.jsx("div",{className:"py-4 text-center text-[11px] text-muted-foreground",children:"No fields found for this category"}),l.jsx(p.ScrollBar,{orientation:"vertical"})]})]}),u&&l.jsx("div",{style:{position:"fixed",top:u.top,left:u.left},className:"pointer-events-none z-50 w-[280px] overflow-hidden rounded-control border border-border bg-popover shadow-[0_4px_16px_rgba(0,0,0,0.08)]",children:l.jsx(Hht,{field:u.field,fieldState:u.fieldState})}),l.jsx(ff,{open:!!_,onOpenChange:ge=>{ge||k(null)},children:l.jsxs(ku,{children:[l.jsxs(_u,{children:[l.jsx(Tu,{children:"Delete calculated field?"}),l.jsxs(Eu,{children:["This will remove"," ",l.jsx("span",{className:"font-medium text-foreground",children:(_==null?void 0:_.label)||(_==null?void 0:_.name)||"this calculated field"})," ",(_==null?void 0:_.fieldScope)==="domain"?"from the semantic domain.":"from this configuration."]})]}),l.jsxs(Iu,{children:[l.jsx(Mu,{disabled:T,children:"Cancel"}),l.jsx(Du,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:T,onClick:ge=>{ge.preventDefault(),De()},children:T?"Deleting...":"Delete"})]})]})}),l.jsx(fme,{open:b,onOpenChange:ge=>{x(ge),ge||(w(null),N("card"))},availableFields:Y,existingField:y??void 0,existingFieldScope:C,initialFieldType:S,onSave:ge=>{const Se=y,Oe=C==="dashboard"?P:(A==null?void 0:A.calculatedFields)||[];if(ge.role==="metric"){const{nextActiveFields:sn,nextSortByFields:Le,nextStoredFields:et,nextSharedFields:at}=IF({activeFields:ae,sortByFields:J,storedFields:re,sharedFields:Oe,updatedField:ge,editingField:Se,previousScope:C});(sn||Le)&&F(R.id,{...sn?{metricColumns:sn}:{},...Le?{sortByColumns:Le}:{}}),z(R.id,{calculatedFields:et}),C==="dashboard"&&at!==Oe?B(at):A&&at!==Oe&&Jf({nextSharedFields:at,currentSharedFields:Oe,isVisualEditing:$,selectedSheetId:H,updateFrame:L,updateSheetCalculatedFields:M});return}const{nextActiveFields:Ye,nextSortByFields:bt,nextStoredFields:St,nextSharedFields:on}=IF({activeFields:ee,sortByFields:J,storedFields:re,sharedFields:Oe,updatedField:ge,editingField:Se,previousScope:C});(Ye||bt)&&F(R.id,{...Ye?{groupByColumns:Ye}:{},...bt?{sortByColumns:bt}:{}}),z(R.id,{calculatedFields:St}),C==="dashboard"&&on!==Oe?B(on):A&&on!==Oe&&Jf({nextSharedFields:on,currentSharedFields:Oe,isVisualEditing:$,selectedSheetId:H,updateFrame:L,updateSheetCalculatedFields:M})},onSaveToSheet:ge=>{const Se=y,Oe=(A==null?void 0:A.calculatedFields)||[];if(ge.role==="metric"){const{nextActiveFields:Le,nextSortByFields:et,nextStoredFields:at,nextSheetFields:ht,nextDashboardFields:Vt}=TF({activeFields:ae,sortByFields:J,storedFields:re,sheetFields:Oe,dashboardFields:P,updatedField:ge,editingField:Se,previousScope:C});A&&Jf({nextSharedFields:ht,currentSharedFields:Oe,isVisualEditing:$,selectedSheetId:H,updateFrame:L,updateSheetCalculatedFields:M}),Vt&&Vt!==P&&B(Vt),(Le||et)&&F(R.id,{...Le?{metricColumns:Le}:{},...et?{sortByColumns:et}:{}}),z(R.id,{calculatedFields:at});return}const{nextActiveFields:Ye,nextSortByFields:bt,nextStoredFields:St,nextSheetFields:on,nextDashboardFields:sn}=TF({activeFields:ee,sortByFields:J,storedFields:re,sheetFields:Oe,dashboardFields:P,updatedField:ge,editingField:Se,previousScope:C});A&&Jf({nextSharedFields:on,currentSharedFields:Oe,isVisualEditing:$,selectedSheetId:H,updateFrame:L,updateSheetCalculatedFields:M}),sn&&sn!==P&&B(sn),(Ye||bt)&&F(R.id,{...Ye?{groupByColumns:Ye}:{},...bt?{sortByColumns:bt}:{}}),z(R.id,{calculatedFields:St})},onSaveToDashboard:ge=>{const Se=y,Oe=ge.role==="metric"?ae:ee,Ye=(A==null?void 0:A.calculatedFields)||[],{nextActiveFields:bt,nextSortByFields:St,nextStoredFields:on,nextSharedFields:sn,nextSheetFields:Le}=hme({activeFields:Oe,sortByFields:J,storedFields:re,sharedFields:P,sheetFields:Ye,updatedField:ge,editingField:Se,previousScope:C});B(sn),A&&Le&&Le!==Ye&&Jf({nextSharedFields:Le,currentSharedFields:Ye,isVisualEditing:$,selectedSheetId:H,updateFrame:L,updateSheetCalculatedFields:M}),(bt||St)&&F(R.id,{...bt?{[ge.role==="metric"?"metricColumns":"groupByColumns"]:bt}:{},...St?{sortByColumns:St}:{}}),z(R.id,{calculatedFields:on})},cardId:R.id})]})}),mme=v.memo(function({context:t,className:n,inlineFilters:r,onFieldSelect:o}){return l.jsx("div",{"data-content":"filterable-fields-panel",className:p.cn("flex min-h-0 grow flex-col overflow-hidden",n),children:l.jsx(nC,{collisionDetection:Jw,children:l.jsx(rC,{items:[],strategy:Lz,children:l.jsx(a4,{context:t,inlineFilters:r,onFieldSelect:o})})})})}),lpt=/{{\s*([A-Za-z_][A-Za-z0-9_]*)(?:\.([A-Za-z_][A-Za-z0-9_]*))?\s*}}/g,cpt=new Set(["generatedAt","pageNumber","pageCount"]),l4="document",upt=/^(\d{4})-(\d{2})-(\d{2})$/;function dpt(e,t){const n=[],r=[];let o=0;for(const s of e.matchAll(lpt)){const i=s[0],a=s.index??0;a>o&&n.push({type:"text",value:e.slice(o,a),sourceStart:o,sourceEnd:a});const c=mpt({aliasOrKey:s[1],exportKey:s[2],inputs:t});c?n.push({type:"variable",ref:c,sourceStart:a,sourceEnd:a+i.length}):(n.push({type:"text",value:i,sourceStart:a,sourceEnd:a+i.length}),r.push(i)),o=a+i.length}return o<e.length&&n.push({type:"text",value:e.slice(o),sourceStart:o,sourceEnd:e.length}),{content:n,unresolvedTokens:r}}function fpt(e){return[...e.flatMap(n=>u4(n).map(r=>({label:`${n.variableName}.${r}`,token:`{{${n.variableName}.${r}}}`,ref:{source:"input",inputId:n.id,export:r}}))),{label:X1("generatedAt",e),token:c2("generatedAt",e),ref:{source:"documentMeta",key:"generatedAt"}},{label:X1("pageNumber",e),token:c2("pageNumber",e),ref:{source:"documentMeta",key:"pageNumber"}},{label:X1("pageCount",e),token:c2("pageCount",e),ref:{source:"documentMeta",key:"pageCount"}}]}function c4(e,t){if(e.source==="documentMeta")return X1(e.key,t);const n=t.find(r=>r.id===e.inputId);return`${(n==null?void 0:n.variableName)||e.inputId}.${e.export}`}function hpt({inputs:e,filterValuesByInputId:t,controlValuesByInputId:n,controlOptionsByInputId:r={},generatedAt:o,timezone:s,generatedAtFormat:i,pageNumber:a=1,pageCount:c=1}){const u={};for(const d of e)u[d.id]=d.kind==="filter"?gpt(d,t[d.id],s):bpt(d,n[d.id],s,r[d.id]);return{inputs:e,resolvedInputsById:u,timezone:s,generatedAtFormat:i,meta:{generatedAt:o,pageNumber:a,pageCount:c}}}function pme(e,t){return(e==null?void 0:e.map(n=>n.type==="text"?{type:"text",value:n.value,...n.format?{format:n.format}:{}}:{type:"variable",value:ppt(n.ref,t),...n.format?{format:n.format}:{}}))||[]}function mpt({aliasOrKey:e,exportKey:t,inputs:n}){if(e===l4&&t&&cK(t))return{source:"documentMeta",key:t};const r=n.find(o=>o.variableName===e);if(r){const o=t||ypt(r);return!gme(o)||!new Set(u4(r)).has(o)?null:{source:"input",inputId:r.id,export:o}}return!t&&cK(e)?{source:"documentMeta",key:e}:null}function ppt(e,t){var o;if(e.source==="documentMeta")return e.key==="generatedAt"?yme(t.meta.generatedAt,t.timezone,t.generatedAtFormat||p.DEFAULT_DOCUMENT_GENERATED_AT_FORMAT):String(t.meta[e.key]);const n=t.resolvedInputsById[e.inputId],r=(o=n==null?void 0:n.exports)==null?void 0:o[e.export];return r==null?"":String(r)}function gpt(e,t,n){const r=(t==null?void 0:t.values)||[];if(p.getDataType(e.filter.dataType)==="date"){const a=r[0]?uk(r[0],n):"",c=r[1]?uk(r[1],n):"",u=a&&c?`${a} - ${c}`:a||c;return{inputId:e.id,variableName:e.variableName,rawValue:r.length>1?r:r[0]??null,displayValue:u,filterValues:t?[t]:void 0,exports:{label:u||null,value:u||null,start:a||null,end:c||null,range:u||null}}}const i=r.map(Cpt).join(", ");return{inputId:e.id,variableName:e.variableName,rawValue:r.length>1?r:r[0]??null,displayValue:i,filterValues:t?[t]:void 0,exports:{label:i||null,value:i||null}}}function bpt(e,t,n,r=[]){const o=wpt(t),i=o.map(c=>e.control.type==="date"?uk(c,n):vpt(e.control,c,r)).join(", "),a=o.map(xme).join(", ");return{inputId:e.id,variableName:e.variableName,rawValue:t??null,displayValue:i,controlValue:t,exports:{label:i||null,value:a||null}}}function u4(e){const t=xpt(e),n=(e.exports||[]).filter(gme);return Array.from(new Set([...t,...n]))}function xpt(e){return e.kind==="filter"?p.getDataType(e.filter.dataType)==="date"?["label","start","end","range"]:["label","value"]:["label","value"]}function ypt(e){const t=u4(e);return t.includes("label")?"label":t.includes("range")?"range":t[0]||"value"}function gme(e){return e==="label"||e==="value"||e==="start"||e==="end"||e==="range"}function cK(e){return cpt.has(e)}function bme(e,t){return t.some(n=>n.variableName===e)}function c2(e,t){return bme(e,t)?`{{${l4}.${e}}}`:`{{${e}}}`}function X1(e,t){return bme(e,t)?`${l4}.${e}`:e}function vpt(e,t,n=[]){var s;const r=xme(t),o=n.find(i=>i.value===r);return o?o.label:e.source.kind==="manual"&&((s=e.source.options.find(i=>i.value===r))==null?void 0:s.label)||r}function wpt(e){return e==null?[]:Array.isArray(e)?e:[e]}function Cpt(e){return e instanceof Date?uk(e):e==null?"":String(e)}function xme(e){return e instanceof Date?e.toISOString():e==null?"":String(e)}function uk(e,t){return e?yme(e,t,"MMM d, yyyy"):""}function yme(e,t,n){const r=Npt(n),o=Spt(e);if(o)return Kt.format(o,r);const s=e instanceof Date?e:new Date(String(e));return Number.isNaN(s.getTime())?e==null?"":String(e):Kt.formatInTimeZone(s,t||"UTC",r)}function Spt(e){if(typeof e!="string")return null;const t=upt.exec(e.trim());if(!t)return null;const n=Number(t[1]),r=Number(t[2]),o=Number(t[3]),s=new Date(n,r-1,o);return s.getFullYear()!==n||s.getMonth()!==r-1||s.getDate()!==o?null:s}function Npt(e){return e.replace(/\[([^\]]+)\]/g,"'$1'").replace(/YYYY/g,"yyyy").replace(/YY/g,"yy").replace(/DD/g,"dd").replace(/D/g,"d").replace(/A/g,"a")}const sC={text:"Text",table:"Table",chart:"Chart",spacer:"Spacer",page_break:"Page break"},vme=["text","table","spacer","page_break"];function pv(e){return e==="table"?p.Table2:e==="text"?p.Type:e==="spacer"?Ave:e==="page_break"?Mve:Qs}function jpt(e){const t=`doc_section_${dt.v4()}`;return e==="text"?{id:t,type:"text",content:p.textContent("New text section")}:e==="table"?{id:t,type:"table",title:"Table",card:{id:`doc_card_${t}`,title:"Table",type:"table",preferences:{tablePrefs:{density:"compact",tableStyle:{headerStyle:"filled",stripedRows:!1,gridLines:"horizontal",wrapText:!1,totals:{enabled:!1}}}}},table:{totalsRow:!1,repeatHeaderOnPageBreak:!0,rowHeightPx:28}}:e==="spacer"?{id:t,type:"spacer",heightPx:24}:{id:t,type:"page_break"}}function u2(e,t){if(e.type==="text"){const n=p.textContentToString(e.content,t).trim();return n?n.split(`
|
|
1295
1295
|
`)[0].slice(0,40):"Text"}return e.type==="table"?e.title||e.card.title||"Table":e.type==="spacer"?`Spacer (${e.heightPx}px)`:sC[e.type]}function kpt(e,t){if(e.type==="spacer")return"Spacer";if(e.type==="text"){const n=p.textContentToString(e.content,t).trim();return n?n.split(`
|
|
1296
1296
|
`)[0].slice(0,28):"Text section"}return e.type==="table"?e.title||e.card.title||"Table":e.type==="page_break"?"Page break":sC[e.type]}function _pt(e){return e.type==="spacer"?`${e.heightPx} px`:e.type==="table"?"Table":null}const $f=Rd,zf=ha,Ipt={spacious:40,comfortable:36,standard:32,compact:28,dense:24};function d4(e){var t;return p3((t=e.card.preferences)==null?void 0:t.tablePrefs)}function Tpt(e){return[e.density,e.headerStyle,e.headerBackgroundColor,e.headerTextColor,e.headerWrapText,e.stripedRows,e.gridLines,e.wrapText,e.totalsStyle.backgroundColor,e.totalsStyle.textColor,e.totalsStyle.fontWeight,e.totalsStyle.borderTop,e.totalsStyle.borderTopStyle,e.totalsStyle.borderTopColor].join(":")}const Ept=Uoe;function EF(e){return Ipt[e]}function Dpt(e){return e.table.rowHeightPx??EF(d4(e).density)}function Mpt(e){const t=new Set;return e.forEach(n=>{Object.keys(n).forEach(r=>t.add(r))}),Array.from(t)}function wme(e){var o;if(e.type!=="table"||e.card.type!=="table")return"";const t=e.card,n=t.config,r=t.dataSource;return JSON.stringify({type:t.type,connectionId:t.connectionId||(r==null?void 0:r.connectionId)||"",sql:((o=t.sql)==null?void 0:o.trim())||"",datamodelId:t.datamodelId||(r==null?void 0:r.datamodelId)||"",semanticDomainId:(r==null?void 0:r.semanticDomainId)||"",selectedEntities:(r==null?void 0:r.selectedEntities)||null,lastSelectedDatabase:t.lastSelectedDatabase||"",lastSelectedSchema:t.lastSelectedSchema||"",lastSelectedTable:t.lastSelectedTable||"",detailColumns:QS(n==null?void 0:n.detailColumns),groupByColumns:QS(n==null?void 0:n.groupByColumns),metricColumns:QS(n==null?void 0:n.metricColumns),pivotByColumns:QS(n==null?void 0:n.pivotByColumns)})}function QS(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object")return String(t??"");const n=t;return{id:n.id,alias:n.alias,name:n.name,label:n.label,column:n.column,expression:n.expression,aggregate:n.aggregate,aggregation:n.aggregation,dataType:n.dataType,type:n.type}}):[]}function cc(e){return e.kind==="filter"}function Ql(e){return e.kind==="control"}function Cme(e,t){return e.reduce((n,r)=>{if(!cc(r))return n;const o=p.buildFilterValueFromDefaults(r.filter,t);return o&&(n[r.id]=o),n},{})}function Sme(e){return e.reduce((t,n)=>{if(!Ql(n))return t;const r=p.buildAuthoringPreviewControlValues({controls:[n.control]});return Object.prototype.hasOwnProperty.call(r,n.control.id)&&(t[n.id]=r[n.control.id]),t},{})}function Rpt(e){return e.map(t=>`${t.id}:${jme(t)}`).join("|")}function Nme(e){return e.reduce((t,n)=>(t[n.id]=jme(n),t),{})}function jme(e){return Ql(e)?JSON.stringify({kind:e.kind,controlId:e.control.id,type:e.control.type,source:e.control.source}):JSON.stringify({kind:e.kind,filterId:e.filter.id,connectionId:e.filter.connectionId,qualifiedTableName:e.filter.qualifiedTableName||null,table:e.filter.table||null,database:e.filter.database||null,sql:e.filter.sql,column:e.filter.column,dataType:e.filter.dataType,operation:e.filter.operation,type:e.filter.type||null,fieldMeta:e.filter.fieldMeta||null,semanticContext:e.filter.semanticContext||null,targetColumns:e.filter.targetColumns||null})}function Apt(e,t,n,r,o){const s={};for(const i of t){if(!cc(i))continue;const a=e[i.id],c=iC(i.id,r,o),u=gv(i,a),d=Object.prototype.hasOwnProperty.call(e,i.id);if(!c&&d&&!a){s[i.id]=void 0;continue}if(!c&&u){s[i.id]=u;continue}n[i.id]&&(s[i.id]=n[i.id])}return Lpt(e,s)?e:s}function Ppt(e,t,n,r,o){const s={};for(const i of t){if(!Ql(i))continue;if(!iC(i.id,r,o)&&Object.prototype.hasOwnProperty.call(e,i.id)){s[i.id]=e[i.id];continue}Object.prototype.hasOwnProperty.call(n,i.id)&&(s[i.id]=n[i.id])}return $pt(e,s)?e:s}function f4(e,t){const n={...t,filterId:e.filter.id};return p.isCompatibleFilterValue(e.filter,n)?Fpt(e).has(t.name):!1}function gv(e,t){if(!(!t||!f4(e,t)))return t.filterId===e.filter.id?t:{...t,filterId:e.filter.id}}function Fpt(e){return new Set([e.filter.column,...(e.filter.targetColumns||[]).map(t=>t.column)])}function Opt(e,t){const n=new Set(t.filter(o=>cc(o)&&vT(o.filter.operation)).map(o=>o.id)),r={};for(const[o,s]of Object.entries(e))n.has(o)&&(r[o]=s);return zpt(e,r)?e:r}function Lpt(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(o=>e[o]===t[o])}function $pt(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(o=>Object.is(e[o],t[o]))}function zpt(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(o=>e[o]===t[o])}function vT(e){return e==="in"||e==="not in"}function kme(e){return e==="not in"?"exclude":"include"}function DF(e){return e==="exclude"?"not in":"in"}function Bpt(e,t,n,r){return t.map(o=>{if(!cc(o))return;const s=e[o.id];if(!(!s||iC(o.id,n,r)||!f4(o,s)))return gv(o,s)}).filter(o=>!!o)}function Vpt(e,t,n,r){return t.reduce((o,s)=>(!Ql(s)||iC(s.id,n,r)||!Object.prototype.hasOwnProperty.call(e,s.id)||(o[s.control.id]=e[s.id]),o),{})}function _me(e,t,n,r,o){return e.filter(s=>s.requiredAtExecution?iC(s.id,r,o)?!0:cc(s)?!t[s.id]||!f4(s,t[s.id]):!Hpt(n,s.id):!1).map(s=>s.label)}function Hpt(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))return!1;const n=e[t];return n==null?!1:Array.isArray(n)?n.length>0:typeof n=="string"?n.trim().length>0:!0}function iC(e,t,n){const r=n[e];return!!r&&r!==t[e]}const qpt=["table","pivotTable"];function Upt(e){return{id:`doc_editor_frame_${e.id}`,cards:[e.card],activeCardId:e.card.id}}function Wpt(e,t){return e.cards.find(n=>n.id===t)||null}function Kpt(e){return qpt.includes(e.type)}function Gpt(){const e=p.useDashboardStore(I=>I.dashboard),t=p.useEditorStore(I=>I.selectedConnectionId),n=p.useEditorStore(I=>I.selectedDatabaseName),r=p.useEditorStore(I=>I.selectedSchemaName),o=p.useEditorStore(I=>I.selectedTableName),s=p.useEditorStore(I=>I.selectedDatamodelId),{clearSelectedVisual:i}=Dm(),{setIsDashboardEditing:a,setIsVisualEditing:c}=p.useDashboardActions(),{setFrame:u,setCard:d,setIsDevMode:f,initializeModeDrafts:h,setActiveTabCardId:m,updateDataSource:g,setQueryResultColumns:b,setFilterValues:x,setInlineFilterValuesMap:y,setApplyFilters:w,clearModeDrafts:C,setEditorContext:N}=p.useEditorActions(),S=p.useEditorStore(I=>I.actions.setSelectedConnectionId),j=p.useEditorStore(I=>I.actions.setSelectedDatamodelId),_=p.useEditorStore(I=>I.actions.setSelectedDatabaseName),k=p.useEditorStore(I=>I.actions.setSelectedSchemaName),T=p.useEditorStore(I=>I.actions.setSelectedTableName);return v.useCallback((I,E,D=[],R=[],A={},F=[])=>{const z=Upt(E);i(),C(),N({type:"documentSection",sheetId:I,sectionId:E.id,cardId:E.card.id,documentFilterValues:Ypt(D),documentControlDefinitions:Zpt(R),documentControlValues:{...A},missingRequiredInputLabels:[...F]}),S_({frame:z,card:E.card,setFrame:u,setCard:d,setIsDevMode:f,initializeModeDrafts:h,setActiveTabCardId:m,updateDataSource:g,setQueryResultColumns:b,setSelectedConnectionId:S,setSelectedDatabaseName:_,setSelectedSchemaName:k,setSelectedTableName:T,setSelectedDatamodelId:j,setFilterValues:x,setInlineFilterValuesMap:y,setApplyFilters:w,setIsDashboardEditing:a,setIsVisualEditing:c,dashboard:e,selectedSheetId:I,selectedFrameId:null,currentSelections:{connectionId:t,databaseName:n,schemaName:r,tableName:o,datamodelId:s}})},[C,i,e,h,t,n,s,r,o,m,w,d,N,x,u,y,a,f,c,b,S,_,j,k,T,g])}function Ypt(e){return e.map(t=>({...t,values:[...t.values]}))}function Zpt(e){return e.map(t=>({...t,source:t.source.kind==="manual"?{...t.source,options:t.source.options.map(n=>({...n}))}:{...t.source}}))}function d2({inputs:e,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,onOptionsChange:o}){return l.jsx(l.Fragment,{children:e.filter(Ql).map(s=>l.jsx(Xpt,{input:s,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,onOptionsChange:o},s.id))})}function Xpt({input:e,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,onOptionsChange:o}){const s=e.control,i=s.source.kind==="sql_query"?s.source:void 0,a=qw({controlId:s.id,source:i,enabled:!!i,controlDefinitionsOverride:n,controlValuesOverride:r,activeFiltersOverride:t}),c=v.useMemo(()=>i?[]:nz(s),[s,i]),u=i?a.options:c;return v.useEffect(()=>{o(e.id,u)},[e.id,o,u]),null}function MF({children:e,className:t,empty:n,wrap:r=!1}){const o=v.Children.toArray(e).filter(s=>s!=null);return o.length===0?n??null:l.jsx("div",{className:p.cn("flex items-center gap-2 pr-1",r?"min-w-0 flex-wrap gap-y-2":"min-w-max",t),children:o})}function f2({children:e,className:t}){return l.jsx("div",{className:p.cn("shrink-0",t),children:e})}const Q1=({dataType:e})=>ek(e),Ime=["day","week","month","quarter","year"],Qpt=[...Ime,"hour","minute","second"],Jpt=e=>p.isDateTimeLikeDataType(e),Tme=e=>Jpt(e)?Qpt:Ime;function Eme(e){const{controlId:t,onCommit:n}=e,[r,o]=v.useState(t);return l.jsx(p.Input,{size:"xs",value:r,onChange:s=>o(s.target.value),onBlur:()=>{n(r),o(s=>s.trim().length===0?t:s)}})}function uK(e){const{control:t,onChange:n}=e,r=p.ensureManualSource(t),o=r.source.kind==="manual"?r.source.options:[],i=!!p.getPresetOptionsForControlType(t.type),a=h=>{n({...r,source:{kind:"manual",options:h}})},c=()=>{const h=o.length+1,m=`Option ${h}`;a([...o,{label:m,value:p.slugifyControlValue(m)||`option_${h}`}])},u=(h,m)=>{a(o.map((g,b)=>{if(b!==h)return g;const x=p.slugifyControlValue(g.label),y=p.slugifyControlValue(m)||g.value,w=g.value.trim().length===0||g.value===x;return{...g,label:m,value:w?y:g.value}}))},d=(h,m)=>{a(o.map((g,b)=>b===h?{...g,value:m}:g))},f=h=>{a(o.filter((m,g)=>g!==h))};return l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Options"}),!i&&l.jsxs(p.Button,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:c,children:[l.jsx(Tr,{className:"mr-1 h-3 w-3"}),"Add option"]})]}),o.length===0?l.jsx("div",{className:"rounded-md border border-dashed p-2.5 text-xs text-muted-foreground",children:"No options yet."}):l.jsxs("div",{className:"rounded-md border",children:[l.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_32px] gap-2 border-b bg-muted/50 px-2.5 py-1.5",children:[l.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:"Label"}),l.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:"Value"}),l.jsx("span",{})]}),o.map((h,m)=>l.jsxs("div",{className:p.cn("grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_32px] items-center gap-2 px-2.5 py-1.5",m<o.length-1&&"border-b"),children:[l.jsx(p.Input,{size:"xs",value:h.label,placeholder:"Label",className:"h-7 text-xs",onChange:g=>u(m,g.target.value),disabled:i}),l.jsx(p.Input,{size:"xs",value:h.value,placeholder:"Value",className:"h-7 text-xs",onChange:g=>d(m,g.target.value),disabled:i}),l.jsx(p.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>f(m),disabled:i,children:l.jsx(el,{className:"h-3.5 w-3.5"})})]},`${t.id}-option-${m}`))]})]})}function egt(e){return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Choices (built in)"}),l.jsx("div",{className:"rounded-md border bg-muted/20 px-3 py-2 text-sm text-muted-foreground",children:e.options.map(t=>t.label).join(" · ")})]})}function tgt(e){return e?p.getDataType(e.dataType||"")==="date":!1}function ngt(e){if(!e)return;const t=p.readTemporalBucketAuthoringState({fieldId:e.id,dataType:e.dataType,granularity:e.granularity,format:e.format,dateFormat:e.dateFormat,customFormat:e.customFormat,semanticTemporalPresentation:e.semanticTemporalPresentation});return t.ok?t.granularity:void 0}function dK(e,t){return p.readTemporalBucketAuthoringSelection({fieldId:(e==null?void 0:e.id)||"structural-control-option",dataType:(e==null?void 0:e.dataType)||"date",granularity:t,format:e==null?void 0:e.format,dateFormat:e==null?void 0:e.dateFormat,customFormat:e==null?void 0:e.customFormat,semanticTemporalPresentation:e==null?void 0:e.semanticTemporalPresentation})}function rgt(e){var _,k;const{control:t,choices:n,choiceLabel:r,emptyMessage:o,onChange:s}=e,i=p.ensureManualSource(t),a=i.source.kind==="manual"?i.source.options:[],c=new Map(a.map(T=>[T.value,T])),u=new Set(a.map(T=>T.value)),[d,f]=v.useState(""),[h,m]=v.useState(((_=a[0])==null?void 0:_.value)||null),[g,b]=v.useState({}),x=T=>{s({...i,source:{kind:"manual",options:T}})},y=(T,I)=>{x(a.map(E=>E.value===T?I(E):E))},w=n.filter(({option:T})=>u.has(T.value)),C=h&&a.some(T=>T.value===h)?h:((k=a[0])==null?void 0:k.value)||null,N=w.find(({option:T})=>T.value===C)||w[0],S=n.filter(({option:T})=>{var E,D,R,A;if(u.has(T.value))return!1;const I=d.trim().toLowerCase();return I?T.label.toLowerCase().includes(I)||T.value.toLowerCase().includes(I)||((D=(E=T.presentation)==null?void 0:E.customFormat)==null?void 0:D.toLowerCase().includes(I))||((A=(R=T.presentation)==null?void 0:R.format)==null?void 0:A.presentation.mode)==="pattern"&&T.presentation.format.presentation.pattern.toLowerCase().includes(I):!0}),j=(T,I)=>{var M;const E=c.get(T.value),D=I?p.getDataType(I.dataType||""):void 0,R=tgt(I),A=R?((M=E==null?void 0:E.presentation)==null?void 0:M.granularity)??ngt(I):void 0,F=R&&A?dK(I,A):void 0,z=R&&A?p.readTemporalBucketAuthoringSelectionWithOverride({fieldId:(I==null?void 0:I.id)||T.value,dataType:(I==null?void 0:I.dataType)||"date",granularity:A,format:F==null?void 0:F.format},E==null?void 0:E.presentation):void 0,L=R&&A?qc.getTemporalBucketAuthoringOptions(A,z==null?void 0:z.format):[],$=g[T.value],H=$!==void 0?"custom":(z==null?void 0:z.value)||"auto";return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsxs("p",{className:"text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Editing selected ",r.slice(0,-1).toLowerCase()]}),l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[l.jsx("div",{className:"shrink-0",children:l.jsx(Q1,{dataType:(I==null?void 0:I.dataType)||"string"})}),l.jsx("span",{className:"text-sm font-medium text-foreground/90",children:(E==null?void 0:E.label)??T.label}),D?l.jsx(mi,{variant:"outline",className:"text-[11px]",children:D}):null,"aggregate"in(I||{})&&typeof(I==null?void 0:I.aggregate)=="string"?l.jsx(mi,{variant:"secondary",className:"text-[11px]",children:I.aggregate}):null]}),I!=null&&I.qualifiedFieldName?l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:I.qualifiedFieldName}):null]}),l.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(p.Label,{className:"text-[11px] text-muted-foreground",children:"Shown as"}),l.jsx(p.Input,{size:"xs",value:(E==null?void 0:E.label)??T.label,onChange:B=>y(T.value,W=>({...W,label:B.target.value}))})]}),R?l.jsxs("div",{className:"space-y-1",children:[l.jsx(p.Label,{className:"text-[11px] text-muted-foreground",children:"Granularity"}),l.jsxs(p.Select,{value:A,onValueChange:B=>{const W=B;b(G=>{const Z={...G};return delete Z[T.value],Z});const P=qc.reconcileTemporalBucketAuthoringFormat((z==null?void 0:z.format)??dK(I,W).format,W);y(T.value,G=>({...G,presentation:{granularity:W,format:P}}))},children:[l.jsx(p.SelectTrigger,{size:"xs",children:l.jsx(p.SelectValue,{placeholder:"Select granularity..."})}),l.jsx(p.SelectContent,{children:Tme(I.dataType).map(B=>l.jsx(p.SelectItem,{value:B,children:B.charAt(0).toUpperCase()+B.slice(1)},B))})]})]}):null,R&&A?l.jsx("div",{className:"space-y-1 md:col-span-2",children:l.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(p.Label,{className:"text-[11px] text-muted-foreground",children:"Date format"}),l.jsxs(p.Select,{value:H,onValueChange:B=>{var P;let W=$??(z==null?void 0:z.customPattern)??"";if(B==="custom"){const G=L.find(X=>X.value==="custom"),Z=((P=G==null?void 0:G.format)==null?void 0:P.presentation.mode)==="pattern"?G.format.presentation.pattern:"";W=(z==null?void 0:z.customPattern)||Z||"",b(X=>({...X,[T.value]:W}))}else b(G=>{const Z={...G};return delete Z[T.value],Z});y(T.value,G=>({...G,presentation:{granularity:A,format:qc.resolveTemporalBucketAuthoringFormat(A,B,W)}}))},children:[l.jsx(p.SelectTrigger,{size:"xs",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:L.map(B=>l.jsx(p.SelectItem,{value:B.value,children:B.label},B.value))})]})]}),H==="custom"?l.jsxs("div",{className:"space-y-1",children:[l.jsx(p.Label,{className:"text-[11px] text-muted-foreground",children:"Custom format"}),l.jsx(p.Input,{size:"xs",value:$??(z==null?void 0:z.customPattern)??"",placeholder:"MMM YYYY",onChange:B=>{const W=B.target.value;b(P=>({...P,[T.value]:W})),y(T.value,P=>({...P,presentation:{granularity:A,format:qc.resolveTemporalBucketAuthoringFormat(A,"custom",W)}}))}})]}):null]})}):null]})]})};return l.jsxs("div",{className:"grid gap-4 md:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]",children:[l.jsxs("div",{className:"flex min-h-0 flex-col gap-3 rounded-lg border bg-muted/10 p-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsxs(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Add ",r.toLowerCase()]}),l.jsxs("div",{className:"relative",children:[l.jsx(Ft.Search,{className:"pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),l.jsx(p.Input,{size:"xs",value:d,name:`${t.id}-search-${r.toLowerCase()}`,placeholder:`Search ${r.toLowerCase()}…`,autoComplete:"off",onChange:T=>f(T.target.value),className:"pl-9 pr-9"}),d?l.jsx("button",{type:"button","aria-label":`Clear ${r.toLowerCase()} search`,className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>f(""),children:l.jsx(je.X,{className:"h-3.5 w-3.5"})}):null]})]}),n.length===0?l.jsx("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:o}):S.length===0?l.jsx("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:d.trim().length>0?"No matching fields found.":`All compatible ${r.toLowerCase()} are already selected.`}):l.jsx("div",{className:"h-[320px] overflow-y-auto pr-1",children:l.jsx("div",{className:"space-y-1",children:S.map(({option:T,target:I})=>{const E=I?p.getDataType(I.dataType||""):void 0;return l.jsxs("button",{type:"button",className:"group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all hover:bg-muted",onClick:()=>{x([...a,{...T}]),m(T.value),f("")},children:[l.jsx("div",{className:"shrink-0",children:l.jsx(Q1,{dataType:(I==null?void 0:I.dataType)||"string"})}),l.jsxs("div",{className:"min-w-0 flex-1 overflow-hidden",children:[l.jsx("div",{className:"truncate text-sm text-foreground/85 group-hover/container:text-foreground",children:(I==null?void 0:I.label)||T.label}),I!=null&&I.qualifiedFieldName?l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:I.qualifiedFieldName}):null]}),l.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[E?l.jsx(mi,{variant:"outline",className:"text-[11px]",children:E}):null,l.jsx(mi,{variant:"secondary",className:"text-[11px]",children:"Add"})]})]},`${t.id}-available-${T.value}`)})})})]}),l.jsxs("div",{className:"flex min-h-0 flex-col gap-3 rounded-lg border bg-card p-3",children:[l.jsxs("div",{className:"flex items-center justify-between gap-3",children:[l.jsxs(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Selected ",r.toLowerCase()]}),l.jsx(mi,{variant:"secondary",className:"text-[11px]",children:w.length})]}),w.length===0?l.jsx("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:"Choose at least one option from the catalog."}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"max-h-[220px] overflow-y-auto pr-1",children:l.jsx("div",{className:"space-y-1",children:w.map(({option:T,target:I})=>{const E=c.get(T.value),D=I?p.getDataType(I.dataType||""):void 0,R=(N==null?void 0:N.option.value)===T.value;return l.jsxs("div",{className:p.cn("flex items-center gap-2 rounded-lg border p-2 transition-colors",R?"border-foreground/20 bg-muted/40":"border-transparent hover:bg-muted/20"),children:[l.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-3 text-left",onClick:()=>m(T.value),children:[l.jsx("div",{className:"shrink-0",children:l.jsx(Q1,{dataType:(I==null?void 0:I.dataType)||"string"})}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-sm font-medium text-foreground/90",children:(E==null?void 0:E.label)??T.label}),I!=null&&I.qualifiedFieldName?l.jsx("div",{className:"truncate text-xs text-muted-foreground",children:I.qualifiedFieldName}):null]})]}),l.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[D?l.jsx(mi,{variant:"outline",className:"text-[11px]",children:D}):null,l.jsx(p.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7","aria-label":`Remove ${(E==null?void 0:E.label)??T.label}`,onClick:()=>{var F;const A=a.filter(z=>z.value!==T.value);x(A),C===T.value&&m(((F=A[0])==null?void 0:F.value)||null)},children:l.jsx(je.X,{className:"h-3.5 w-3.5"})})]})]},`${t.id}-selected-${T.value}`)})})}),l.jsx("div",{className:"rounded-lg border bg-muted/5 p-3",children:N?j(N.option,N.target):l.jsx("div",{className:"text-xs text-muted-foreground",children:"Select a field to configure how it appears in the control."})})]})]})]})}function Dme(e){if(e.participants.length===0)return null;const t=new Set(e.selectedCardIds);return l.jsxs("div",{className:"space-y-2",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Cards using this shared control"}),l.jsx("div",{className:"space-y-2 rounded-md border p-3",children:e.participants.map(n=>l.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[l.jsx(Tn,{checked:t.has(n.cardId),onCheckedChange:r=>{if(r===!0){e.onChange([...e.selectedCardIds,n.cardId]);return}e.onChange(e.selectedCardIds.filter(o=>o!==n.cardId))}}),l.jsxs("div",{className:"min-w-0",children:[l.jsx("div",{className:"font-medium",children:n.title}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:[n.choiceCount," ",e.type==="field_selector"?"compatible group-by fields":"compatible metrics"]})]})]},n.cardId))})]})}function ogt(e){const t=e.value===!0?"true":"false";return l.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[l.jsx(p.Button,{type:"button",variant:t==="true"?"default":"outline",onClick:()=>e.onChange(!0),children:"On"}),l.jsx(p.Button,{type:"button",variant:t==="false"?"default":"outline",onClick:()=>e.onChange(!1),children:"Off"})]})}function sgt(e){return e.scope==="dashboard"&&(e.type==="enum"||e.type==="multi_enum")}const Mme={kind:"sql_query",connectionId:"",sql:"",valueColumn:""};function fK(e){return{kind:"manual",options:e.options.map(t=>({...t,...t.presentation?{presentation:{...t.presentation}}:{}}))}}function hK(e){return{...e}}function igt(e){return e.source.kind==="sql_query"?e.source:Mme}function Rme(e){const t=h4(e);return JSON.stringify({controlId:e.controlId,source:oz(e.source),controlDefinitions:Lue(t.controlDefinitions),controlValues:Oue(t.controlValues,t.controlDefinitions),activeFilters:e.activeFiltersOverride??null})}function h4(e){const t=Pue(e.previewControlDefinitions),n={...e.previewControlValues||{}};delete n[e.controlId];const r=Fue(n,t);return{controlDefinitions:t,controlValues:r}}function agt(e){const[t,n]=v.useState(null),r=v.useRef(e);return v.useEffect(()=>{r.current!==e&&(r.current=e,n(null))},[e]),{requestedForCurrentKey:t===e,markCurrentKeyRequested:()=>n(e)}}function lgt(e){var C;const{control:t,onChange:n,previewControlDefinitions:r,previewControlValues:o,activeFiltersOverride:s}=e,i=igt(t),{connections:a,isPending:c}=Au(),u=t.id||"preview",d=i.connectionId.trim().length>0&&i.sql.trim().length>0&&i.valueColumn.trim().length>0,f=h4({controlId:u,previewControlDefinitions:r,previewControlValues:o}),h=Rme({controlId:u,source:i,previewControlDefinitions:r,previewControlValues:o,activeFiltersOverride:s}),{requestedForCurrentKey:m,markCurrentKeyRequested:g}=agt(h),b=qw({controlId:u,source:d?i:void 0,enabled:m&&d,controlDefinitionsOverride:f.controlDefinitions,controlValuesOverride:f.controlValues,activeFiltersOverride:s}),x=N=>{const S={...i,...N,kind:"sql_query"};(!S.labelColumn||S.labelColumn.trim().length===0)&&delete S.labelColumn,n({...t,source:S})},y=p.getRequestErrorMessage(b.error,""),w=b.options;return v.useEffect(()=>{var j;if(i.connectionId||a.length!==1)return;const N=(j=a[0])==null?void 0:j.id;if(!N)return;const S={...i,kind:"sql_query",connectionId:N};(!S.labelColumn||S.labelColumn.trim().length===0)&&delete S.labelColumn,n({...t,source:S})},[a,t,i,n]),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Connection"}),l.jsxs(p.Select,{value:i.connectionId,onValueChange:N=>{x({connectionId:N})},disabled:c||a.length===0,children:[l.jsx(p.SelectTrigger,{size:"xs",children:l.jsx(p.SelectValue,{placeholder:c?"Loading connections…":a.length===0?"No connections available":"Select a connection"})}),l.jsx(p.SelectContent,{children:a.map(N=>l.jsx(p.SelectItem,{value:N.id,children:N.name},N.id))})]})]}),i.connectionId.trim().length===0?l.jsxs("div",{className:"flex min-h-[200px] flex-col items-center justify-center gap-1 rounded-control border border-border/60 bg-muted/20 px-4 py-8 text-center",children:[l.jsx("p",{className:"text-[13px] font-medium text-foreground",children:"Pick a connection above"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Then write your SQL query to source options."})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL"}),l.jsx("div",{className:"h-24 w-full overflow-hidden rounded-control border border-input",onKeyDown:N=>N.stopPropagation(),children:l.jsx(p.CodeEditor,{value:i.sql,onValueChange:N=>x({sql:N}),language:"sql-jinja",embedded:!0,hideLineNumbers:!0,dense:!0,ariaLabel:"Control options SQL query",placeholder:"SELECT id, name FROM segments WHERE account_id = [[param.tenantId]]"})})]}),l.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Value column"}),l.jsx(p.Input,{size:"xs",value:i.valueColumn,placeholder:"id",onChange:N=>{x({valueColumn:N.target.value})}})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label column (optional)"}),l.jsx(p.Input,{size:"xs",value:i.labelColumn||"",placeholder:"name",onChange:N=>{x({labelColumn:N.target.value})}})]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(p.Button,{type:"button",variant:"outline",size:"xs",disabled:!d||b.isFetching,onClick:()=>{if(m){b.refetch();return}g()},children:b.isFetching?"Loading…":"Preview options"}),m&&!b.isFetching&&b.data?l.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[w.length," option",w.length===1?"":"s",(C=b.metadata)!=null&&C.truncated?" (truncated)":""]}):null]}),m&&b.isError?l.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Preview unavailable",y?` — ${y}`:""]}):null]})]})}function cgt(e){const{control:t,onChange:n,controlLifecycle:r="edit"}=e,o=t.source.kind==="sql_query"?"sql_query":"manual",s=v.useRef(t.source.kind==="manual"?fK(t.source):null),i=v.useRef(t.source.kind==="manual"?t.requiredAtExecution:null),a=v.useRef(t.source.kind==="sql_query"?hK(t.source):null);t.source.kind==="manual"?(s.current=fK(t.source),i.current=t.requiredAtExecution):t.source.kind==="sql_query"&&(a.current=hK(t.source));const c=u=>{if(u!==o){if(u==="manual"){n({...t,source:s.current||{kind:"manual",options:[]},requiredAtExecution:i.current??t.requiredAtExecution});return}n({...t,source:a.current||Mme,requiredAtExecution:t.initialValueStrategy==="embed_required"?!0:r==="create"?!1:t.requiredAtExecution})}};return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Option source"}),l.jsxs(rl,{value:o,onValueChange:u=>c(u),className:"flex flex-col gap-1.5",children:[l.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[l.jsx(vs,{value:"manual",className:"mt-0.5"}),l.jsxs("span",{children:[l.jsx("span",{className:"font-medium text-foreground",children:"Manual"}),l.jsx("span",{className:"ml-1 text-muted-foreground",children:"— enter label/value rows"})]})]}),l.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[l.jsx(vs,{value:"sql_query",className:"mt-0.5"}),l.jsxs("span",{children:[l.jsx("span",{className:"font-medium text-foreground",children:"SQL query"}),l.jsx("span",{className:"ml-1 text-muted-foreground",children:"— resolve options from a database query at runtime"})]})]})]})]})}function Ame(e){const t=p.getPresetOptionsForControlType(e.control.type),n=e.control.source.kind==="sql_query"?e.control:p.ensureManualSource(e.control),r=e.control.type==="field_selector"?e.availableFieldChoices||[]:e.control.type==="metric_selector"?e.availableMetricChoices||[]:[];if(t)return l.jsx(egt,{options:t});if(n.type==="field_selector"||n.type==="metric_selector"){const o=n.type==="field_selector"?"Fields":"Metrics",s=n.type==="field_selector"?"No valid group-by fields are available yet. Add fields to the card first.":"No valid metrics are available yet. Add metrics to the card first.";return l.jsx(rgt,{control:n,choices:r,choiceLabel:o,emptyMessage:s,onChange:e.onChange})}return p.needsManualOptions(n)?sgt(n)?l.jsxs("div",{className:"space-y-3",children:[l.jsx(cgt,{control:n,onChange:e.onChange,controlLifecycle:e.controlLifecycle}),n.source.kind==="sql_query"?l.jsx(lgt,{control:n,onChange:e.onChange,previewControlDefinitions:e.previewControlDefinitions,previewControlValues:e.previewControlValues,activeFiltersOverride:e.activeFiltersOverride}):l.jsx(uK,{control:n,onChange:e.onChange})]}):l.jsx(uK,{control:n,onChange:e.onChange}):null}function Pme(e){const{control:t,value:n,onChange:r,allowNoDefault:o=!1,allowCardDefault:s=!1,hint:i}=e;if(t.source.kind==="sql_query")return l.jsx(dgt,{control:t,value:n,onChange:r,allowNoDefault:o,allowCardDefault:s,hint:i,previewControlDefinitions:e.previewControlDefinitions,previewControlValues:e.previewControlValues,activeFiltersOverride:e.activeFiltersOverride});const a=p.ensureManualSource(t),c=p.getDefaultValueForType(t,n),d=p.getPresetOptionsForControlType(t.type)??(a.source.kind==="manual"?a.source.options:[]),f=t.type==="enum"||t.type==="field_selector"||t.type==="metric_selector"||t.type==="aggregation_selector"||t.type==="grain_selector";return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default"}),t.type==="boolean"?l.jsx(ogt,{value:c,onChange:r}):f&&d.length>0?l.jsx(Fme,{controlType:t.type,options:d,value:c,onChange:r,allowNoDefault:o,allowCardDefault:s}):f?l.jsx(p.Input,{size:"xs",value:"",placeholder:"Add choices first",disabled:!0,readOnly:!0}):l.jsx(p.Input,{size:"xs",value:Array.isArray(c)?c.join(", "):String(c??""),placeholder:t.type==="multi_enum"?"value_one, value_two":"Default value",onChange:h=>r(p.parseControlDefaultValue(a,h.target.value))}),i?l.jsx("p",{className:"text-[11px] text-muted-foreground",children:i}):null]})}function Fme(e){const{controlType:t,options:n,value:r,onChange:o,allowNoDefault:s=!1,allowCardDefault:i=!1}=e,a=i&&p.supportsCardDefaultValue(t),c=r===void 0&&s?p.CONTROL_SELECT_UI_VALUES.noDefault:r===xr.CONTROL_CARD_DEFAULT_VALUE&&a?p.CONTROL_SELECT_UI_VALUES.cardDefault:typeof r=="string"?p.findControlSelectOptionUiValue(n,r):void 0;return l.jsxs(p.Select,{value:c,onValueChange:u=>{if(u===p.CONTROL_SELECT_UI_VALUES.noDefault){o(void 0);return}if(u===p.CONTROL_SELECT_UI_VALUES.cardDefault){o(xr.CONTROL_CARD_DEFAULT_VALUE);return}const d=p.getControlSelectOptionFromUiValue(n,u);d&&o(d.value)},children:[l.jsx(p.SelectTrigger,{size:"xs",children:l.jsx(p.SelectValue,{placeholder:"Choose a default"})}),l.jsxs(p.SelectContent,{children:[s?l.jsx(p.SelectItem,{value:p.CONTROL_SELECT_UI_VALUES.noDefault,children:"No default"}):null,a?l.jsx(p.SelectItem,{value:p.CONTROL_SELECT_UI_VALUES.cardDefault,children:"Card default"}):null,n.map((u,d)=>l.jsx(p.SelectItem,{value:p.getControlSelectOptionUiValue(d),children:u.label},u.value))]})]})}function ugt(e){var a;const{options:t,value:n,onChange:r,allowNoDefault:o=!1}=e,s=p.normalizeControlStringArrayValue(n),i=s.length===0?o?"No default":"Choose defaults":s.length===1?((a=t.find(c=>c.value===s[0]))==null?void 0:a.label)||s[0]:`${s.length} selected`;return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(p.Popover,{children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsx(p.Button,{type:"button",variant:"outline",className:"w-full justify-between",children:l.jsx("span",{className:"truncate",children:i})})}),l.jsx(p.PopoverContent,{align:"start",className:"w-64",children:l.jsx("div",{className:"space-y-2",children:t.map(c=>{const u=s.includes(c.value);return l.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[l.jsx(Tn,{checked:u,onCheckedChange:d=>{const f=d?[...s,c.value]:s.filter(h=>h!==c.value);r(f.length>0?f:void 0)}}),l.jsx("span",{children:c.label})]},c.value)})})})]}),o&&s.length>0?l.jsx(p.Button,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground",onClick:()=>r(void 0),children:"Clear"}):null]})}function dgt(e){const{control:t,value:n,onChange:r,allowNoDefault:o=!1,allowCardDefault:s=!1,hint:i,previewControlDefinitions:a,previewControlValues:c,activeFiltersOverride:u}=e,d=t.source,f=t.id||"preview",h=d.connectionId.trim().length>0&&d.sql.trim().length>0&&d.valueColumn.trim().length>0,m=h4({controlId:f,previewControlDefinitions:a,previewControlValues:c});Rme({controlId:f,source:d,previewControlDefinitions:a,previewControlValues:c,activeFiltersOverride:u});const g=qw({controlId:f,source:h?d:void 0,enabled:!1,controlDefinitionsOverride:m.controlDefinitions,controlValuesOverride:m.controlValues,activeFiltersOverride:u}),b=g.data!==void 0&&!g.isError,x=g.options.map(N=>({value:N.value,label:N.label})),y=t.type==="multi_enum"?p.normalizeControlStringArrayValue(n):p.getDefaultValueForType(t,n),w=(()=>{const N=[...x],S=new Set(N.map(_=>_.value)),j=_=>{typeof _!="string"||_.length===0||S.has(_)||(S.add(_),N.push({value:_,label:_}))};return Array.isArray(y)?y.forEach(j):j(y),N})(),C=b&&w.length>0;return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default"}),C&&t.type==="multi_enum"?l.jsx(ugt,{options:w,value:y,onChange:r,allowNoDefault:o}):C?l.jsx(Fme,{controlType:t.type,options:w,value:y,onChange:r,allowNoDefault:o,allowCardDefault:s}):l.jsx(p.Input,{size:"xs",value:"",placeholder:h?"Preview options above to pick a default (optional)":"Complete the SQL source to pick a default (optional)",disabled:!0,readOnly:!0}),i?l.jsx("p",{className:"text-[11px] text-muted-foreground",children:i}):null]})}function fgt(e){const{control:t,onChange:n}=e;return l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"space-y-1",children:l.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx(Tn,{checked:t.hidden===!0,onCheckedChange:r=>n({...t,hidden:r===!0})}),"Hide control UI from viewers"]})}),l.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx(Tn,{checked:t.locked===!0,onCheckedChange:r=>n({...t,locked:r===!0})}),"Locked"]})]})}function Ome(e){const t=nv(e);return e.scope==="dashboard"?t==="advanced"?"More controls":"dashboard toolbar":t==="advanced"?"More options":"card header"}function hgt(e){const t=new Map;for(const n of e.controls||[])t.set(n.id,0);for(const n of p.getDashboardCards(e)){const r=new Set(Hw(n));for(const o of r)t.has(o)&&t.set(o,(t.get(o)||0)+1)}return Object.fromEntries((e.controls||[]).map(n=>{if(n.hidden)return[n.id,{tone:"default",status:"Hidden from viewers",helper:"This control can still be used by connected cards, but it will not appear in the dashboard UI."}];const r=t.get(n.id)||0,o=Ome(n);return r===0?[n.id,{tone:"warning",status:"Not used by any cards yet",helper:`This control is already available in the ${o}. Next: open a card's Controls and either bind this control or reference [[param.${n.id}]] in SQL.`}]:[n.id,{tone:"success",status:`Used in ${r} ${r===1?"card":"cards"}`,helper:`Available in the ${o}. ${r===1?"That card":"Those cards"} will respond when the value changes.`}]}))}function mgt(e){const t=new Set(Hw(e.card));return Object.fromEntries(e.controls.map(n=>{var o;const r=Ome(n);return n.hidden?[n.id,{tone:"default",status:"Hidden from viewers",helper:"This control is available for runtime state but will not appear in this card UI."}]:t.has(n.id)?[n.id,{tone:"success",status:"Used by this card",helper:`Available in the ${r} for this card.`}]:[n.id,{tone:"warning",status:"Not used by this card yet",helper:(o=e.card)!=null&&o.sql?`Reference [[param.${n.id}]] in this card's SQL to make the card respond to it.`:"Choose what this control changes below to make this card respond to it."}]}))}function pgt(e){let t=0,n=0,r=0;const o=[];for(const s of p.getDashboardCards(e.dashboard)){if(!new Set(Hw(s)).has(e.controlId))continue;t+=1,o.push(s.title||s.id),IY({sql:s.sql,controlBindings:s.controlBindings}).some(u=>u.controlId===e.controlId)&&(n+=1),(s.controlBindings||[]).some(u=>u.target!=="sql_param"&&u.target!=="presentation_currency"&&u.controlId===e.controlId)&&(r+=1)}return{totalCards:t,sqlCards:n,configCards:r,cardTitles:o}}function Lme(e){var n;const t=new Map;for(const r of p.getDashboardCards(e))for(const o of r.controlBindings||[])o.target!=="config_field_selector"&&o.target!=="config_metric_selector"||(t.has(o.controlId)||t.set(o.controlId,new Set),(n=t.get(o.controlId))==null||n.add(r.id));return Object.fromEntries(Array.from(t.entries()).map(([r,o])=>[r,Array.from(o)]))}function ggt(e){var n;return(((n=e.dataSource)==null?void 0:n.selectedEntities)||[]).filter(r=>r.type!=="file"&&r.type!=="url"&&r.type!=="upload").map(r=>({cardId:e.id,target:r}))}function bgt(e){if(e.type==="model")return`model:${e.connectionId}:${e.id}`;if(e.type==="dataset"){const t=e;return`dataset:${t.connectionId}:${t.domainId}:${t.name}`}return`table:${e.connectionId}:${e.database||""}:${e.schema||""}:${e.name}`}function xgt(e){const t=new Map;return e.flatMap(n=>ggt(n)).forEach(({cardId:n,target:r})=>{const o=bgt(r),s=t.get(o);if(!s){t.set(o,{key:o,cardIds:[n],target:r});return}s.cardIds.includes(n)||s.cardIds.push(n)}),Array.from(t.values())}function ygt(e){if(e.type==="dataset"){const t=e;return!!(t.connectionId&&t.domainId&&t.name)}if(e.type==="model"){const t=e;return!!(t.connectionId&&t.id)}return!!(e.connectionId&&e.name)}function vgt(e){if(e.type==="model"){const t=e;return{connection_id:t.connectionId,datamodel_id:t.id,database_name:"",schema_name:"",table_name:""}}if(e.type==="dataset"){const t=e;return{connection_id:t.connectionId,domain_id:t.domainId,dataset_name:t.name}}return{connection_id:e.connectionId,datamodel_id:"",database_name:e.database,schema_name:e.schema,table_name:e.name}}function wgt(e){const{target:t,column:n}=e,r=p.getQualifiedEntityName(t);return{id:`${t.name}-${n.column_name}`,name:n.column_name,qualifiedFieldName:n.qualifiedFieldName||n.column_name,dataType:n.data_type,label:n.label||n.column_name,description:n.description||"",qualifiedEntityName:r,entityId:t.id||t.id||t.name,entityName:t.name,entityType:t.type,role:n.role==="metric"?"metric":void 0,expression:n.expression,calculatedFormula:n.calculatedFormula,...Mhe(n)}}function $me(e){const{tokenProps:t}=It(),n=p.useDashboardStore(c=>c.authToken),r=v.useMemo(()=>xgt(e),[e]),o=ib({queries:r.map(({key:c,target:u})=>({queryKey:["dashboard-structural-columns",c],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",vgt(u)),enabled:!!(n!=null&&n.accessToken)&&ygt(u)}))}),s=o.some(c=>c.isPending&&c.fetchStatus==="fetching"),i=v.useMemo(()=>{const c=new Map;return o.forEach((u,d)=>{const f=r[d],h=f==null?void 0:f.target;if(!f||!h||!u.data)return;const m=[...(u.data.columns||[]).map(g=>wgt({target:h,column:g})),...u.data.calculatedFields||[]];f.cardIds.forEach(g=>{c.set(g,[...c.get(g)||[],...m])})}),c},[o,r]);return{participants:v.useMemo(()=>e.map(c=>{var b,x,y,w,C;const u=i.get(c.id)||[],d=((y=(x=(b=c.config)==null?void 0:b.metricColumns)==null?void 0:x[0])==null?void 0:y.aggregate)||"SUM",f=p.buildDashboardFieldSelectorChoicesFromFields(u),h=p.buildDashboardMetricSelectorChoicesFromFields(u,d),m=p.getFieldSelectorChoicesForCard(c),g=p.getMetricSelectorChoicesForCard(c);return{cardId:c.id,title:c.title||c.id,canBindStructuralControl:!!c.config,fieldChoices:f.choices.length>0?f.choices:m,metricChoices:h.choices.length>0?h.choices:g,fieldTargetMap:f.choices.length>0?f.targetMap:Object.fromEntries((((w=c.config)==null?void 0:w.groupByColumns)||[]).filter(N=>typeof N.id=="string").map(N=>[N.id,N])),metricTargetMap:h.choices.length>0?h.targetMap:Object.fromEntries((((C=c.config)==null?void 0:C.metricColumns)||[]).filter(N=>typeof N.id=="string").map(N=>[N.id,N]))}}),[e,i]),isLoading:s}}function zme({control:e,defaultValue:t,defaultPlacement:n,placementOptions:r,previewControlDefinitions:o,previewControlValues:s,availableFieldChoices:i=[],availableMetricChoices:a=[],structuralParticipantSelector:c,allowCardDefault:u=!1,allowControlIdEdit:d=!0,showPlacementSelect:f=!0,showViewerVisibilityToggle:h=!0,activeFiltersOverride:m,onChangeControl:g,onChangeDefaultValue:b,onCommitControlId:x}){const y="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",w=d&&!!x,C=f?w?"grid grid-cols-3 gap-2":"grid grid-cols-2 gap-2":w?"grid grid-cols-2 gap-2":"grid grid-cols-1 gap-2";return l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:C,children:[l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx(p.Label,{className:y,children:"Label"}),l.jsx(p.Input,{size:"xs",value:e.label,placeholder:"Control label",onChange:N=>g(S=>({...S,label:N.target.value}))})]}),w?l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx(p.Label,{className:y,children:"Variable name"}),l.jsx(Eme,{controlId:e.id,onCommit:x},e.id)]}):null,f?l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx(p.Label,{className:y,children:"Show in"}),l.jsxs(p.Select,{value:e.placement||n,onValueChange:N=>g(S=>({...S,placement:N})),children:[l.jsx(p.SelectTrigger,{size:"xs",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:r.map(N=>l.jsx(p.SelectItem,{value:N.value,children:N.label},N.value))})]})]}):null]}),c,l.jsx(Ame,{control:e,availableFieldChoices:i,availableMetricChoices:a,previewControlDefinitions:o,previewControlValues:s,activeFiltersOverride:m,controlLifecycle:"edit",onChange:N=>g(()=>N)}),e.initialValueStrategy==="saved_default"&&l.jsx(Pme,{control:e,value:t,allowNoDefault:!0,allowCardDefault:u,previewControlDefinitions:o,previewControlValues:s,activeFiltersOverride:m,onChange:b}),l.jsx("div",{className:"grid grid-cols-1 gap-2",children:l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx(p.Label,{className:y,children:"Initial value"}),l.jsxs(p.Select,{value:e.initialValueStrategy,onValueChange:N=>g(S=>({...S,initialValueStrategy:N})),children:[l.jsx(p.SelectTrigger,{size:"xs",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:p.INITIAL_VALUE_STRATEGY_OPTIONS.map(N=>l.jsx(p.SelectItem,{value:N.value,children:N.label},N.value))})]})]})}),l.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx(Tn,{checked:e.showLabel??!0,onCheckedChange:N=>g(S=>({...S,showLabel:N===!0}))}),"Show label in toolbar"]}),h?l.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[l.jsx(Tn,{checked:e.hidden===!0,onCheckedChange:N=>g(S=>({...S,hidden:N===!0}))}),"Hide control UI from viewers"]}):null]})}function Bme({open:e,onOpenChange:t,trigger:n,title:r,subtitle:o,description:s,body:i,footer:a,onClose:c,useDialog:u=!1,deleteDialogOpen:d,onDeleteDialogOpenChange:f,deleteDescription:h,deleteDetails:m,onConfirmDelete:g}){const b=dc("interactive"),x=l.jsx(Cgt,{title:r,subtitle:o,onClose:c,titleAsDialogTitle:u});return l.jsxs(l.Fragment,{children:[u?l.jsxs(Mo,{open:e,onOpenChange:t,children:[l.jsx(uQ,{asChild:!0,children:n}),l.jsxs(go,{showCloseButton:!1,className:"flex max-h-[88vh] flex-col overflow-hidden rounded-control border border-border/60 p-0 shadow-sm sm:max-w-[600px] sm:rounded-control",style:b.controlStyle,onInteractOutside:y=>y.preventDefault(),children:[l.jsx(Ro,{className:"sr-only",children:s}),x,l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i}),l.jsx("div",{className:"shrink-0 border-t border-border/60 px-4 py-2.5",children:a})]})]}):l.jsxs(p.Popover,{open:e,onOpenChange:t,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:n}),l.jsxs(p.PopoverContent,{align:"start",className:"m-2 flex h-[440px] max-h-[85vh] w-[480px] max-w-[95vw] flex-col overflow-hidden rounded-control border border-border/60 p-0 shadow-sm",style:b.controlStyle,onMouseDown:y=>y.stopPropagation(),children:[x,l.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i}),l.jsx("div",{className:"shrink-0 border-t border-border/60 px-4 py-2.5",children:a})]})]}),f&&g?l.jsx(Vme,{open:d,onOpenChange:f,description:h,details:m,onConfirm:g}):null]})}function Vme({open:e,defaultOpen:t,onOpenChange:n,description:r,details:o,onConfirm:s}){const i=dc("interactive");return l.jsx(ff,{open:e,defaultOpen:t,onOpenChange:n,children:l.jsxs(ku,{style:i.controlStyle,children:[l.jsxs(_u,{children:[l.jsx(Tu,{children:"Delete control?"}),l.jsx(Eu,{children:r}),o]}),l.jsxs(Iu,{children:[l.jsx(Mu,{children:"Cancel"}),l.jsx(Du,{onClick:s,children:"Delete control"})]})]})})}function Cgt({title:e,subtitle:t,onClose:n,titleAsDialogTitle:r}){const o="truncate text-[13px] font-medium text-foreground",s=r?l.jsx(bo,{className:o,title:e,children:e}):l.jsx("span",{className:o,title:e,children:e});return l.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[l.jsx(p.SlidersHorizontal,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),s,l.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:t})]}),l.jsx("button",{type:"button",onClick:n,"aria-label":"Close",className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(je.X,{className:"h-3.5 w-3.5"})})]})}function Sgt({control:e,onClose:t}){const n=p.useDashboardStore(d=>d.dashboard),{setDashboardControlsModel:r}=p.useDashboardActions(),o=v.useMemo(()=>pgt({dashboard:n,controlId:e.id}),[n,e.id]),s=()=>{const d=(n.controls||[]).filter(h=>h.id!==e.id),f={...n.defaultControlValues||{}};delete f[e.id],r(d,f,{removedControlId:e.id}),t()},i=o.totalCards===0?`Delete "${e.label}"?`:`This control is used by ${o.totalCards} ${o.totalCards===1?"card":"cards"}. Deleting it will remove bindings and replace SQL references with NULL on affected cards.`,a=o.cardTitles.slice(0,3).join(", "),c=o.cardTitles.length>3,u=o.totalCards>0?l.jsxs("div",{className:"space-y-1 text-sm text-muted-foreground",children:[l.jsxs("p",{children:["Affected cards: ",a,c?` +${o.cardTitles.length-3} more`:""]}),o.sqlCards>0?l.jsxs("p",{children:["SQL references on ",o.sqlCards," ",o.sqlCards===1?"card":"cards"," will be replaced with `NULL`."]}):null,o.configCards>0?l.jsxs("p",{children:["Config bindings on ",o.configCards," ",o.configCards===1?"card":"cards"," will be removed."]}):null]}):void 0;return l.jsx(Vme,{defaultOpen:!0,onOpenChange:d=>!d&&t(),description:i,details:u,onConfirm:s})}function Hme({onOpen:e}){return l.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Control settings",onClick:t=>{t.stopPropagation(),e==null||e()},children:l.jsx(Fm,{className:"h-3 w-3"})})}function Ngt({control:e}){const[t,n]=v.useState("closed");return t==="closed"?l.jsx(Hme,{onOpen:()=>n("settings")}):t==="delete"?l.jsx(Sgt,{control:e,onClose:()=>n("closed")}):l.jsx(jgt,{control:e,onClose:()=>n("closed"),onDelete:()=>n("delete")})}function jgt({control:e,onClose:t,onDelete:n}){const r=p.useDashboardStore(M=>M.dashboard),{setDashboardControlsModel:o}=p.useDashboardActions(),s=p.getPlacementOptionsForScope("dashboard"),i=p.getDefaultPlacement("dashboard"),{participants:a}=$me(p.getDashboardCards(r)),c=Lme(r),u=v.useMemo(()=>c[e.id]||[],[c,e.id]),d=p.isStructuralSelectorControlType(e.type)?p.getEligibleParticipantsForStructuralControl(a,e.type):[],f=p.resolveAuthoringControlDefaultValue({control:e,defaultValues:r.defaultControlValues||{}}),h=v.useCallback(M=>({...M,source:M.source.kind==="manual"?{kind:"manual",options:M.source.options.map(B=>({...B,presentation:B.presentation?{...B.presentation}:void 0}))}:{...M.source}}),[]),m=v.useCallback(()=>({control:h(e),selectedCardIds:[...u],defaultValue:f}),[h,e,f,u]),[g,b]=v.useState(m),x=v.useRef(f),y=g.control,w=g.selectedCardIds,C=p.isStructuralSelectorControlType(y.type)?p.getCompatibleStructuralChoiceCatalog({controlType:y.type,participants:a,selectedCardIds:w}):{choices:[],fieldTargetMap:{},metricTargetMap:{}},N=y.type==="field_selector"?C.choices.map(M=>({option:M,target:C.fieldTargetMap[M.value]})):Array.from(new Map(a.flatMap(M=>M.fieldChoices.map(B=>{var W;return[B.value,{option:B,target:(W=M.fieldTargetMap)==null?void 0:W[B.value]}]}))).values()),S=y.type==="metric_selector"?C.choices.map(M=>({option:M,target:C.metricTargetMap[M.value]})):Array.from(new Map(a.flatMap(M=>M.metricChoices.map(B=>{var W;return[B.value,{option:B,target:(W=M.metricTargetMap)==null?void 0:W[B.value]}]}))).values()),j=v.useMemo(()=>(r.controls||[]).map(M=>M.id===e.id?y:M),[e.id,r.controls,y]),_=v.useMemo(()=>p.buildAuthoringPreviewControlValues({controls:j,defaultValues:r.defaultControlValues||{},overrides:[{controlId:e.id,value:void 0},{controlId:y.id,value:g.defaultValue}]}),[e.id,r.defaultControlValues,g.defaultValue,y.id,j]),k=M=>{b(B=>{const W=M(B.control);B.control.source.kind==="manual"&&W.source.kind==="sql_query"&&(x.current=B.defaultValue);const P=B.defaultValue===void 0&&B.control.source.kind==="sql_query"&&W.source.kind==="manual"?x.current:B.defaultValue,G=p.getNextEditedControlDefaultValue({previousControl:B.control,nextControl:W,currentDefaultValue:P});return W.source.kind==="manual"&&(x.current=G),{...B,control:W,defaultValue:G}})},T=M=>{if(!p.isStructuralSelectorControlType(y.type))return;const B=p.getCompatibleStructuralChoiceCatalog({controlType:y.type,participants:a,selectedCardIds:M}),W=p.reconcileStructuralControlChoices({control:y,choices:B.choices});b(P=>({...P,selectedCardIds:M,control:W,defaultValue:p.getNextEditedControlDefaultValue({previousControl:P.control,nextControl:W,currentDefaultValue:P.defaultValue})}))},I=M=>{if(!M.trim())return;const B=Lv(M);B!==e.id&&tue(r,{source:"dashboardControl",controlId:e.id}).includes(B)||b(W=>W.control.id===B?W:{...W,control:{...W.control,id:B}})},E=()=>{x.current=f,b(m()),t()},D=()=>{const M={...r.defaultControlValues||{}};delete M[e.id];let B=g.control,W;if(p.isStructuralSelectorControlType(B.type)){const Z=p.getCompatibleStructuralChoiceCatalog({controlType:B.type,participants:a,selectedCardIds:g.selectedCardIds});B=p.reconcileStructuralControlChoices({control:B,choices:Z.choices}),W=Object.fromEntries(u.filter(X=>!g.selectedCardIds.includes(X)).map(X=>[X,void 0])),g.selectedCardIds.length>0&&B.source.kind==="manual"&&B.source.options.length>0&&Object.assign(W,p.buildStructuralControlBindingsForParticipants({control:B,participants:a,selectedCardIds:g.selectedCardIds}))}!p.isStructuralSelectorControlType(B.type)&&p.isStructuralSelectorControlType(e.type)&&(W=Object.fromEntries(u.map(Z=>[Z,void 0]))),B.initialValueStrategy==="saved_default"&&g.defaultValue!==void 0&&(M[B.id]=g.defaultValue),B={...B,defaultValue:M[B.id]},B=p.syncSqlQueryControlExecutionRequirement(B,M[B.id]);const P=(r.controls||[]).map(Z=>Z.id===e.id?B:Z),G={renamed:B.id!==e.id?{oldId:e.id,newId:B.id}:void 0,cardBindingsById:W,affectedBindingControlIds:p.isStructuralSelectorControlType(B.type)?[B.id]:p.isStructuralSelectorControlType(e.type)?[e.id]:void 0};o(P,M,G),t()},R=p.isStructuralSelectorControlType(e.type),A=M=>{M||E()},F=l.jsx(Hme,{}),z=l.jsx(zme,{control:y,defaultValue:g.defaultValue,defaultPlacement:i,placementOptions:s,previewControlDefinitions:j,previewControlValues:_,availableFieldChoices:N,availableMetricChoices:S,allowCardDefault:!0,structuralParticipantSelector:p.isStructuralSelectorControlType(y.type)?l.jsx(Dme,{type:y.type,participants:d.map(M=>({cardId:M.cardId,title:M.title,choiceCount:y.type==="field_selector"?M.fieldChoices.length:M.metricChoices.length})),selectedCardIds:w,onChange:T}):null,onChangeControl:k,onChangeDefaultValue:M=>{y.source.kind==="manual"&&(x.current=M),b(B=>({...B,defaultValue:M}))},onCommitControlId:I}),L=l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsxs(p.Button,{type:"button",variant:"ghost",size:"xs",className:"text-destructive hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive",onClick:n,children:[l.jsx(je.X,{className:"h-3.5 w-3.5"}),"Delete"]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:E,children:"Cancel"}),l.jsx(p.Button,{type:"button",size:"xs",onClick:D,children:"Accept"})]})]}),$=y.label||"Control",H=p.getFriendlyTypeOption(y.type).label;return l.jsx(Bme,{open:!0,onOpenChange:A,trigger:F,title:$,subtitle:H,description:"Update how this control appears and behaves in the dashboard toolbar.",body:z,footer:L,onClose:E,useDialog:R})}function kgt(e,t){return e.length===t.length&&e.every((n,r)=>{var o,s;return n.value===((o=t[r])==null?void 0:o.value)&&n.label===((s=t[r])==null?void 0:s.label)})}function _gt(e){if(!(e.source.kind!=="sql_query"||e.type!=="enum"&&e.type!=="multi_enum"))return e.source}function Igt(e){return e.source.kind==="manual"?e.source.options:[]}function Tgt({control:e,value:t,popoverOpen:n,controlDefinitionsOverride:r,controlValuesOverride:o,activeFiltersOverride:s}){const i=_gt(e),a=v.useMemo(()=>{const C=oz(i);return C===null?null:`${e.id}:${e.type}:${C}`},[e.id,e.type,i]),c=i!==void 0&&(n||rz(t)),u=qw({controlId:e.id,source:i,enabled:c,controlDefinitionsOverride:r,controlValuesOverride:o,activeFiltersOverride:s}),[d,f]=v.useState(()=>({key:a,labels:new Map,options:[]})),h=u.options,m=c&&!u.isLoading&&!u.isFetching&&!u.isError,g=h.length>0||m;if(v.useEffect(()=>{if(!i){f(C=>C.key===null&&C.options.length===0?C:{key:null,labels:new Map,options:[]});return}f(C=>{const N=C.key===a;if(!g)return N?C:{key:a,labels:new Map,options:[]};const S=N?new Map(C.labels):new Map;let j=!N;for(const _ of h)S.get(_.value)!==_.label&&(S.set(_.value,_.label),j=!0);return N&&!j&&kgt(C.options,h)?C:{key:a,labels:S,options:h}})},[h,g,a,i]),!i)return{options:Igt(e),labelByValue:void 0,isInitialLoading:!1,hasBlockingError:!1};const b=new Map(d.key===a?d.labels:void 0);for(const C of h)b.set(C.value,C.label);const x=[...g?h:d.key===a?d.options:[]],y=new Set(x.map(C=>C.value)),w=C=>{typeof C!="string"||C.length===0||y.has(C)||(y.add(C),x.push({value:C,label:b.get(C)??C}))};if(Array.isArray(t))for(const C of t)w(C);else w(t);return{options:x,labelByValue:b,isInitialLoading:u.isLoading&&x.length===0,hasBlockingError:u.isError&&x.length===0}}const Egt=24,Dgt=/^\d{4}-\d{2}-\d{2}$/;function Bf(e,t=Egt){return e.length<=t?e:`${e.slice(0,t-1)}…`}function Mgt(e,t,n,r){if(t==null||t==="")return null;if(e.type==="date")try{if(typeof t=="string"&&Dgt.test(t)){const[s,i,a]=t.split("-").map(Number);return Kt.format(new Date(s,i-1,a),"MMM d, yyyy")}const o=t instanceof Date?t:new Date(t);return Number.isNaN(o.getTime())?null:Kt.formatInTimeZone(o,n,"MMM d, yyyy")}catch{return null}if(e.type==="multi_enum"&&Array.isArray(t)){if(t.length===0)return null;if(t.length===1){const o=h2(e,t[0],r);return o!==null?Bf(o):e.source.kind==="sql_query"?null:Bf(String(t[0]))}return`${t.length} selected`}if(e.type==="enum"){const o=h2(e,t,r);return o!==null?Bf(o):e.source.kind==="sql_query"?null:Bf(String(t))}if(Aue(e)){const o=h2(e,t,r);return Bf(o===null?String(t):o)}return e.type==="boolean"?t?"On":"Off":Bf(String(t))}function h2(e,t,n){const r=String(t);if(n!=null&&n.has(r))return n.get(r)??null;const o=e.source;if(!o)return null;if(o.kind==="manual"&&Array.isArray(o.options)){const a=o.options.find(c=>c.value===t);return(a==null?void 0:a.label)??null}const i=Rgt(e,t).find(a=>a.value===t);return i?i.label:null}function Rgt(e,t){const n=nz(e);return!(t===xr.CONTROL_CARD_DEFAULT_VALUE||e.defaultValue===xr.CONTROL_CARD_DEFAULT_VALUE)||n.some(o=>o.value===JP.value)?n:[JP,...n]}function Agt(e){return e.type==="date"?mN:p.SlidersHorizontal}function Pgt(e){return e.type==="date"?360:e.type==="multi_enum"?300:e.type==="number"?240:280}function qme({control:e,value:t,isEditing:n=!1,dragListeners:r,onChange:o,onUpdateControl:s,disabled:i=!1,controlDefinitionsOverride:a,controlValuesOverride:c,activeFiltersOverride:u,actions:d}){const f=dc("interactive"),[h,m]=v.useState(!1),g=dl(),b=Tgt({control:e,value:t,popoverOpen:h,controlDefinitionsOverride:a,controlValuesOverride:c,activeFiltersOverride:u}),x=Mgt(e,t,g,b.labelByValue),y=rz(t),w=x!==null,C=e.showLabel??!0,N=i||e.locked===!0,S=Fgt(e,t,N),j=Agt(e);return l.jsxs("div",{className:"group/chip flex shrink-0 items-center gap-2",children:[n&&r&&l.jsx("span",{role:"button",tabIndex:-1,"aria-label":"Drag to reorder",className:"inline-flex h-7 cursor-grab items-center justify-center px-0.5 text-muted-foreground/50 transition-colors hover:text-muted-foreground active:cursor-grabbing",...r,children:l.jsx(Nu,{className:"size-3"})}),l.jsxs(p.Popover,{open:h,onOpenChange:m,children:[l.jsxs("div",{className:p.cn("inline-flex h-7 items-stretch overflow-hidden rounded-control border border-border text-[12px] transition-colors",y?f.hasAppearance?"bg-accent/80 hover:bg-accent":"bg-muted/80 hover:bg-muted":f.hasAppearance?"bg-muted/40 hover:bg-accent/50":"bg-muted/40 hover:bg-muted/70"),style:f.chipStyle,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":w?`${e.label}: ${x}`:e.label,className:"inline-flex items-center gap-1.5 px-2 focus:outline-none",children:[l.jsx(j,{className:p.cn("h-3 w-3 shrink-0",y?"text-muted-foreground":"text-muted-foreground/70")}),C&&l.jsx("span",{className:"whitespace-nowrap text-muted-foreground",children:e.label}),w&&l.jsxs(l.Fragment,{children:[C&&l.jsx("span",{className:"text-border","aria-hidden":"true",children:"·"}),l.jsx("span",{className:"max-w-[160px] truncate whitespace-nowrap font-medium text-foreground",children:x})]}),l.jsx(je.ChevronDown,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"})]})}),y&&S&&l.jsxs(l.Fragment,{children:[l.jsx("span",{"aria-hidden":"true",className:"w-px bg-border"}),l.jsx("button",{type:"button",onClick:_=>{_.preventDefault(),_.stopPropagation(),o(void 0)},"aria-label":`Clear ${e.label}`,className:"inline-flex w-6 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(je.X,{className:"h-3 w-3"})})]})]}),l.jsx(p.PopoverContent,{align:"start",sideOffset:4,style:{width:Pgt(e),...f.contentStyle},className:p.cn(mK(e)||pK(e)?"p-1":"p-3"),onMouseDown:_=>_.stopPropagation(),onClick:_=>_.stopPropagation(),children:mK(e)?l.jsx(gK,{control:e,value:t,disabled:N,multi:!1,options:b.options,isInitialLoading:b.isInitialLoading,hasBlockingError:b.hasBlockingError,onChange:_=>{o(_),m(!1)}}):pK(e)?l.jsx(gK,{control:e,value:t,disabled:N,multi:!0,options:b.options,isInitialLoading:b.isInitialLoading,hasBlockingError:b.hasBlockingError,onChange:_=>{m(!1),o(_)}}):l.jsx(eF,{control:e,value:t,onChange:o,showLabel:!1,disabled:N,controlDefinitionsOverride:a,controlValuesOverride:c,activeFiltersOverride:u})})]}),n&&l.jsx("div",{className:p.cn("flex shrink-0 items-center transition-opacity",h?"opacity-100":"opacity-0 group-hover/chip:opacity-100 focus-within:opacity-100"),children:d!==void 0?d:l.jsx(Ngt,{control:e})})]})}function mK(e){return e.type==="enum"&&(e.source.kind==="manual"||e.source.kind==="sql_query")}function pK(e){return e.type==="multi_enum"&&(e.source.kind==="manual"||e.source.kind==="sql_query")}function gK({control:e,value:t,disabled:n,multi:r,options:o,isInitialLoading:s,hasBlockingError:i,onChange:a}){return s?l.jsx("p",{className:"px-2 py-2 text-[12px] text-muted-foreground",children:"Loading options…"}):i?l.jsx(Qce,{}):r?l.jsx(Lgt,{control:e,options:o,value:t,disabled:n,onChange:a}):l.jsx(Ogt,{control:e,options:o,value:t,disabled:n,onChange:a})}function Fgt(e,t,n){return!n&&!e.requiredAtExecution&&rz(t)}function Ogt({control:e,options:t,value:n,disabled:r,onChange:o}){return t.length===0?l.jsx("p",{className:"px-2 py-2 text-[12px] text-muted-foreground",children:"No options"}):l.jsx("div",{role:"radiogroup",className:"flex flex-col gap-0.5",children:t.map(s=>{const i=n===s.value;return l.jsxs("button",{type:"button",role:"radio","aria-checked":i,disabled:r,onClick:()=>{r||o(s.value)},className:p.cn("flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left text-[13px] transition-colors",r?"cursor-not-allowed opacity-50":i?"bg-muted text-foreground hover:bg-foreground/[0.08]":"text-foreground hover:bg-muted"),children:[l.jsx("span",{"aria-hidden":"true",className:p.cn("inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center text-foreground",i?"opacity-100":"opacity-0"),children:l.jsx(p.Check,{className:"h-3 w-3",strokeWidth:3})}),l.jsx("span",{className:"truncate",children:s.label})]},String(s.value))})})}function Lgt({control:e,options:t,value:n,disabled:r,onChange:o}){const[s,i]=v.useState(""),[a,c]=v.useState(()=>bK(n)),[u,d]=v.useState(!1),f=v.useMemo(()=>bK(n),[n]),h=u?a:f,m=v.useMemo(()=>{const w=s.trim().toLowerCase();return w?t.filter(C=>C.label.toLowerCase().includes(w)||C.value.toLowerCase().includes(w)):t},[t,s]),g=v.useMemo(()=>new Set(h.map(w=>String(w))),[h]),b=()=>{if(r)return;const w=a.length===0&&!e.requiredAtExecution?void 0:a;o(w),d(!1)},x=()=>{r||e.requiredAtExecution||(c([]),d(!0))},y=w=>{if(r)return;const C=String(w),N=g.has(C);N&&h.length===1&&e.requiredAtExecution||(d(!0),c(()=>N?h.filter(S=>String(S)!==C):[...h,w]))};return t.length===0?l.jsx("p",{className:"px-2 py-2 text-[12px] text-muted-foreground",children:"No options"}):l.jsxs("div",{className:"flex min-w-0 flex-col",children:[l.jsxs("div",{className:"mb-2 flex h-7 items-center gap-1.5 rounded-control border border-input bg-background px-2 focus-within:border-ring",children:[l.jsx(Ft.Search,{className:"h-3 w-3 shrink-0 text-muted-foreground","aria-hidden":"true"}),l.jsx("input",{type:"text",value:s,onChange:w=>i(w.target.value),placeholder:`Search ${e.label.toLowerCase()}`,"aria-label":`Search ${e.label.toLowerCase()}`,className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"})]}),l.jsx("div",{role:"listbox","aria-multiselectable":"true",className:"-mx-1 max-h-[260px] overflow-y-auto px-1",children:m.length===0?l.jsx("div",{className:"px-2 py-6 text-center text-[12px] text-muted-foreground",children:s?"No matches":"No options"}):m.map(w=>{const C=g.has(String(w.value)),N=r||C&&h.length===1&&e.requiredAtExecution;return l.jsxs("button",{type:"button",role:"option","aria-selected":C,disabled:N,onClick:()=>y(w.value),className:p.cn("flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left text-[13px] transition-colors",N?"cursor-not-allowed opacity-50":C?"bg-muted text-foreground hover:bg-foreground/[0.08]":"text-foreground hover:bg-muted"),children:[l.jsx("span",{"aria-hidden":"true",className:p.cn("inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] border border-input bg-background text-primary",C&&"border-primary bg-primary text-primary-foreground",N&&"opacity-60"),children:C?l.jsx(p.Check,{className:"h-3 w-3",strokeWidth:3}):null}),l.jsx("span",{className:"truncate",children:w.label})]},String(w.value))})}),l.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 border-t border-border pt-2",children:[l.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[l.jsx("span",{className:"tabular-nums text-foreground",children:h.length})," ","selected"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[!e.requiredAtExecution&&(u||f.length>0)&&l.jsx("button",{type:"button",onClick:x,className:"rounded-control px-2 py-1 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground",children:"Clear"}),l.jsx("button",{type:"button",onClick:b,disabled:r||!u,className:"rounded-control bg-primary px-2 py-1 text-[12px] text-primary-foreground disabled:pointer-events-none disabled:opacity-50",children:"Apply"})]})]})]})}function bK(e){return Array.isArray(e)?e:e==null?[]:[e]}function $gt({control:e,controls:t,reservedVariableNames:n=[],activeFiltersOverride:r,onUpdateControl:o,onRemoveControl:s}){const[i,a]=v.useState(!1),[c,u]=v.useState(!1),d=p.getPlacementOptionsForScope("dashboard"),f=p.getDefaultPlacement("dashboard"),h=v.useMemo(()=>Bgt(t),[t]),m=p.resolveAuthoringControlDefaultValue({control:e,defaultValues:h}),g=v.useCallback(L=>({...L,source:L.source.kind==="manual"?{kind:"manual",options:L.source.options.map($=>({...$,presentation:$.presentation?{...$.presentation}:void 0}))}:{...L.source}}),[]),b=v.useCallback(()=>({control:g(e),defaultValue:m}),[g,e,m]),[x,y]=v.useState(b),w=v.useRef(m),C=x.control,N=v.useMemo(()=>t.map(L=>L.id===e.id?C:L),[e.id,t,C]),S=v.useMemo(()=>p.buildAuthoringPreviewControlValues({controls:N,defaultValues:h,overrides:[{controlId:e.id,value:void 0},{controlId:C.id,value:x.defaultValue}]}),[e.id,h,x.defaultValue,C.id,N]),j=L=>{y($=>{const H=L($.control);$.control.source.kind==="manual"&&H.source.kind==="sql_query"&&(w.current=$.defaultValue);const M=$.defaultValue===void 0&&$.control.source.kind==="sql_query"&&H.source.kind==="manual"?w.current:$.defaultValue,B=p.getNextEditedControlDefaultValue({previousControl:$.control,nextControl:H,currentDefaultValue:M});return H.source.kind==="manual"&&(w.current=B),{...$,control:H,defaultValue:B}})},_=L=>{if(!L.trim())return;const $=Lv(L);$!==e.id&&(n.includes($)||t.some(H=>H.id===$&&H.id!==e.id))||y(H=>H.control.id===$?H:{...H,control:{...H.control,id:$}})},k=()=>{w.current=m,y(b()),a(!1)},T=()=>{if(!o){k();return}const L=C.initialValueStrategy==="saved_default"?x.defaultValue:void 0,$=p.syncSqlQueryControlExecutionRequirement({...C,defaultValue:L});o(zgt($)),a(!1)},I=L=>{if(L){w.current=m,y(b()),a(!0);return}k()},E=()=>{s==null||s(),u(!1),a(!1)},D=C.label||"Control",R=p.getFriendlyTypeOption(C.type).label,A=l.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Control settings",onClick:L=>L.stopPropagation(),children:l.jsx(Fm,{className:"h-3 w-3"})}),F=l.jsx(zme,{control:C,defaultValue:x.defaultValue,defaultPlacement:f,placementOptions:d,previewControlDefinitions:N,previewControlValues:S,allowControlIdEdit:!0,showPlacementSelect:!1,showViewerVisibilityToggle:!1,activeFiltersOverride:r,onChangeControl:j,onChangeDefaultValue:L=>{C.source.kind==="manual"&&(w.current=L),y($=>({...$,defaultValue:L}))},onCommitControlId:_}),z=l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsxs(p.Button,{type:"button",variant:"ghost",size:"xs",className:"text-destructive hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive",onClick:()=>u(!0),children:[l.jsx(je.X,{className:"h-3.5 w-3.5"}),"Delete"]}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:k,children:"Cancel"}),l.jsx(p.Button,{type:"button",size:"xs",onClick:T,children:"Accept"})]})]});return l.jsx(Bme,{open:i,onOpenChange:I,trigger:A,title:D,subtitle:R,description:"Update how this control appears and behaves in the document toolbar.",body:F,footer:z,onClose:k,deleteDialogOpen:c,onDeleteDialogOpenChange:u,deleteDescription:`Delete "${e.label}" from this document sheet?`,onConfirmDelete:E})}function zgt(e){const t={...e};return delete t.placement,delete t.hidden,t}function Bgt(e){const t={};for(const n of e)n.defaultValue!==void 0&&(t[n.id]=n.defaultValue);return t}function Ume({className:e,inputs:t,filterValuesByInputId:n,filterModesByInputId:r,documentFilterValues:o,documentControlValues:s,onSetFilterValue:i,onSetFilterMode:a,onUpdateFilterInput:c,onUpdateControlInput:u,onRemoveFilterValue:d,onRemoveInput:f,controlValuesByInputId:h,onSetControlValue:m,actions:g,isEditing:b=!1}){const x=v.useMemo(()=>t.filter(Ql).map(N=>N.control),[t]),y=p.useDashboardStore(N=>{var S;return((S=N.dashboard.filterLayout)==null?void 0:S.toolbarWrap)??!1}),w=l.jsx("span",{className:"block shrink-0 text-[12px] text-muted-foreground",children:"None yet"}),C=t.map(N=>l.jsx(f2,{children:l.jsx(Vgt,{input:N,filterValuesByInputId:n,filterModesByInputId:r,documentFilterValues:o,documentControlValues:s,documentControlDefinitions:x,onSetFilterValue:i,onSetFilterMode:a,onUpdateFilterInput:c,onUpdateControlInput:u,onRemoveFilterValue:d,onRemoveInput:f,reservedVariableNames:t.filter(S=>S.id!==N.id).map(S=>S.variableName),controlValuesByInputId:h,onSetControlValue:m,isEditing:b})},N.id));return l.jsx("div",{className:p.cn("sticky top-0 z-30 shrink-0 gap-3 border-b bg-background/95 px-3 py-1.5 shadow-[0_1px_0_rgba(0,0,0,0.04)] backdrop-blur supports-[backdrop-filter]:bg-background/90",y?"flex min-h-10 items-start overflow-visible":"grid h-10 grid-cols-[minmax(0,1fr)_auto] items-center overflow-hidden",e),children:y?l.jsxs(MF,{wrap:!0,className:"w-full gap-3 pr-0",children:[C.length>0?C:l.jsx(f2,{children:w}),g?l.jsx(f2,{children:g}):null]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"min-w-0 overflow-x-auto overflow-y-hidden",children:l.jsx(MF,{empty:w,children:C})}),g?l.jsx("div",{className:"shrink-0 justify-self-end",children:g}):null]})})}function Vgt({input:e,filterValuesByInputId:t,filterModesByInputId:n,documentFilterValues:r,documentControlValues:o,documentControlDefinitions:s,onSetFilterValue:i,onSetFilterMode:a,onUpdateFilterInput:c,onUpdateControlInput:u,onRemoveFilterValue:d,onRemoveInput:f,reservedVariableNames:h,controlValuesByInputId:m,onSetControlValue:g,isEditing:b}){if(e.kind==="control"){const _=Object.prototype.hasOwnProperty.call(m,e.id)?m[e.id]:o[e.control.id];return l.jsx(qme,{control:e.control,value:_,isEditing:b,onChange:k=>g(e.id,k),onUpdateControl:k=>u==null?void 0:u(e.id,k),controlDefinitionsOverride:s,controlValuesOverride:o,activeFiltersOverride:r,actions:b?l.jsx($gt,{control:e.control,controls:s,reservedVariableNames:h,activeFiltersOverride:r,onUpdateControl:k=>u==null?void 0:u(e.id,k),onRemoveControl:()=>f==null?void 0:f(e.id)}):null})}const x=e,y=gv(x,t[x.id]),w=y?[y]:[],C=n[x.id]||kme(x.filter.operation),N=vT(x.filter.operation)?{...x.filter,operation:DF(C)}:x.filter,S={filters:[],activeFilterValues:r,selectedSheetId:null,dashboardControls:s,controlValues:o};function j(_,k){const T={...x.filter,..._,operation:x.filter.operation};c==null||c(x.id,T,k)}return l.jsx(P$,{filter:N,isEditing:b,settingsVariant:"document",filterQueryContext:S,inputVariableName:x.variableName,reservedInputVariableNames:h,onUpdateFilter:j,onRemoveFilter:()=>f==null?void 0:f(x.id),storageOptions:{storageTarget:"card",cardId:`document-input-${x.id}`,inlineFilterValues:w,setInlineFilterValue:_=>i(x.id,_),removeInlineFilterValue:()=>d(x.id),setInlineFilterMode:(_,k)=>a(x.id,k),filterQueryContext:S}})}function Hgt({sections:e,inputs:t,selectedSectionId:n,onSelectSection:r,onDeleteSection:o,onReorderSection:s,onInsertSection:i}){const[a,c]=v.useState(null),[u,d]=v.useState(!1);return l.jsxs("aside",{"data-testid":"document-outline",className:"flex w-64 shrink-0 flex-col border-r bg-background",children:[l.jsxs("div",{className:"flex h-10 items-center justify-between border-b px-3",children:[l.jsxs("div",{className:"flex items-baseline gap-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Sections"}),l.jsxs("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground",children:["· ",e.length]})]}),i?l.jsxs(p.Popover,{open:u,onOpenChange:d,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add section",className:"inline-flex h-6 items-center gap-1 rounded-[4px] px-1.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(Tr,{className:"h-3 w-3"}),"Add"]})}),l.jsx(p.PopoverContent,{align:"end",side:"bottom",sideOffset:6,className:"w-48 p-1",children:vme.map(f=>{const h=pv(f);return l.jsxs("button",{type:"button",onClick:()=>{i(f),d(!1)},className:"flex w-full items-center gap-2 rounded-[4px] px-2 py-1.5 text-left text-[12px] text-foreground transition-colors hover:bg-muted",children:[l.jsx(h,{className:"h-3.5 w-3.5 text-muted-foreground"}),sC[f]]},f)})})]}):null]}),l.jsx("div",{className:"flex-1 overflow-y-auto py-1",children:e.length===0?l.jsx("p",{className:"px-3 py-3 text-[12px] text-muted-foreground",children:"No sections yet"}):e.map(f=>{const h=pv(f.type),m=f.id===n,g=kpt(f,t),b=_pt(f);return l.jsxs("div",{"data-testid":`document-outline-section-${f.id}`,"data-selected":m?"true":void 0,draggable:!0,onDragStart:x=>{c(f.id),x.dataTransfer.effectAllowed="move",x.dataTransfer.setData("application/x-semaphor-document-section",f.id)},onDragOver:x=>{!a||a===f.id||(x.preventDefault(),x.dataTransfer.dropEffect="move")},onDrop:x=>{x.preventDefault();const y=x.dataTransfer.getData("application/x-semaphor-document-section")||a;if(y&&y!==f.id){const w=x.currentTarget.getBoundingClientRect(),C=x.clientY<w.top+w.height/2?"before":"after";s(y,f.id,C)}c(null)},onDragEnd:()=>c(null),className:p.cn("group mx-1 flex w-[calc(100%-8px)] items-start rounded transition-colors",m?"bg-muted":"hover:bg-muted/70",a===f.id&&"opacity-40"),children:[l.jsxs("button",{type:"button",onClick:()=>r(f.id),className:"flex min-w-0 flex-1 items-start gap-2 rounded-l px-2 py-2 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[l.jsx(Nu,{className:"mt-0.5 h-3 w-3 shrink-0 cursor-grab text-muted-foreground/50"}),l.jsx(h,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:p.cn("truncate text-[13px] leading-tight",m?"font-medium text-foreground":"text-foreground/90"),children:g}),b?l.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:b}):null]})]}),l.jsx("div",{className:"flex shrink-0 items-center pr-1 pt-2 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 group-data-[selected=true]:opacity-100",children:l.jsx(p.Button,{type:"button",variant:"ghost",size:"icon",className:"h-5 w-5 text-muted-foreground hover:text-destructive","aria-label":`Delete ${g}`,onClick:x=>{x.stopPropagation(),o(f.id)},children:l.jsx(je.X,{className:"h-3 w-3"})})})]},f.id)})})]})}const m2=[];function qgt({card:e,queryOptions:t,surfaceMode:n,previewRowLimit:r,onPreviewRowLimitChange:o}){const{authToken:s,tokenProps:i}=It(),a=p.useDashboardStore(oe=>oe.authToken),u=Mg(e)?n==="print"?"export-full-with-cap":"preview-window":void 0,d=u?u==="preview-window"&&r||IC(u):void 0,f=v.useMemo(()=>{if(u!=="preview-window")return"";const{paginationConfig:oe,...me}=e;return JSON.stringify({card:me,queryOptions:t,surfaceMode:n})},[e,u,t,n]),h=v.useRef(null),m=v.useMemo(()=>u&&d?{...e,paginationConfig:{page:1,pageSize:d}}:e,[e,d,u]),g=v.useMemo(()=>({...t,...u?{documentTableDataPolicy:u}:{}}),[u,t]),b=pu(m,g),x=!!u&&b.isFetching&&(b.isPlaceholderData||b.dataUpdatedAt===0),y=x?void 0:b.data,w=v.useMemo(()=>Array.isArray(y==null?void 0:y.records)?y.records:m2,[y==null?void 0:y.records]),C=h.current,N=u==="preview-window"&&b.isFetching&&!b.error&&!y&&(C==null?void 0:C.identity)===f,S=N?C.records:w,j=N?C.data:y,_=N?C.pagination:x?void 0:b.pagination,k=N?C.comparisonMetadata:x?void 0:b.comparisonMetadata,T=N?C.queryRequestPayload:x?void 0:b.queryRequestPayload,I=N?C.dataUpdatedAt:b.dataUpdatedAt;v.useEffect(()=>{u!=="preview-window"||x||w.length===0||!y||(h.current={identity:f,data:y,pagination:b.pagination,comparisonMetadata:b.comparisonMetadata,queryRequestPayload:b.queryRequestPayload,records:w,dataUpdatedAt:b.dataUpdatedAt})},[b.comparisonMetadata,b.data,b.dataUpdatedAt,b.pagination,b.queryRequestPayload,y,x,u,f,w]);const E=typeof(_==null?void 0:_.totalCount)=="number"?_.totalCount:void 0,D=!u||typeof(_==null?void 0:_.totalCount)=="number",R=u==="export-full-with-cap"&&E!==void 0&&E>mE,A=v.useMemo(()=>JSON.stringify(b.queryKey),[b.queryKey]),F=u&&d&&E!==void 0&&!R&&u==="export-full-with-cap"?Math.max(1,Math.ceil(E/d)):1,z=u&&d&&D&&F>1?Array.from({length:F-1},(oe,me)=>me+2):[],L=T,$=(s==null?void 0:s.accessToken)||(a==null?void 0:a.accessToken)||"",H=ib({queries:z.map(oe=>({queryKey:["documentTableRows",A,I,oe,d,i.apiServiceUrl],enabled:!!(u&&d&&L&&$&&D&&!R),queryFn:async()=>{const me={...L||{},pagination:{page:oe,pageSize:d}};return delete me.tableTotalsRequest,p.postRequest(`${i.apiServiceUrl}/v1/query`,$,me)}}))}),M=H.map(oe=>{var le;const me=Array.isArray((le=oe.data)==null?void 0:le.records)?oe.data.records.length:0;return`${oe.dataUpdatedAt}:${me}`}).join("|"),B=v.useMemo(()=>H.length===0?m2:H.flatMap(oe=>{var me;return Array.isArray((me=oe.data)==null?void 0:me.records)?oe.data.records:m2}),[H.length,M]),W=v.useMemo(()=>u?B.length===0?S:[...S,...B]:S,[B,S,u]),P=H.map(oe=>{var me,le;return oe.error?{error:p.getRequestErrorMessage(oe.error,"Query failed",{preserveSyntheticMessage:!0}),sql:p.getRequestErrorSql(oe.error)||""}:(me=oe.data)!=null&&me.error?{error:p.getRequestErrorMessage(oe.data,"Query failed"),sql:p.getRequestErrorSql(oe.data)||(typeof((le=oe.data)==null?void 0:le.errorSql)=="string"?oe.data.errorSql:"")}:void 0}).find(Boolean),G=x&&!N?"":b.errorMessage,Z=u&&T&&!b.isLoading&&!b.isPending&&!G&&!D?"Document table queries require backend pagination metadata.":"",X=R&&E!==void 0?`This table has ${E.toLocaleString()} rows. Paginated report export currently supports up to ${mE.toLocaleString()} rows. Add filters or reduce the result set before exporting.`:"",Y=G||(P==null?void 0:P.error)||Z||X,O=b.errorSql||(P==null?void 0:P.sql)||"",q=[u??"single-query",I,M,W.length,E??"unknown",Y].join(":"),U=H.some(oe=>oe.isFetching),V=H.some(oe=>oe.isLoading||oe.isPending),K=u==="export-full-with-cap"&&!Y&&F>1&&B.length+S.length<Math.min(E??0,mE),Q=u==="preview-window"&&E!==void 0&&W.length<E,se=v.useCallback(()=>{u!=="preview-window"||!o||!d||o(Math.min(d+IC("preview-window"),E??d+IC("preview-window")))},[o,d,u,E]);return{data:j&&{...j,records:W},records:W,pagination:_,comparisonMetadata:k,queryRequestPayload:T,errorMessage:Y,errorSql:O,isLoading:!N&&b.isLoading||V||K,isPending:!N&&b.isPending||V||K,isFetching:b.isFetching||U,isPreviewWindowIncomplete:Q,loadedRowCount:W.length,totalRowCount:E,rowDataVersion:q,loadMorePreviewRows:Q&&o?se:void 0}}function Ugt(e){return rw(e)}function Wgt(e){var o,s,i,a;if(!Ugt(e)||!y_(e))return[];const t=(s=(o=e.preferences)==null?void 0:o.tablePrefs)==null?void 0:s.columnSettingsMap,n=(a=(i=e.preferences)==null?void 0:i.tablePrefs)==null?void 0:a.columnVisibility;let r=!1;return H5(e).flatMap(c=>aTe(c,n)?c.role!=="metric"&&!r?(r=!0,[j6(c,t)]):c.role==="metric"?[j6(c,t)]:[]:[])}function Wme(e){return lTe(e)}function Kgt(e){return v_(e)}function Ggt(e){return!!(e!=null&&e.columns.some(t=>t.behavior!=="label"))}function Ygt(e){return cTe(e)}const Zgt={mode:"table-print"},Xgt={suppressSortControls:!0,renderPlainWrapper:!0,disableDashboardInteractions:!0};function Qgt(e){return e.interactionConfig?{...e,interactionConfig:void 0}:e}function Jgt(e){return Array.from(e.querySelectorAll("tbody tr, tfoot tr"))}function ebt({sectionElement:e,tableSurfaceElement:t,firstRowElement:n,lastRowElement:r,measurementScale:o}){const s=Number.isFinite(o)&&o>0?o:1,i=e.getBoundingClientRect(),a=t==null?void 0:t.getBoundingClientRect(),c=n.getBoundingClientRect(),u=r.getBoundingClientRect(),d=r.closest("table"),f=d?d.getBoundingClientRect().bottom:u.bottom,h=Math.max(0,(c.top-i.top)/s),m=Math.max(0,(Math.max(f,u.bottom)-u.bottom)/s),g=t?tbt({sectionRect:i,tableSurfaceElement:t,tableSurfaceRect:a,measurementScale:s}):void 0;return{chromeHeightPx:Math.ceil(h+m),trailingChromePx:Math.ceil(m),...g!==void 0?{renderedMinHeightPx:g}:{}}}function tbt({sectionRect:e,tableSurfaceElement:t,tableSurfaceRect:n,measurementScale:r}){const o=window.getComputedStyle(t),s=Number.parseFloat(o.minHeight||"0")||0;if(s<=0||!n)return;const i=Math.max(0,(n.top-e.top)/r);return Math.ceil(i+s)}function xK(e){return e==null?void 0:e.closest('[data-testid="document-page"]')}function Kme(e){return e==null?void 0:e.querySelector('[data-document-region="footer"]')}function nbt(e){const t=Number.parseFloat(e.style.height||"")||Number.parseFloat(e.style.minHeight||"");if(t>0)return t;const n=window.getComputedStyle(e),r=Number.parseFloat(n.height||"")||Number.parseFloat(n.minHeight||"");return r>0?r:e.clientHeight}function rbt(e,t){return e?Math.abs(e.rowHeightPx-t.rowHeightPx)>1||Math.abs((e.averageRowHeightPx??e.rowHeightPx)-(t.averageRowHeightPx??t.rowHeightPx))>1||obt(e.rowHeightsPx,t.rowHeightsPx)||Math.abs(e.chromeHeightPx-t.chromeHeightPx)>1||Math.abs((e.renderedMinHeightPx??0)-(t.renderedMinHeightPx??0))>1||e.rowsPerPage!==t.rowsPerPage:!0}function obt(e,t){return!e&&!t?!1:!e||!t||e.length!==t.length?!0:e.some((n,r)=>{const o=t[r];return n===void 0||o===void 0?n!==o:Math.abs(n-o)>1})}const yK=40,wT=18,sbt=120;function fu({section:e,totalRowCount:t=0,layoutMeasurement:n}){var g;const r=lbt(e),o=r!=="unsupported",s=!!(e.card.connectionId||(g=e.card.dataSource)!=null&&g.connectionId),i=cbt(e,r),a=r==="table"?ubt(e):[],c=a.length>0?1:0,u=Math.max(0,t),d=ibt(e),f=n==null?void 0:n.rowHeightPx,h=n==null?void 0:n.averageRowHeightPx,m=n==null?void 0:n.rowHeightsPx;return{sectionId:e.id,kind:r,isSupported:o,hasConnection:s,hasRunnableQuery:i,isRunnable:o&&s&&i,totalRowCount:u,bodyRowCount:Math.max(0,u-c),trailingRowCount:c,visibleTotalsColumnIds:a,fallbackRowHeightPx:d,measuredRowHeightPx:f,measuredAverageRowHeightPx:h,measuredRowHeightsPx:m,effectiveRowHeightPx:Gme({fallbackRowHeightPx:d,measuredRowHeightPx:f,measuredRowHeightsPx:m,totalRowCount:u}),chromeHeightPx:n==null?void 0:n.chromeHeightPx,renderedMinHeightPx:n==null?void 0:n.renderedMinHeightPx,measuredRowsPerPage:n==null?void 0:n.rowsPerPage,renderContract:Xgt}}function ibt(e){return Math.max(yK,e.table.rowHeightPx??yK)}function Gme({fallbackRowHeightPx:e,measuredRowHeightPx:t,measuredRowHeightsPx:n,totalRowCount:r}){return n&&r!==void 0&&!abt(n,r)?e:t!==void 0?Math.max(wT,t):e}function abt(e,t){if(e.length<t)return!1;for(let n=0;n<t;n+=1)if(e[n]===void 0)return!1;return!0}function lbt(e){return e.card.type==="table"||e.card.type==="pivotTable"?e.card.type:"unsupported"}function cbt(e,t){var n;return t==="unsupported"?!1:t==="pivotTable"?dt.hasValidCardConfig(e.card.config):!!((n=e.card.sql)!=null&&n.trim()||dt.hasValidCardConfig(e.card.config))}function ubt(e){return e.table.totalsRow?Wgt(Wme(e.card)):[]}function CT({totalRowCount:e,fallbackRowHeightPx:t,layoutMeasurement:n}){const r=Math.max(0,e),o=Math.max(wT,t),s=n==null?void 0:n.rowHeightsPx;if(!s||s.length===0){if((n==null?void 0:n.rowHeightPx)!==void 0){const d=dk(n.rowHeightPx)??o;return{kind:"uniform",totalRowCount:r,fallbackRowHeightPx:o,measuredRowHeightPx:d,measuredAverageRowHeightPx:n.averageRowHeightPx}}return{kind:"unmeasured",totalRowCount:r,fallbackRowHeightPx:o}}const i=Array.from({length:r},(d,f)=>dk(s[f])),a=i.filter(d=>d!==void 0);if(a.length===0)return{kind:"unmeasured",totalRowCount:r,fallbackRowHeightPx:o};const c=Math.max(...a),u=n.averageRowHeightPx??Math.ceil(a.reduce((d,f)=>d+f,0)/a.length);return gbt(i)?{kind:"complete",totalRowCount:r,fallbackRowHeightPx:o,measuredRowHeightPx:c,measuredAverageRowHeightPx:u,rowHeightsPx:i}:{kind:"sparse",totalRowCount:r,fallbackRowHeightPx:o,measuredRowHeightPx:c,measuredAverageRowHeightPx:u,rowHeightsPx:i}}function dbt(e,t){const{rowHeightsPx:n,rowRangeStartIndex:r,rowRangeEndIndex:o,totalRowCount:s}=t;if(!n||r===void 0||o===void 0||s===void 0)return g2(e,p2(t));const i=Math.max(0,s),a=Math.min(Math.max(0,r),i),c=Math.min(Math.max(a,o),i),u=c-a,d=p2({...t,rowRangeStartIndex:a,rowRangeEndIndex:c,totalRowCount:i});if(u===i||u!==n.length)return g2(e,d);const f=(e==null?void 0:e.totalRowCount)===i||(e==null?void 0:e.totalRowCount)===void 0,h=Array.from({length:i},(m,g)=>{var b;return f?(b=e==null?void 0:e.rowHeightsPx)==null?void 0:b[g]:void 0});return n.forEach((m,g)=>{h[a+g]=dk(m)}),g2(e,p2({...d,rowHeightsPx:h}))}function Yme(e,t){return e.kind!=="unmeasured"&&e.kind!=="uniform"&&e.rowHeightsPx[t]!==void 0?e.rowHeightsPx[t]:e.kind==="uniform"?e.measuredRowHeightPx:e.fallbackRowHeightPx}function m4({rowMeasurementState:e,startIndex:t,endIndex:n}){let r=0;const o=Math.max(0,t),s=Math.min(Math.max(o,n),e.totalRowCount);for(let i=o;i<s;i+=1)r+=Yme(e,i);return r}function fbt({rowMeasurementState:e,startIndex:t,endIndex:n,chromeHeightPx:r,renderedMinHeightPx:o}){const s=m4({rowMeasurementState:e,startIndex:t,endIndex:n});return Math.max(r+s,Xme(o)??0)}function hbt({rowMeasurementState:e,startIndex:t,endIndex:n,chromeHeightPx:r}){return r+m4({rowMeasurementState:e,startIndex:t,endIndex:n})}function Zme({rowMeasurementState:e,startIndex:t,availableHeightPx:n}){if(!Number.isFinite(n)||n<=0)return 0;let r=0,o=Math.max(0,t);for(;o<e.totalRowCount;){const s=Yme(e,o);if(s<=0||r+s>n)break;r+=s,o+=1}return o-Math.max(0,t)}function mbt(e){return e.kind==="complete"||e.kind==="uniform"?e.measuredRowHeightPx:e.fallbackRowHeightPx}function pbt({tableSlice:e}){return!e||e.pageIndex===0}function p2(e){var s;const t=(s=e.rowHeightsPx)==null?void 0:s.map(i=>dk(i)),n=(t??[]).filter(i=>i!==void 0),r=n.length>0?Math.max(...n):Math.max(wT,e.rowHeightPx),o=n.length>0?Math.ceil(n.reduce((i,a)=>i+a,0)/n.length):e.averageRowHeightPx;return{...e,rowHeightPx:r,averageRowHeightPx:o,rowHeightsPx:t,renderedMinHeightPx:Xme(e.renderedMinHeightPx),canUpdateLayoutChrome:e.canUpdateLayoutChrome}}function g2(e,t){return!e||t.canUpdateLayoutChrome===void 0||t.canUpdateLayoutChrome?t:{...t,chromeHeightPx:e.chromeHeightPx,renderedMinHeightPx:e.renderedMinHeightPx,rowsPerPage:e.rowsPerPage}}function Xme(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.ceil(e)}function dk(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.max(wT,Math.ceil(e))}function gbt(e){return e.every(t=>t!==void 0)}const bbt={colorScheme:"light","--semaphor-background":"0 0% 100%","--semaphor-foreground":"240 5.9% 10%","--semaphor-card":"0 0% 100%","--semaphor-card-foreground":"240 5.9% 10%","--semaphor-muted":"0 0% 98%","--semaphor-muted-foreground":"240 3.8% 46.1%","--semaphor-accent":"240 4.8% 95.9%","--semaphor-accent-foreground":"240 5.9% 10%","--semaphor-border":"240 5.9% 90%","--background":"0 0% 100%","--foreground":"240 5.9% 10%","--muted":"0 0% 98%","--muted-foreground":"240 3.8% 46.1%","--border":"240 5.9% 90%"},xbt=[],ybt={spacious:"[&_tbody_td]:!py-3 [&_tfoot_td]:!py-3 [&_tbody_td>div]:!leading-6",comfortable:"[&_tbody_td]:!py-2 [&_tfoot_td]:!py-2 [&_tbody_td>div]:!leading-5",standard:"[&_tbody_td]:!py-1.5 [&_tfoot_td]:!py-1.5 [&_tbody_td>div]:!leading-5",compact:"[&_tbody_td]:!py-1 [&_tfoot_td]:!py-1 [&_tbody_td>div]:!leading-5",dense:"[&_tbody_td]:!py-1 [&_tfoot_td]:!py-1 [&_tbody_td]:!text-[11px] [&_tfoot_td]:!text-[11px] [&_tbody_td>div]:!leading-4"};function vbt(e){const t=["full","outer"].includes(e.gridLines),n=t||e.gridLines==="top",r=t||e.gridLines==="right",o=t||e.gridLines==="bottom",s=t||e.gridLines==="left",i=["full","inner","horizontal"].includes(e.gridLines),a=["full","inner","vertical"].includes(e.gridLines);return p.cn("relative min-h-[var(--document-table-min-surface-height)] overflow-hidden rounded-none bg-white text-zinc-950",n?"border-t border-t-zinc-200":"border-t-0",r?"border-r border-r-zinc-200":"border-r-0",o?"border-b border-b-zinc-200":"border-b-0",s?"border-l border-l-zinc-200":"border-l-0","[&_.data-table-scroll-container]:!rounded-none [&_.data-table-scroll-container]:!border-0 [&_.data-table-scroll-container]:!bg-white","[&_table]:!bg-white","[&_tbody_td>div]:!text-[var(--document-table-cell-color)] [&_tbody_td]:!text-[var(--document-table-cell-color)]","[&_tbody_tr:hover]:!bg-white [&_tbody_tr]:h-[var(--document-table-row-height)] [&_tbody_tr]:!bg-white","[&_tfoot_td]:!bg-[var(--document-table-totals-bg)] [&_tfoot_td]:!text-[var(--document-table-totals-color)] [&_tfoot_td]:!font-[var(--document-table-totals-font-weight)]","[&_thead]:!bg-[var(--document-table-header-bg)] [&_thead_tr]:!bg-[var(--document-table-header-bg)]","[&_th]:!bg-[var(--document-table-header-bg)] [&_th]:!text-[var(--document-table-header-color)]",ybt[e.density],e.stripedRows&&"[&_tbody_tr:nth-child(even)]:!bg-zinc-50 [&_tbody_tr:nth-child(even):hover]:!bg-zinc-50","[&_table]:!border-0",i?"[&_tbody_tr]:!border-zinc-200 [&_th]:!border-b [&_th]:!border-zinc-200":"[&_tbody_tr]:!border-transparent [&_th]:!border-b-0",e.totalsStyle.borderTop?["[&_tfoot_td]:![border-top-color:var(--document-table-totals-border-color)]","[&_tfoot_td]:!border-[var(--document-table-totals-border-color)]",e.totalsStyle.borderTopStyle==="double"?"[&_tfoot_td]:!border-t-[3px] [&_tfoot_td]:!border-double":"[&_tfoot_td]:!border-t",e.totalsStyle.borderTopStyle==="dashed"&&"[&_tfoot_td]:!border-dashed",e.totalsStyle.borderTopStyle==="dotted"&&"[&_tfoot_td]:!border-dotted",e.totalsStyle.borderTopStyle==="solid"&&"[&_tfoot_td]:!border-solid"]:"[&_tfoot_td]:!border-t-0",a?"[&_td]:!border-r [&_td]:!border-zinc-200 [&_td:last-child]:!border-r-0 [&_th]:!border-r [&_th]:!border-zinc-200 [&_th:last-child]:!border-r-0 [&_tfoot_td]:!border-r [&_tfoot_td]:!border-zinc-200 [&_tfoot_td:last-child]:!border-r-0":"[&_td]:!border-r-0 [&_th]:!border-r-0 [&_tfoot_td]:!border-r-0")}function wbt({section:e,documentFilterValues:t=[],documentControlDefinitions:n=[],documentControlValues:r={},documentDashboardInputValues:o,missingRequiredInputLabels:s=[],isEditing:i=!0,surfaceMode:a="preview",tableSlice:c,initialRowsPerPageLimit:u,previewRowLimit:d,showInlineEditAction:f=!0,onEditTableSection:h,onTableRowCountChange:m,onTableResultColumnsChange:g,onTableLayoutMeasure:b,onTableLayoutInvalidate:x,onUpdateTableSection:y,onPreviewRowLimitChange:w,measurementScale:C=1}){const N=fu({section:e});return N.isRunnable?s.length>0?l.jsx(od,{section:e,icon:l.jsx(Zs,{className:"h-4 w-4 text-amber-500"}),title:"Required inputs missing",message:`Set ${s.join(", ")} to run this table.`,exportState:"blocked",isEditing:i,showInlineEditAction:f,onEditTableSection:h}):l.jsx(HI,{displayPreferences:Zgt,children:l.jsx(Si,{fallbackRender:({error:S})=>l.jsx("div",{...zw(S),children:l.jsx(od,{section:e,icon:l.jsx(Zs,{className:"h-4 w-4 text-amber-500"}),title:"Table unavailable",message:"The table result could not be validated. Refresh or reconfigure the table.",exportState:"error",isEditing:i,showInlineEditAction:f,onEditTableSection:h})}),children:l.jsx(jbt,{section:e,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,documentDashboardInputValues:o,isEditing:i,surfaceMode:a,tableSlice:c,initialRowsPerPageLimit:u,previewRowLimit:d,showInlineEditAction:f,onEditTableSection:h,onTableRowCountChange:m,onTableResultColumnsChange:g,onTableLayoutMeasure:b,onTableLayoutInvalidate:x,onUpdateTableSection:y,onPreviewRowLimitChange:w,measurementScale:C})})}):l.jsx(Dbt,{section:e,isEditing:i,reason:N.isSupported?void 0:"Unsupported table type",showInlineEditAction:f,onEditTableSection:h})}const Qme=v.memo(wbt,Cbt);Qme.displayName="DocumentTableSectionRenderer";function Cbt(e,t){return e.section===t.section&&e.documentFilterValues===t.documentFilterValues&&e.documentControlDefinitions===t.documentControlDefinitions&&e.documentControlValues===t.documentControlValues&&e.documentDashboardInputValues===t.documentDashboardInputValues&&Sbt(e.missingRequiredInputLabels,t.missingRequiredInputLabels)&&e.isEditing===t.isEditing&&e.surfaceMode===t.surfaceMode&&e.initialRowsPerPageLimit===t.initialRowsPerPageLimit&&e.previewRowLimit===t.previewRowLimit&&e.showInlineEditAction===t.showInlineEditAction&&e.measurementScale===t.measurementScale&&Nbt(e.tableSlice,t.tableSlice)&&e.onEditTableSection===t.onEditTableSection&&e.onTableRowCountChange===t.onTableRowCountChange&&e.onTableResultColumnsChange===t.onTableResultColumnsChange&&e.onTableLayoutMeasure===t.onTableLayoutMeasure&&e.onTableLayoutInvalidate===t.onTableLayoutInvalidate&&e.onUpdateTableSection===t.onUpdateTableSection&&e.onPreviewRowLimitChange===t.onPreviewRowLimitChange}function Sbt(e,t){if(e===t)return!0;const n=e||[],r=t||[];return n.length===r.length&&n.every((o,s)=>o===r[s])}function Nbt(e,t){return e===t?!0:!e||!t?!1:e.startIndex===t.startIndex&&e.endIndex===t.endIndex&&e.pageIndex===t.pageIndex&&e.pageCount===t.pageCount&&e.totalRows===t.totalRows&&e.rowsPerPage===t.rowsPerPage}function jbt({section:e,documentFilterValues:t=[],documentControlDefinitions:n=[],documentControlValues:r={},documentDashboardInputValues:o,isEditing:s=!0,surfaceMode:i="preview",tableSlice:a,initialRowsPerPageLimit:c,previewRowLimit:u,showInlineEditAction:d=!0,onEditTableSection:f,onTableRowCountChange:h,onTableResultColumnsChange:m,onTableLayoutMeasure:g,onTableLayoutInvalidate:b,onUpdateTableSection:x,onPreviewRowLimitChange:y,measurementScale:w=1}){var Ce,ce,ie,we,fe,ae,ee;const C=v.useMemo(()=>e.card.type==="table"&&e.table.totalsRow?Wme(e.card):e.card,[e.card,e.table.totalsRow]),N=v.useMemo(()=>Qgt(C),[C]),S=v.useMemo(()=>d4(e),[e]),j=v.useMemo(()=>e.card.type==="table"&&e.table.totalsRow?Kgt(C):void 0,[C,e.card.type,e.table.totalsRow]),_=Ggt(j),k=v.useMemo(()=>{const J=t.length>0,re=n.length>0||Object.keys(r).length>0;return{runtimeContext:"documentSection",documentSectionId:e.id,...j?{tableTotalsRequest:j}:{},...J?{documentFilterValues:t}:{},...re?{documentControlDefinitions:n,documentControlValues:r}:{},...o?{documentDashboardInputValues:o}:{}}},[t,n,r,o,e.id,j]),T=qgt({card:C,queryOptions:k,surfaceMode:i,previewRowLimit:u,onPreviewRowLimitChange:y}),I=T.records||xbt,E=v.useMemo(()=>Mpt(I),[I]),D=v.useMemo(()=>wme(e),[e]),R=C.type==="table"?fu({section:e}).trailingRowCount:0,A=v.useMemo(()=>fu({section:e,totalRowCount:C.type==="table"?I.length+R:0}),[C.type,R,I.length,e]),F=C.type==="table"&&I.length>0&&A.trailingRowCount>0,z=T.errorMessage?0:A.totalRowCount,L=F&&(a?a.endIndex>I.length:!c||A.totalRowCount<=c),$=F&&L,H=v.useMemo(()=>C.type==="table"&&!$?Ygt(N):N,[C.type,N,$]),M=v.useCallback(J=>{x==null||x(e.id,re=>{var Te;const pe=(Te=re.card.preferences)==null?void 0:Te.tablePrefs,Ee=typeof J=="function"?J((pe==null?void 0:pe.columnSizing)||{}):J;return{...re,card:{...re.card,preferences:{...re.card.preferences,tablePrefs:{...pe,columnSizing:Ee}}}}})},[x,e.id]);let B=I;C.type==="table"&&a?B=I.slice(Math.min(a.startIndex,I.length),Math.min(a.endIndex,I.length)):C.type==="table"&&c&&(B=I.slice(0,c));const W=(T.isLoading||T.isPending||T.isFetching)&&I.length===0,P=i!=="print"&&T.isFetching&&I.length>0,G=i==="print"&&T.isLoading&&I.length>0;v.useEffect(()=>{C.type==="table"&&(h==null||h(e.id,z))},[C.type,h,e.id,z]),v.useEffect(()=>{C.type==="table"&&(m==null||m(e.id,E,D))},[C.type,m,D,E,e.id]);const Z=v.useMemo(()=>C.type!=="pivotTable"||T.errorMessage?{kind:"not_loaded"}:Ym({data:T.data,card:C}),[C,T.data,T.errorMessage]),X=Gm(C,Z,T.comparisonMetadata),Y=v.useMemo(()=>{if(C.type!=="pivotTable"||!X)return 0;const J=uL(X.data);return fu({section:e,totalRowCount:J.tableData.length+J.grandTotalRows.length}).totalRowCount},[C.type,X,e]);v.useEffect(()=>{C.type==="pivotTable"&&(h==null||h(e.id,Y))},[C.type,h,X,Y,e.id]);const O=Dpt(e),q=Tpt(S),U=v.useRef(null),V=v.useRef(null),K=v.useRef({rowDataVersion:T.rowDataVersion,errorMessage:T.errorMessage}),[Q,se]=v.useState(!1),[oe,me]=v.useState(0),le=Ibt({tableSlice:a,initialRowsPerPageLimit:c,totalRowCount:C.type==="pivotTable"?Y:z}),ue=a?`${a.pageIndex}:${a.startIndex}:${a.endIndex}:${a.totalRows}`:"unsliced";if(v.useEffect(()=>{const J=K.current;K.current={rowDataVersion:T.rowDataVersion,errorMessage:T.errorMessage},!(J.rowDataVersion===T.rowDataVersion&&J.errorMessage===T.errorMessage)&&(b==null||b(e.id),me(re=>re+1))},[b,T.errorMessage,T.rowDataVersion,e.id]),kbt({sectionId:e.id,sectionRef:U,tableSurfaceRef:V,enabled:!Q,measureKey:`${I.length}:${B.length}:${W?"loading":"ready"}:${q}:${ue}:${oe}`,measurementScale:w,fallbackRowHeightPx:O,fallbackRowCount:Math.max(0,le.endIndex-le.startIndex),rowRangeStartIndex:le.startIndex,rowRangeEndIndex:le.endIndex,totalRowCount:le.totalRowCount,canUpdateLayoutChrome:pbt({tableSlice:a}),onTableLayoutMeasure:g}),T.errorMessage)return l.jsx(od,{section:e,icon:l.jsx(Zs,{className:"h-4 w-4 text-amber-500"}),title:"Table query failed",message:T.errorMessage,exportState:"error",isEditing:s,showInlineEditAction:d,onEditTableSection:f});if(W)return l.jsx(Mbt,{section:e,isEditing:s,showInlineEditAction:d,onEditTableSection:f});if(G)return l.jsx(od,{section:e,icon:l.jsx(p.LoaderCircle,{className:"h-4 w-4 animate-spin text-zinc-400"}),title:"Preparing report table",message:"Rows are being acquired for the final document export.",exportState:"loading",isEditing:s,showInlineEditAction:d,onEditTableSection:f});if($&&_&&!((Ce=T.data)!=null&&Ce.tableTotalsByColumnId)&&T.isFetching)return l.jsx(od,{section:e,icon:l.jsx(p.LoaderCircle,{className:"h-4 w-4 animate-spin text-zinc-400"}),title:"Computing table totals",message:"Grand totals are being computed for this document table.",exportState:"loading",isEditing:s,showInlineEditAction:d,onEditTableSection:f});if($&&_&&!((ce=T.data)!=null&&ce.tableTotalsByColumnId))return l.jsx(od,{section:e,icon:l.jsx(Zs,{className:"h-4 w-4 text-amber-500"}),title:"Table totals unavailable",message:"Grand totals could not be computed for this document table.",exportState:"error",isEditing:s,showInlineEditAction:d,onEditTableSection:f});if(I.length===0&&C.type!=="pivotTable")return l.jsx(od,{section:e,icon:l.jsx(p.Table2,{className:"h-4 w-4 text-zinc-300"}),title:e.title||C.title||"Table",message:"No records to display",exportState:"empty",isEditing:s,showInlineEditAction:d,onEditTableSection:f});let ne;if(C.type==="pivotTable"){if(!X)return l.jsx(od,{section:e,icon:l.jsx(Zs,{className:"h-4 w-4 text-amber-500"}),title:"Pivot table configuration unavailable",message:"Edit the table to confirm its rows, columns, and metrics.",exportState:"error",isEditing:s,showInlineEditAction:d,onEditTableSection:f});ne=l.jsx(Wb,{card:N,data:Ebt(X.data,a,c),options:X.options,suppressSortControls:A.renderContract.suppressSortControls,renderPlainWrapper:A.renderContract.renderPlainWrapper})}else ne=l.jsx(Zd,{card:H,data:B,resultColumns:(ie=T.data)==null?void 0:ie.columns,columnKeyMap:(we=T.data)==null?void 0:we.columnKeyMap,formattingFullRows:I,totalsData:$?I:void 0,totalsByColumnId:$?(fe=T.data)==null?void 0:fe.tableTotalsByColumnId:void 0,comparisonMetadata:T.comparisonMetadata,paginationMetadata:T.pagination,isLoading:W,columnSizing:(ee=(ae=H.preferences)==null?void 0:ae.tablePrefs)==null?void 0:ee.columnSizing,onColumnSizingChange:s&&i!=="print"?M:void 0,onColumnResizeStateChange:se,showColumnResizeHandles:s&&i!=="print",suppressSortControls:A.renderContract.suppressSortControls,suppressCellHoverCards:A.renderContract.disableDashboardInteractions});const de=i!=="print"&&T.isPreviewWindowIncomplete&&(!a||a.endIndex>=I.length);return l.jsxs("div",{className:"relative",children:[l.jsxs("div",{ref:U,className:"pt-3",children:[l.jsx(Rbt,{section:e}),l.jsxs("div",{ref:V,"data-document-table-section":"true",className:vbt(S),style:{...bbt,"--document-table-row-height":`${O}px`,"--document-table-min-surface-height":`${a?0:sbt}px`,"--document-table-header-bg":S.headerBackgroundColor,"--document-table-header-color":S.headerTextColor,"--document-table-totals-bg":S.totalsStyle.backgroundColor,"--document-table-totals-color":S.totalsStyle.textColor,"--document-table-totals-border-color":S.totalsStyle.borderTopColor,"--document-table-totals-font-weight":String(Ept(S.totalsStyle.fontWeight)),"--document-table-cell-color":"#18181b"},children:[P?l.jsx(Abt,{}):null,ne]})]}),de?l.jsx(Pbt,{loadedRowCount:T.loadedRowCount,totalRowCount:T.totalRowCount,isFetching:T.isFetching,onLoadMore:T.loadMorePreviewRows}):null]})}function kbt({sectionId:e,sectionRef:t,tableSurfaceRef:n,enabled:r,measureKey:o,measurementScale:s,fallbackRowHeightPx:i,fallbackRowCount:a,rowRangeStartIndex:c,rowRangeEndIndex:u,totalRowCount:d,canUpdateLayoutChrome:f,onTableLayoutMeasure:h}){const m=v.useRef(null);v.useEffect(()=>{if(!r||!h)return;m.current=null;let g=null;const b=()=>{const I=t.current,E=n.current;if(!I||!E)return;const D=Number.isFinite(s)&&s>0?s:1,R=O=>O/D,A=Jgt(E),F=A.length>0?A.map(O=>{const q=R(O.getBoundingClientRect().height);return q>0?q:i}).filter(O=>O>0):Array.from({length:a},()=>i);if(F.length===0)return;const z=F.map(O=>Math.ceil(O)),L=Math.ceil(Math.max(...F)),$=F.reduce((O,q)=>O+q,0),H=Math.ceil($/F.length),M=Math.ceil(R(I.getBoundingClientRect().height)),B=xK(I),W=A[0],P=A[A.length-1],G=W&&P?ebt({sectionElement:I,tableSurfaceElement:E,firstRowElement:W,lastRowElement:P,measurementScale:D}):void 0;let Z;if(B&&W&&P){const O=B.getBoundingClientRect(),q=Tbt(B,D,O),U=W.getBoundingClientRect(),V=R(U.top-O.top),K=(G==null?void 0:G.trailingChromePx)??0,Q=q-V-K;Z=Math.max(1,_bt(F,Q))}const X=(G==null?void 0:G.chromeHeightPx)??Math.max(0,Math.ceil(M-$)),Y={rowHeightPx:L,averageRowHeightPx:H,rowHeightsPx:z,rowRangeStartIndex:c,rowRangeEndIndex:u,totalRowCount:d,chromeHeightPx:X,renderedMinHeightPx:G==null?void 0:G.renderedMinHeightPx,canUpdateLayoutChrome:f,rowsPerPage:Z};rbt(m.current,Y)&&(m.current=Y,h(e,Y))},x=()=>{g!==null&&window.cancelAnimationFrame(g),g=window.requestAnimationFrame(()=>{g=null,b()})};if(x(),typeof ResizeObserver>"u")return()=>{g!==null&&window.cancelAnimationFrame(g)};const y=new ResizeObserver(x),w=typeof MutationObserver>"u"?null:new MutationObserver(x),C=new Set,N=I=>{!I||C.has(I)||(y.observe(I),C.add(I))},S=I=>{!I||!w||w.observe(I,{attributes:!0,characterData:!0,childList:!0,subtree:!0})},j=t.current,_=n.current,k=xK(j),T=Kme(k);return N(j),N(_),N(k),N(T),S(k),()=>{g!==null&&window.cancelAnimationFrame(g),y.disconnect(),w==null||w.disconnect()}},[r,s,o,h,e,t,n,i,a,c,u,d,f])}function _bt(e,t){if(!Number.isFinite(t)||t<=0)return 0;let n=0,r=0;for(const o of e){if(n+o>t)break;n+=o,r+=1}return r}function Ibt({tableSlice:e,initialRowsPerPageLimit:t,totalRowCount:n}){const r=Math.max(0,n),o=Math.min((e==null?void 0:e.startIndex)??0,r),s=Math.min((e==null?void 0:e.endIndex)??t??r,r);return{startIndex:o,endIndex:Math.max(o,s),totalRowCount:r}}function Tbt(e,t,n){const r=Kme(e);if(r)return(r.getBoundingClientRect().top-n.top)/t;const o=window.getComputedStyle(e),s=Number.parseFloat(o.paddingBottom||"0")||0;return nbt(e)-s}function Ebt(e,t,n){var f,h,m,g,b,x;const r=(t==null?void 0:t.startIndex)??0,o=(t==null?void 0:t.endIndex)??(n||void 0);if(o===void 0)return e;const s=((f=e.rowData)==null?void 0:f.length)??((h=e.rowHeaders)==null?void 0:h.length)??0,i=((m=e.grandTotalRows)==null?void 0:m.length)??0,a=Math.min(r,s),c=Math.min(o,s),u=Math.max(0,r-s),d=Math.max(0,Math.min(o-s,i));return{...e,rowData:(g=e.rowData)==null?void 0:g.slice(a,c),rowHeaders:((b=e.rowHeaders)==null?void 0:b.slice(a,c))??[],grandTotalRows:((x=e.grandTotalRows)==null?void 0:x.slice(u,d))??[]}}function Dbt({section:e,isEditing:t,reason:n,showInlineEditAction:r,onEditTableSection:o}){return l.jsx("div",{className:"pt-3",children:l.jsxs("div",{className:"rounded border border-dashed border-zinc-200 px-4 py-8 text-center","data-document-render-error":"true",children:[l.jsx(p.Table2,{className:"mx-auto mb-2 h-5 w-5 text-zinc-300"}),l.jsx("p",{className:"text-[12px] font-medium text-zinc-600",children:e.title||e.card.title||"Table"}),n?l.jsx("p",{className:"mt-1 text-[11px] text-zinc-400",children:n}):null,r?l.jsx(p4,{section:e,isEditing:t,className:"mt-3",onEditTableSection:o}):null]})})}function Mbt({section:e,isEditing:t,showInlineEditAction:n,onEditTableSection:r}){return l.jsx("div",{className:"pt-3","data-document-render-loading":"true",children:l.jsxs("div",{className:"relative h-[220px] overflow-hidden rounded",children:[l.jsx(tz,{columns:5,rows:8}),n?l.jsx("div",{className:"absolute right-2 top-2 z-20",children:l.jsx(p4,{section:e,isEditing:t,onEditTableSection:r})}):null]})})}function od({section:e,icon:t,title:n,message:r,exportState:o,isEditing:s,showInlineEditAction:i,onEditTableSection:a}){const c=o==="blocked"||o==="error",u=o==="loading";return l.jsx("div",{className:"pt-3",children:l.jsx("div",{className:"rounded border border-zinc-200 bg-zinc-50 px-4 py-5","data-document-render-error":c?"true":void 0,"data-document-render-loading":u?"true":void 0,children:l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsx("div",{className:"mt-0.5 shrink-0",children:t}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"text-[12px] font-medium text-zinc-700",children:n}),l.jsx("p",{className:"mt-1 break-words text-[11px] text-zinc-500",children:r})]}),i?l.jsx(p4,{section:e,isEditing:s,onEditTableSection:a}):null]})})})}function Rbt({section:e}){const t=e.title||e.card.title;return t?l.jsx("div",{className:"mb-2 min-w-0",children:t?l.jsx("p",{className:"whitespace-normal break-words text-[12px] font-semibold leading-4 text-zinc-800",children:t}):null}):null}function Abt(){return l.jsxs("div",{role:"status","aria-live":"polite",className:"pointer-events-none absolute right-2 top-2 z-10 inline-flex items-center gap-1.5 rounded-full border border-zinc-200 bg-white/95 px-2 py-1 text-[10px] font-medium text-zinc-500 shadow-sm",children:[l.jsx(p.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Updating..."]})}function Pbt({loadedRowCount:e,totalRowCount:t,isFetching:n,onLoadMore:r}){const o=t===void 0?"unknown":t.toLocaleString();return l.jsxs("div",{className:"absolute left-0 top-full z-20 mt-2 flex max-w-full items-center gap-2 rounded border border-zinc-200 bg-white px-2 py-1 text-[11px] text-zinc-500 shadow-sm print:hidden",children:[l.jsxs("span",{className:"whitespace-nowrap",children:["Previewing ",e.toLocaleString()," of ",o," rows"]}),r?l.jsx(p.Button,{type:"button",variant:"outline",size:"sm",className:"h-6 rounded px-2 text-[11px]",disabled:n,onClick:r,children:n?"Loading...":"Load more pages"}):null]})}function p4({section:e,isEditing:t,className:n,onEditTableSection:r}){return t?l.jsxs(p.Button,{type:"button",variant:"outline",size:"sm",className:n?`h-8 gap-2 ${n}`:"h-8 gap-2",onClick:o=>{o.stopPropagation(),r==null||r(e)},children:[l.jsx(p.Table2,{className:"h-3.5 w-3.5"}),"Edit table"]}):null}const Fbt={a4:{width:595,height:842},letter:{width:612,height:792}},Obt=96/72;function Jme(e){return Lbt(e)}function Lbt(e){return $bt(e,{pointToPixelScale:Obt})}function $bt(e,{pointToPixelScale:t}){const n=Fbt[e.size],r=e.orientation==="landscape"?n.height:n.width,o=e.orientation==="landscape"?n.width:n.height,s=e.margins,i=s.unit==="mm"?72/25.4:72,a=u=>Math.round(u*i*t),c={top:a(s.top),right:a(s.right),bottom:a(s.bottom),left:a(s.left)};return{width:Math.round(r*t),height:Math.round(o*t),padding:`${c.top}px ${c.right}px ${c.bottom}px ${c.left}px`,paddingPx:c}}const zbt=16,ob=78,Bbt=0,Vbt=0,Hbt=72,qbt=40;function Ubt(e,t={}){var m;const n=t.tablePaginationBySectionId??{},r=t.pageMetricsMode??"preview",o=t.document?tpe(t.document):Number.POSITIVE_INFINITY,s=[];let i=[],a=0,c=0,u;const d=(g,b=i,x=a,y=`document-page-${s.length+1}-${x}`,w=u)=>{s.push({id:y,startInsertIndex:x,sections:b,breakAfterSection:g,layoutError:w})},f=g=>{const b=s[s.length-1];return!b||b.breakAfterSection||b.sections.length===0?!1:(b.breakAfterSection=g,!0)};e.forEach((g,b)=>{if(g.type==="page_break"){i.length>0?d(g):f(g)||d(g),i=[],c=0,a=b+1;return}if(g.type==="table"){const w=n[g.id],C=(w==null?void 0:w.rowCount)??0,N=(w==null?void 0:w.rowsPerPage)??0,S=!!t.document,j=S&&N>0?Gbt(g,w,o-c):N;if(N>0&&(C>N||S&&i.length>0&&j>0&&C>j)&&w){!S&&i.length>0&&(d(),i=[],c=0,u=void 0,a=b),S&&i.length>0&&j<=0&&(d(),i=[],c=0,u=void 0,a=b);const k=g4(g,w),T=Wbt({rowCount:C,rowsPerPage:N,footerRowCount:(w==null?void 0:w.footerRowCount)??0,firstRowsPerPage:S&&i.length>0?j:N,rowMeasurementState:k,capFirstRowsPerPage:S&&i.length>0&&w.measuredRowsPerPage!==void 0,firstRowsAvailableHeightPx:S&&i.length>0?J1(w,o-c):J1(w,o),fullRowsAvailableHeightPx:J1(w,o)});T.forEach((I,E)=>{const D=E===T.length-1,R={section:g,sectionIndex:b,tableSlice:{startIndex:I.startIndex,endIndex:I.endIndex,pageIndex:E,pageCount:T.length,totalRows:C,rowsPerPage:N}},A=Ybt(g,w,I.startIndex,I.endIndex);if(S&&E===0&&i.length>0){i.push(R),c+=A,D||(d(),i=[],c=0,u=void 0,a=b+1);return}if(D&&S){i=[R],c=A,u=void 0,a=b;return}d(void 0,[R],b,`document-page-table-${g.id}-${E+1}`,void 0)});return}}const x=t.document?Xbt({section:g,document:t.document,tablePagination:n[g.id],pageMetricsMode:r,textRenderContext:t.textRenderContext}):0;if(Number.isFinite(o)&&x>o){i.length>0&&(d(),i=[],c=0,u=void 0,a=b),d(void 0,[{section:g,sectionIndex:b}],b,`document-page-overflow-${g.id}`,`Section "${g.id}" exceeds the available page body height.`),i=[],c=0,u=void 0,a=b+1;return}i.length>0&&c+x>o&&(d(),i=[],c=0,u=void 0,a=b),i.push({section:g,sectionIndex:b}),c+=x}),(s.length===0||i.length>0||((m=e[e.length-1])==null?void 0:m.type)==="page_break")&&d();const h=s.length;return s.map((g,b)=>({...g,pageNumber:b+1,pageCount:h}))}function Wbt({rowCount:e,rowsPerPage:t,footerRowCount:n=0,firstRowsPerPage:r,rowMeasurementState:o,capFirstRowsPerPage:s=!1,firstRowsAvailableHeightPx:i,fullRowsAvailableHeightPx:a}){const c=[];let u=0,d=Math.max(1,r);const f=Math.max(0,n),h=Math.max(0,e-f);for(;u<e;){const m=c.length===0?i:a,b=(o.kind==="sparse"||o.kind==="complete")&&Number.isFinite(m)?Zme({rowMeasurementState:o,startIndex:u,availableHeightPx:m??0}):void 0,x=b!==void 0?Math.max(1,c.length===0&&s?Math.min(b,d):b):Math.max(1,d);let y;if(f===0||u>=h)y=Math.min(u+x,e);else{const w=h-u;if(w+f<=x&&m4({rowMeasurementState:o,startIndex:u,endIndex:e})<=(m??Number.POSITIVE_INFINITY))y=e;else{let C=Math.min(x,w);C===w&&f>0&&w>1&&(C-=1),y=u+Math.max(1,C)}}c.push({startIndex:u,endIndex:y}),u=y,d=t}return c}function Kbt({document:e,tableRowCountsBySectionId:t,tableLayoutMeasurementsBySectionId:n,shouldPaginateTables:r,pageMetricsMode:o="preview"}){if(!r)return{};const s={};for(const i of e.sections){if(!c0(i))continue;const a=t[i.id]??0;if(a<=0)continue;const c=n==null?void 0:n[i.id],u=fu({section:i,totalRowCount:a,layoutMeasurement:c}),d=CT({totalRowCount:u.totalRowCount,fallbackRowHeightPx:u.fallbackRowHeightPx,layoutMeasurement:c});s[i.id]={rowCount:u.totalRowCount,rowsPerPage:epe(e,u,o),footerRowCount:u.trailingRowCount,fallbackRowHeightPx:u.fallbackRowHeightPx,rowMeasurementState:d,rowHeightPx:u.measuredRowHeightPx,averageRowHeightPx:u.measuredAverageRowHeightPx,rowHeightsPx:u.measuredRowHeightsPx,chromeHeightPx:u.chromeHeightPx,renderedMinHeightPx:u.renderedMinHeightPx,measuredRowsPerPage:u.measuredRowsPerPage}}return s}function c0(e){return e.type!=="table"?!1:fu({section:e}).isRunnable}function epe(e,t,n="preview"){const o=tpe(e)-(t.chromeHeightPx??ob),s=Math.floor(o/t.effectiveRowHeightPx);return Math.max(1,s)}function Gbt(e,t,n){if(!Number.isFinite(n))return(t==null?void 0:t.rowsPerPage)??0;const r=J1(t,n),o=t&&g4(e,t),i=(o&&o.kind!=="unmeasured"?Zme({rowMeasurementState:o,startIndex:0,availableHeightPx:r}):void 0)??Math.max(0,Math.floor(r/fk(e,t)));return(t==null?void 0:t.measuredRowsPerPage)!==void 0?Math.max(0,Math.min(i,t.measuredRowsPerPage)):i}function Ybt(e,t,n,r){return hbt({rowMeasurementState:t?g4(e,t):CT({totalRowCount:r,fallbackRowHeightPx:fk(e,t)}),startIndex:n,endIndex:r,chromeHeightPx:(t==null?void 0:t.chromeHeightPx)??ob})}function J1(e,t){return t-((e==null?void 0:e.chromeHeightPx)??ob)}function fk(e,t){if(t!=null&&t.rowMeasurementState)return mbt(t.rowMeasurementState);const n=(t==null?void 0:t.fallbackRowHeightPx)??fu({section:e}).fallbackRowHeightPx;return Gme({fallbackRowHeightPx:n,measuredRowHeightPx:t==null?void 0:t.rowHeightPx,measuredRowHeightsPx:t==null?void 0:t.rowHeightsPx,totalRowCount:t==null?void 0:t.rowCount})}function g4(e,t){return t.rowMeasurementState?t.rowMeasurementState:CT({totalRowCount:t.rowCount,fallbackRowHeightPx:fk(e,t),layoutMeasurement:t.rowHeightPx!==void 0||t.rowHeightsPx?{rowHeightPx:t.rowHeightPx??fk(e,t),averageRowHeightPx:t.averageRowHeightPx,rowHeightsPx:t.rowHeightsPx,chromeHeightPx:t.chromeHeightPx??ob,renderedMinHeightPx:t.renderedMinHeightPx,rowsPerPage:t.rowsPerPage}:void 0})}function tpe(e,t){const n=npe(e),r=vK(e.header,Hbt),o=vK(e.footer,qbt);return n.height-n.paddingPx.top-n.paddingPx.bottom-r-o-zbt}function Zbt(e,t){const n=npe(e);return n.width-n.paddingPx.left-n.paddingPx.right}function Xbt({section:e,document:t,tablePagination:n,pageMetricsMode:r,textRenderContext:o}){if(e.type==="spacer")return Math.max(8,e.heightPx);if(e.type==="text")return Qbt(e,t,r,o);if(e.type==="table"){const s=fu({section:e,totalRowCount:(n==null?void 0:n.rowCount)??3,layoutMeasurement:n!=null&&n.rowHeightPx?{rowHeightPx:n.rowHeightPx,averageRowHeightPx:n.averageRowHeightPx,rowHeightsPx:n.rowHeightsPx,chromeHeightPx:n.chromeHeightPx??ob,renderedMinHeightPx:n.renderedMinHeightPx,rowsPerPage:n.rowsPerPage}:void 0}),i=(n==null?void 0:n.rowCount)??3;return fbt({rowMeasurementState:(n==null?void 0:n.rowMeasurementState)??CT({totalRowCount:i,fallbackRowHeightPx:s.effectiveRowHeightPx}),startIndex:0,endIndex:i,chromeHeightPx:(n==null?void 0:n.chromeHeightPx)??ob,renderedMinHeightPx:n==null?void 0:n.renderedMinHeightPx})}return 0}function Qbt(e,t,n,r){var c,u;const o=((c=e.style)==null?void 0:c.fontSize)??13,s=Math.ceil(o*((u=e.style)!=null&&u.fontSize?1.45:1.55)),i=Math.max(120,Zbt(t)-Bbt),a=Jbt({content:e.content,bodyWidthPx:i,fontSize:o,textRenderContext:r});return Vbt+a*s}function Jbt({content:e,bodyWidthPx:t,fontSize:n,textRenderContext:r}){const o=n*.54,s=r?pme(e,r):ext(e),i=txt(s,o);return i.length===0?1:i.reduce((a,c)=>a+Math.max(1,Math.ceil(c/t)),0)}function ext(e){return e.map(t=>({type:t.type,value:t.type==="text"?t.value:"0".repeat(120),format:t.format}))}function txt(e,t){const n=[0];for(const r of e){const o=nxt(r);r.value.split(`
|
|
@@ -1337,7 +1337,7 @@ Include in the briefing:
|
|
|
1337
1337
|
`}),l.jsx("div",{"data-document-print-pages":"true",className:"flex justify-center",children:l.jsx(b4,{document:e,inputs:t,textRenderContext:n,documentFilterValues:r,documentControlDefinitions:o,documentControlValues:s,documentDashboardInputValues:i,missingRequiredInputLabels:a,surfaceMode:"print"})})]})}function b4({document:e,inputs:t,textRenderContext:n,documentFilterValues:r=[],documentControlDefinitions:o=[],documentControlValues:s={},documentDashboardInputValues:i,missingRequiredInputLabels:a=[],isEditing:c=!1,selectedSectionId:u,activeAddIndex:d,onSelectSection:f,onToggleAddIndex:h,onInsertSection:m,onEditTableSection:g,onUpdateTableSection:b,onTableResultColumnsChange:x,onReorderSection:y,pageNumber:w,onPageCountChange:C,surfaceMode:N="preview",measurementScale:S=1}){var ue,ne,de,Ce,ce,ie;const[j,_]=v.useState({}),[k,T]=v.useState({}),[I,E]=v.useState({}),[D,R]=v.useState({}),[A,F]=v.useState(null),z=v.useCallback((we,fe)=>{_(ae=>ae[we]===fe?ae:{...ae,[we]:fe})},[]),L=v.useCallback((we,fe)=>{T(ae=>{const ee=ae[we],J=dbt(ee,fe);return ee&&Math.abs(ee.rowHeightPx-J.rowHeightPx)<=1&&Math.abs((ee.averageRowHeightPx??ee.rowHeightPx)-(J.averageRowHeightPx??J.rowHeightPx))<=1&&ixt(ee.rowHeightsPx,J.rowHeightsPx)&&Math.abs(ee.chromeHeightPx-J.chromeHeightPx)<=1&&Math.abs((ee.renderedMinHeightPx??0)-(J.renderedMinHeightPx??0))<=1&&ee.rowsPerPage===J.rowsPerPage?ae:{...ae,[we]:J}})},[]),$=v.useCallback(we=>{T(fe=>{if(!fe[we])return fe;const{[we]:ae,...ee}=fe;return ee})},[]),H=v.useCallback((we,fe)=>{R(ae=>{const ee=Math.max(M5,Math.ceil(fe));return ae[we]===ee?ae:{...ae,[we]:ee}})},[]),M=v.useCallback((we,fe)=>{E(ae=>ae[we]===fe?ae:{...ae,[we]:fe})},[]),B=(ue=e.header)==null?void 0:ue.enabled,W=(ne=e.header)==null?void 0:ne.heightPx,P=(de=e.header)==null?void 0:de.layout,G=(Ce=e.footer)==null?void 0:Ce.enabled,Z=(ce=e.footer)==null?void 0:ce.heightPx,X=(ie=e.footer)==null?void 0:ie.layout,Y=v.useMemo(()=>axt(B,W,P),[B,W,P]),O=v.useMemo(()=>lxt(G,Z,X),[G,Z,X]),q=v.useMemo(()=>({version:e.version,page:e.page,runtime:e.runtime,inputs:e.inputs,defaultInputValues:e.defaultInputValues,header:Y,footer:O,sections:e.sections,theme:e.theme}),[e.defaultInputValues,e.inputs,e.page,e.runtime,e.sections,e.theme,e.version,O,Y]);v.useEffect(()=>{T({})},[q.footer,q.header,q.page,q.sections,N]),v.useEffect(()=>{_(we=>{const fe=new Set(e.sections.filter(c0).map(J=>J.id));let ae=!1;const ee={};for(const[J,re]of Object.entries(we))fe.has(J)?ee[J]=re:ae=!0;return ae?ee:we}),T(we=>{const fe=new Set(e.sections.filter(c0).map(J=>J.id));let ae=!1;const ee={};for(const[J,re]of Object.entries(we))fe.has(J)?ee[J]=re:ae=!0;return ae?ee:we}),R(we=>{const fe=new Set(e.sections.filter(J=>c0(J)&&Mg(J.card)).map(J=>J.id));let ae=!1;const ee={};for(const[J,re]of Object.entries(we))fe.has(J)?ee[J]=re:ae=!0;return ae?ee:we})},[e.sections]);const U=v.useMemo(()=>Kbt({document:q,tableRowCountsBySectionId:j,tableLayoutMeasurementsBySectionId:k,shouldPaginateTables:a.length===0,pageMetricsMode:N}),[q,a.length,N,k,j]),V=v.useMemo(()=>Ubt(q.sections,{document:q,tablePaginationBySectionId:U,pageMetricsMode:N,textRenderContext:n}),[q,N,U,n]);v.useEffect(()=>{C==null||C(V.length)},[V.length,C]),v.useEffect(()=>{if(N!=="print")return;const we=new Set(V.map(fe=>fe.id));E(fe=>{const ae={};let ee=!1;for(const[J,re]of Object.entries(fe))we.has(J)?ae[J]=re:ee=!0;return ee?ae:fe})},[V,N]);const K=V.some(we=>we.layoutError),Q=N==="print"&&Object.values(I).some(Boolean),se=w===void 0?void 0:Math.min(V.length,Math.max(1,w)),oe=N==="print"||se===void 0?V:V[se-1]?[V[se-1]]:[],me=v.useCallback(we=>{F(we)},[]),le=v.useCallback(()=>{F(null)},[]);return l.jsx("div",{"data-testid":"document-page-stack","data-document-page-stack":"true","data-document-render-error":K||Q?"true":void 0,className:"flex flex-col items-center gap-8",children:oe.map(we=>l.jsx(cxt,{page:we,document:e,inputs:t,textRenderContext:n,documentFilterValues:r,documentControlDefinitions:o,documentControlValues:s,documentDashboardInputValues:i,missingRequiredInputLabels:a,isEditing:c,selectedSectionId:u,activeAddIndex:d,onSelectSection:f,onToggleAddIndex:h,onInsertSection:m,onEditTableSection:g,onUpdateTableSection:b,onTableResultColumnsChange:x,onReorderSection:y,draggingSectionId:A,onSectionDragStart:me,onSectionDragEnd:le,onTableRowCountChange:z,onTableLayoutMeasure:L,onTableLayoutInvalidate:$,tablePreviewRowLimitsBySectionId:D,onTablePreviewRowLimitChange:H,onPageOverflowChange:N==="print"?M:void 0,tableLayoutMeasurementsBySectionId:k,surfaceMode:N,measurementScale:S},we.id))})}function ixt(e,t){return!e&&!t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>{const o=t[r];return n===void 0||o===void 0?n===o:Math.abs(n-o)<=1})}function axt(e,t,n){if(!(e===void 0||!n))return{region:"header",enabled:e,heightPx:t,layout:n,blocks:[]}}function lxt(e,t,n){if(!(e===void 0||!n))return{region:"footer",enabled:e,heightPx:t,layout:n,blocks:[]}}function cxt({page:e,document:t,inputs:n,textRenderContext:r,documentFilterValues:o,documentControlDefinitions:s,documentControlValues:i,documentDashboardInputValues:a,missingRequiredInputLabels:c,isEditing:u,selectedSectionId:d,activeAddIndex:f,onSelectSection:h,onToggleAddIndex:m,onInsertSection:g,onEditTableSection:b,onUpdateTableSection:x,onTableResultColumnsChange:y,onReorderSection:w,draggingSectionId:C,onSectionDragStart:N,onSectionDragEnd:S,onTableRowCountChange:j,onTableLayoutMeasure:_,onTableLayoutInvalidate:k,tablePreviewRowLimitsBySectionId:T,onTablePreviewRowLimitChange:I,onPageOverflowChange:E,tableLayoutMeasurementsBySectionId:D,surfaceMode:R,measurementScale:A}){return l.jsxs("div",{"data-document-page-item":"true","data-document-page-number":e.pageNumber,"data-document-page-count":e.pageCount,"data-document-layout-error":e.layoutError?"true":void 0,className:"flex flex-col items-center gap-2",children:[l.jsx(uxt,{page:e,document:t,inputs:n,textRenderContext:r,documentFilterValues:o,documentControlDefinitions:s,documentControlValues:i,documentDashboardInputValues:a,missingRequiredInputLabels:c,isEditing:u,selectedSectionId:d,activeAddIndex:f,onSelectSection:h,onToggleAddIndex:m,onInsertSection:g,onEditTableSection:b,onUpdateTableSection:x,onTableResultColumnsChange:y,onReorderSection:w,draggingSectionId:C,onSectionDragStart:N,onSectionDragEnd:S,onTableRowCountChange:j,onTableLayoutMeasure:_,onTableLayoutInvalidate:k,tablePreviewRowLimitsBySectionId:T,onTablePreviewRowLimitChange:I,onPageOverflowChange:E,tableLayoutMeasurementsBySectionId:D,surfaceMode:R,measurementScale:A}),u&&e.breakAfterSection?l.jsx(mxt,{selected:d===e.breakAfterSection.id,onSelect:()=>h==null?void 0:h(e.breakAfterSection.id)}):null]})}function uxt({page:e,document:t,inputs:n,textRenderContext:r,documentFilterValues:o,documentControlDefinitions:s,documentControlValues:i,documentDashboardInputValues:a,missingRequiredInputLabels:c,isEditing:u,selectedSectionId:d,activeAddIndex:f,onSelectSection:h,onToggleAddIndex:m,onInsertSection:g,onEditTableSection:b,onUpdateTableSection:x,onTableResultColumnsChange:y,onReorderSection:w,draggingSectionId:C,onSectionDragStart:N,onSectionDragEnd:S,onTableRowCountChange:j,onTableLayoutMeasure:_,onTableLayoutInvalidate:k,tablePreviewRowLimitsBySectionId:T,onTablePreviewRowLimitChange:I,onPageOverflowChange:E,tableLayoutMeasurementsBySectionId:D,surfaceMode:R,measurementScale:A}){const F=v.useRef(null),z=Jme(t.page),L={...r,meta:{...r.meta,pageNumber:e.pageNumber,pageCount:e.pageCount}},$=t.sections.length>0,H=e.sections[0];return H!=null&&H.tableSlice&&H.tableSlice.pageIndex>0,v.useEffect(()=>{var q,U;if(!E||R!=="print"){E==null||E(e.id,!1);return}const M=F.current;if(!M)return;let B=null,W=null,P=null;const G=new Set,Z=()=>{B!==null&&(typeof window.cancelAnimationFrame=="function"?window.cancelAnimationFrame(B):window.clearTimeout(B),B=null)},X=()=>{B=null;const V=Math.ceil(M.scrollHeight)>Math.ceil(M.clientHeight)+1,K=Math.ceil(M.scrollWidth)>Math.ceil(M.clientWidth)+1;E(e.id,V||K)},Y=()=>{Z(),B=typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(X):window.setTimeout(X,0)},O=()=>{M.querySelectorAll("img").forEach(V=>{G.has(V)||(G.add(V),V.addEventListener("load",Y),V.addEventListener("error",Y))})};return O(),Y(),typeof ResizeObserver<"u"&&(W=new ResizeObserver(Y),W.observe(M)),typeof MutationObserver<"u"&&(P=new MutationObserver(()=>{O(),Y()}),P.observe(M,{attributes:!0,childList:!0,characterData:!0,subtree:!0})),(U=(q=globalThis.document)==null?void 0:q.fonts)==null||U.ready.then(Y),()=>{Z(),W==null||W.disconnect(),P==null||P.disconnect(),G.forEach(V=>{V.removeEventListener("load",Y),V.removeEventListener("error",Y)})}},[E,e.id,e.sections,R]),l.jsxs("div",{ref:F,"data-testid":"document-page",className:"flex flex-col bg-white text-zinc-950 shadow-[0_1px_4px_rgba(0,0,0,0.08),0_0_0_1px_rgba(0,0,0,0.04)]",style:{boxSizing:"border-box",width:z.width,height:z.height,overflow:R==="print"?"hidden":void 0,padding:z.padding},onClick:M=>{u&&M.target===M.currentTarget&&(h==null||h(null),m==null||m(null))},children:[l.jsx(CK,{region:t.header,textRenderContext:L,isEditing:u}),l.jsx("div",{className:"min-h-0 flex-1 py-2",children:$?l.jsx(l.Fragment,{children:e.sections.length===0?l.jsx(hxt,{isEditing:u}):e.sections.map(({section:M,sectionIndex:B,tableSlice:W})=>l.jsx(dxt,{item:{section:M,sectionIndex:B,tableSlice:W},document:t,inputs:n,textRenderContext:L,documentFilterValues:o,documentControlDefinitions:s,documentControlValues:i,documentDashboardInputValues:a,missingRequiredInputLabels:c,isEditing:u,selectedSectionId:d,activeAddIndex:f,onSelectSection:h,onToggleAddIndex:m,onInsertSection:g,onEditTableSection:b,onUpdateTableSection:x,onTableResultColumnsChange:y,onReorderSection:w,draggingSectionId:C,onSectionDragStart:N,onSectionDragEnd:S,onTableRowCountChange:j,onTableLayoutMeasure:_,onTableLayoutInvalidate:k,tablePreviewRowLimitsBySectionId:T,onTablePreviewRowLimitChange:I,tableLayoutMeasurementsBySectionId:D,surfaceMode:R,measurementScale:A},Sxt({sectionId:M.id,tableSlice:W})))}):u?l.jsx(bxt,{onInsertSection:M=>g==null?void 0:g(M,0)}):null}),l.jsx(CK,{region:t.footer,textRenderContext:L,isEditing:u})]})}function dxt({item:e,document:t,inputs:n,textRenderContext:r,documentFilterValues:o,documentControlDefinitions:s,documentControlValues:i,documentDashboardInputValues:a,missingRequiredInputLabels:c,isEditing:u,selectedSectionId:d,onSelectSection:f,onEditTableSection:h,onUpdateTableSection:m,onTableResultColumnsChange:g,onReorderSection:b,draggingSectionId:x,onSectionDragStart:y,onSectionDragEnd:w,onTableRowCountChange:C,onTableLayoutMeasure:N,onTableLayoutInvalidate:S,tablePreviewRowLimitsBySectionId:j,onTablePreviewRowLimitChange:_,tableLayoutMeasurementsBySectionId:k,surfaceMode:T,measurementScale:I}){const{section:E,sectionIndex:D}=e,R=E.type==="table"?k[E.id]:void 0,A=fxt({document:t,item:e,tableLayoutMeasurement:R,surfaceMode:T});!e.tableSlice||(e.tableSlice.pageIndex,e.tableSlice.pageCount-1);const F=!!(e.tableSlice&&e.tableSlice.pageIndex>0),z=u&&!F,L=u;return l.jsx("div",{children:l.jsx(xxt,{section:E,inputs:n,textRenderContext:r,documentFilterValues:o,documentControlDefinitions:s,documentControlValues:i,documentDashboardInputValues:a,missingRequiredInputLabels:c,isEditing:z,selectionEnabled:L,selected:L&&d===E.id,onSelect:()=>f==null?void 0:f(E.id),onReorderSection:z?b:void 0,draggingSectionId:x,onSectionDragStart:y,onSectionDragEnd:w,onEditTableSection:h,onUpdateTableSection:m,onTableResultColumnsChange:g,surfaceMode:T,tableSlice:e.tableSlice,initialRowsPerPageLimit:A,onTableRowCountChange:C,onTableLayoutMeasure:N,onTableLayoutInvalidate:S,previewRowLimit:E.type==="table"?j[E.id]??M5:void 0,onPreviewRowLimitChange:E.type==="table"?$=>_==null?void 0:_(E.id,$):void 0,measurementScale:I})})}function fxt({document:e,item:t,tableLayoutMeasurement:n,surfaceMode:r}){const{section:o}=t;if(!(o.type!=="table"||t.tableSlice||!c0(o)))return epe(e,fu({section:o,layoutMeasurement:n}),r)}function hxt({isEditing:e}){return l.jsx("div",{className:"flex min-h-[160px] items-center justify-center text-[11px] text-zinc-300",children:e?"Empty page":null})}function mxt({selected:e,onSelect:t}){return l.jsxs("button",{type:"button",className:p.cn("flex w-full items-center gap-2 rounded px-3 py-1.5 text-[10px] uppercase tracking-[0.08em] text-zinc-400 transition-colors",e?"bg-zinc-100 text-zinc-600":"hover:bg-zinc-100"),onClick:n=>{n.stopPropagation(),t()},children:[l.jsx("div",{className:"h-px flex-1 border-t border-dashed border-zinc-300"}),"Page break",l.jsx("div",{className:"h-px flex-1 border-t border-dashed border-zinc-300"})]})}function CK({region:e,textRenderContext:t,isEditing:n=!1}){if(!(e!=null&&e.enabled))return null;if(e.region==="header"){const d=p.getRegionImageBlock(e.blocks,"logo"),f=pxt(d),h=p.getRegionTextBlock(e.blocks,"title"),m=p.getRegionTextBlock(e.blocks,"metadata"),g=vy(h==null?void 0:h.content,t.inputs,n,t),b=vy(m==null?void 0:m.content,t.inputs,n,t),x=kd(g),y=kd(b),w=!!(d!=null&&d.src||x||y),C=gxt(g,b,{showVariableChips:n});return f==="left"?l.jsxs("div",{"data-document-region":"header",className:"flex items-center gap-3 border-b border-zinc-100",style:{minHeight:e.heightPx||72},children:[b2(d),l.jsx("div",{className:"min-w-0 flex-1",children:C}),!w&&n?l.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.12em] text-zinc-300",children:"Header"}):null]}):l.jsxs("div",{"data-document-region":"header",className:"grid grid-cols-[1fr_auto_1fr] items-center gap-3 border-b border-zinc-100",style:{minHeight:e.heightPx||72},children:[l.jsxs("div",{className:"min-w-0",children:[C,!w&&n?l.jsx("span",{className:"text-[11px] font-medium uppercase tracking-[0.12em] text-zinc-300",children:"Header"}):null]}),l.jsx("div",{className:"flex justify-center",children:f==="center"?b2(d):null}),l.jsx("div",{className:"flex justify-end",children:f==="right"?b2(d):null})]})}const r=p.getRegionTextBlock(e.blocks,"note"),o=p.getRegionTextBlock(e.blocks,"pageInfo"),s=vy(r==null?void 0:r.content,t.inputs,n,t),i=vy(o==null?void 0:o.content,t.inputs,n,t),a=kd(s),c=kd(i),u=!!(a||c);return l.jsxs("div",{"data-document-region":"footer",className:"flex items-center justify-between border-t border-zinc-100 text-[10px] text-zinc-400",style:{minHeight:e.heightPx||40},children:[a?l.jsx("span",{children:bv(s,{showVariableChips:n})}):null,c?l.jsx("span",{className:"ml-auto tabular-nums",children:bv(i,{showVariableChips:n})}):null,!u&&n?l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.12em] text-zinc-300",children:"Footer"}):null]})}function pxt(e){return(e==null?void 0:e.area)==="center"||(e==null?void 0:e.area)==="right"?e.area:"left"}function b2(e){return e!=null&&e.src?l.jsx("img",{src:e.src,alt:e.alt||"",className:"max-h-10 shrink-0 object-contain",style:{width:e.widthPx||120}}):null}function gxt(e,t,n={}){const r=kd(e),o=kd(t);return!r&&!o?null:l.jsxs("div",{className:"min-w-0",children:[r?l.jsx("div",{className:"whitespace-normal break-words text-[13px] font-semibold leading-5",children:bv(e,n)}):null,o?l.jsx("div",{className:"whitespace-normal break-words text-[11px] leading-4 text-zinc-500",children:bv(t,n)}):null]})}function bxt({onInsertSection:e}){return l.jsxs("div",{className:"flex min-h-[360px] flex-col items-center justify-center py-16 text-center",children:[l.jsx("div",{className:"mb-4 flex h-10 w-10 items-center justify-center rounded-md border border-zinc-200 bg-zinc-50",children:l.jsx(Qs,{className:"h-5 w-5 text-zinc-400"})}),l.jsx("p",{className:"text-[14px] font-medium text-zinc-900",children:"Add your first section"}),l.jsx("div",{className:"mt-5 flex items-center gap-2",children:vme.filter(t=>t!=="page_break").map(t=>{const n=pv(t);return l.jsxs(p.Button,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded px-3 text-[12px]",onClick:()=>e(t),children:[l.jsx(n,{className:"h-3.5 w-3.5"}),sC[t]]},t)})})]})}function xxt({section:e,inputs:t,textRenderContext:n,documentFilterValues:r,documentControlDefinitions:o,documentControlValues:s,documentDashboardInputValues:i,missingRequiredInputLabels:a,isEditing:c,selectionEnabled:u=!1,selected:d,onSelect:f,onReorderSection:h,draggingSectionId:m,onSectionDragStart:g,onSectionDragEnd:b,onEditTableSection:x,onUpdateTableSection:y,onTableResultColumnsChange:w,surfaceMode:C,tableSlice:N,initialRowsPerPageLimit:S,onTableRowCountChange:j,onTableLayoutMeasure:_,onTableLayoutInvalidate:k,previewRowLimit:T,onPreviewRowLimitChange:I,measurementScale:E}){const D=pv(e.type),[R,A]=v.useState(null);return c?l.jsxs("section",{className:p.cn("mb-0.5 overflow-hidden rounded transition-shadow",d?"ring-1 ring-zinc-300":"hover:ring-1 hover:ring-zinc-200",R==="before"&&"ring-2 ring-primary/60",R==="after"&&"ring-2 ring-primary/60"),onClick:F=>{F.stopPropagation(),f()},children:[l.jsxs("div",{role:"button",tabIndex:0,"aria-label":`Select ${u2(e,t)} section`,draggable:!!h,className:p.cn("flex items-center gap-1.5 border-b px-3 py-1 outline-none focus-visible:ring-2 focus-visible:ring-ring",d?"bg-zinc-50":"bg-white"),onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),f())},onDragStart:F=>{F.dataTransfer.effectAllowed="move",F.dataTransfer.setData(wK,e.id),g==null||g(e.id)},onDragOver:F=>{if(h){if(!m||m===e.id){A(null);return}F.preventDefault(),F.dataTransfer.dropEffect="move",A(NK(F))}},onDragLeave:()=>A(null),onDragEnd:()=>{A(null),b==null||b()},onDrop:F=>{if(!h)return;F.preventDefault();const z=F.dataTransfer.getData(wK)||m,L=NK(F);A(null),b==null||b(),!(!z||z===e.id)&&h(z,e.id,L)},children:[l.jsx(Nu,{className:"h-3.5 w-3.5 cursor-grab text-zinc-300"}),l.jsx(D,{className:"h-3.5 w-3.5 shrink-0 text-zinc-400"}),l.jsx("span",{className:"flex-1 text-[11px] text-zinc-500",children:u2(e,t)}),e.type==="table"?l.jsxs(p.Button,{type:"button",variant:"ghost",size:"sm",className:"h-6 gap-1.5 px-2 text-[11px] text-zinc-600",onClick:F=>{F.stopPropagation(),x==null||x(e)},children:[l.jsx(p.Table2,{className:"h-3.5 w-3.5"}),"Edit table"]}):null]}),l.jsx(SK,{section:e,inputs:t,textRenderContext:n,documentFilterValues:r,documentControlDefinitions:o,documentControlValues:s,documentDashboardInputValues:i,missingRequiredInputLabels:a,isEditing:c,surfaceMode:C,onEditTableSection:x,onUpdateTableSection:y,onTableResultColumnsChange:w,tableSlice:N,initialRowsPerPageLimit:S,showInlineEditAction:!c,onTableRowCountChange:j,onTableLayoutMeasure:_,onTableLayoutInvalidate:k,previewRowLimit:T,onPreviewRowLimitChange:I,measurementScale:E})]}):l.jsx("section",{className:p.cn(u&&"rounded transition-shadow hover:ring-1 hover:ring-zinc-200",d&&"ring-1 ring-zinc-300"),role:u?"button":void 0,tabIndex:u?0:void 0,"aria-label":u?`Select ${u2(e,t)} section`:void 0,onClick:u?F=>{F.stopPropagation(),f()}:void 0,onKeyDown:u?F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),f())}:void 0,children:l.jsx(SK,{section:e,inputs:t,textRenderContext:n,documentFilterValues:r,documentControlDefinitions:o,documentControlValues:s,documentDashboardInputValues:i,missingRequiredInputLabels:a,isEditing:!1,surfaceMode:C,onUpdateTableSection:y,tableSlice:N,initialRowsPerPageLimit:S,onTableRowCountChange:j,onTableResultColumnsChange:w,onTableLayoutMeasure:_,onTableLayoutInvalidate:k,previewRowLimit:T,onPreviewRowLimitChange:I,measurementScale:E})})}function SK({section:e,inputs:t,textRenderContext:n,documentFilterValues:r,documentControlDefinitions:o,documentControlValues:s,documentDashboardInputValues:i,missingRequiredInputLabels:a,isEditing:c=!0,surfaceMode:u="preview",onEditTableSection:d,onUpdateTableSection:f,onTableResultColumnsChange:h,tableSlice:m,initialRowsPerPageLimit:g,showInlineEditAction:b=!0,onTableRowCountChange:x,onTableLayoutMeasure:y,onTableLayoutInvalidate:w,previewRowLimit:C,onPreviewRowLimitChange:N,measurementScale:S}){if(e.type==="text"){const j=vy(e.content,t,c,n),_=kd(j);return l.jsx("div",{className:p.cn("whitespace-pre-wrap text-[13px] leading-5 text-zinc-800",c&&"px-3"),style:yxt(e.style),children:_?bv(j,{showVariableChips:c}):c?"Text":null})}return e.type==="table"?l.jsx(Qme,{section:e,documentFilterValues:r,documentControlDefinitions:o,documentControlValues:s,documentDashboardInputValues:i,missingRequiredInputLabels:a,isEditing:c,surfaceMode:u,onEditTableSection:d,onUpdateTableSection:f,tableSlice:m,initialRowsPerPageLimit:g,showInlineEditAction:b,onTableRowCountChange:x,onTableResultColumnsChange:h,onTableLayoutMeasure:y,onTableLayoutInvalidate:w,previewRowLimit:C,onPreviewRowLimitChange:N,measurementScale:S}):e.type==="spacer"?c?l.jsxs("div",{className:"relative",style:{height:Math.max(8,e.heightPx)},children:[l.jsx("div",{className:"absolute inset-x-0 top-1/2 border-t border-dashed border-zinc-200"}),l.jsxs("span",{className:"absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-white px-1.5 text-[10px] text-zinc-400",children:[e.heightPx,"px"]})]}):l.jsx("div",{style:{height:Math.max(8,e.heightPx)}}):e.type==="page_break"&&c?l.jsxs("div",{className:"flex items-center gap-2 px-3 py-4",children:[l.jsx("div",{className:"h-px flex-1 border-t border-dashed border-zinc-200"}),l.jsx("span",{className:"text-[10px] uppercase tracking-[0.08em] text-zinc-400",children:"Page break"}),l.jsx("div",{className:"h-px flex-1 border-t border-dashed border-zinc-200"})]}):null}function NK(e){const t=e.currentTarget.getBoundingClientRect(),n=t.top+t.height/2;return e.clientY>n?"after":"before"}function yxt(e){if(e)return{...e.fontSize?{fontSize:e.fontSize}:{},...e.fontSize?{lineHeight:1.45}:{},...e.fontWeight?{fontWeight:Cxt(e.fontWeight)}:{},...e.color?{color:e.color}:{},...e.align?{textAlign:e.align}:{}}}function kd(e){return e.map(t=>t.value).join("")}function bv(e,t={}){return!t.showVariableChips&&e.every(n=>!n.format)?kd(e):e.map((n,r)=>l.jsx("span",{className:p.cn(t.showVariableChips&&n.type==="variable"&&"rounded-[2px] bg-emerald-50 px-0.5 font-mono text-[0.92em] font-medium text-emerald-700 ring-1 ring-inset ring-emerald-200/80"),style:wxt(n),children:n.value},r))}function vy(e,t,n,r){return n?vxt(e,t):pme(e,r)}function vxt(e,t){return(e||[]).map(n=>n.type==="text"?{type:"text",value:n.value,...n.format?{format:n.format}:{}}:{type:"variable",value:c4(n.ref,t),...n.format?{format:n.format}:{}})}function wxt(e){if(e.format)return{...e.format.bold?{fontWeight:700}:{},...e.format.italic?{fontStyle:"italic"}:{},...e.format.underline?{textDecoration:"underline"}:{}}}function Cxt(e){switch(e){case"medium":return 500;case"semibold":return 600;default:return e}}function Sxt({sectionId:e,tableSlice:t}){return t?`${e}:${t.startIndex}-${t.endIndex}`:e}const Nxt=rse|ose|sse,jK="document-text-external-sync";function xv({content:e,inputs:t,multiline:n=!1,disabled:r=!1,onChange:o}){const s=v.useRef(e),i=v.useRef(t);v.useMemo(()=>Rxt(e),[e]);const a=v.useMemo(()=>upe(e,t),[e,t]),c=v.useMemo(()=>lpe(e||[],t),[e,t]),u=c.unresolvedTokens.length===0&&Axt(e,t)&&!Pxt(e,c.content);v.useEffect(()=>{r||!u||o(c.content)},[r,o,c.content,u]);const d=v.useMemo(()=>({namespace:"DocumentTextEditor",nodes:[aC],onError(f){throw f},theme:{text:{bold:"font-semibold",italic:"italic",underline:"underline"}},editorState:()=>{rpe(s.current||[],i.current,n)}}),[n]);return l.jsx(Pie,{initialConfig:d,children:l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:p.cn("rounded border border-input bg-background focus-within:border-ring",r&&"bg-muted text-muted-foreground"),children:[r?null:l.jsx(kxt,{inputs:t}),l.jsx(vae,{contentEditable:l.jsx(Kie,{"aria-label":"Document text","aria-multiline":n,className:p.cn("min-h-8 w-full px-2 py-1.5 text-[12px] leading-5 outline-none",n?"min-h-28":"whitespace-nowrap",r&&"cursor-not-allowed")}),placeholder:null,ErrorBoundary:Gie})]}),l.jsx(oae,{}),l.jsx(_xt,{content:e||[],disabled:r,inputs:t,multiline:n,onChange:o,syncSignature:a}),c.unresolvedTokens.length>0?l.jsxs("p",{className:"text-[11px] leading-4 text-destructive",children:["Unresolved variable:"," ",c.unresolvedTokens.map(f=>f).join(", ")]}):null]})})}class aC extends pc{constructor(n,r,o){super(r,o);Ne(this,"__ref");this.__ref=n}static getType(){return"document-variable"}static clone(n){const r=new aC(n.__ref,n.__text,n.__key);return r.__format=n.__format,r.__style=n.__style,r.__detail=n.__detail,r.__mode=n.__mode,r}static importJSON(n){return x4(n.ref,n.text).setFormat(n.format).setStyle(n.style).setDetail(n.detail)}static importDOM(){return{}}getRef(){return this.getLatest().__ref}createDOM(n){const r=document.createElement("span");return r.className=IK(this),r.textContent=this.__text,r}updateDOM(n,r){return n.__text!==this.__text&&(r.textContent=this.__text),r.className=IK(this),!1}exportDOM(){return{element:document.createTextNode(`{{${this.__text}}}`)}}exportJSON(){return{...super.exportJSON(),ref:this.__ref,type:"document-variable",version:1}}isTextEntity(){return!0}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}}function x4(e,t){return new aC(e,t).setMode("token")}function jxt(e){return e instanceof aC}function kxt({inputs:e}){const[t]=Xi(),[n,r]=v.useState({}),o=v.useMemo(()=>fpt(e),[e]),s=v.useCallback(()=>{const c=Nt();if(!ut(c)){r({});return}r({bold:c.hasFormat("bold"),italic:c.hasFormat("italic"),underline:c.hasFormat("underline")})},[]);v.useEffect(()=>Ui(t.registerUpdateListener(({editorState:c})=>{c.read(s)})),[t,s]);const i=c=>{t.dispatchCommand(Bl,c)},a=c=>{t.focus(()=>{t.update(()=>{const u=x4(c.ref,c.label),d=Nt();if(ut(d)){u.setFormat(d.format&Nxt),vI([u,kr(" ")]);return}const f=Cr(),h=f.getLastChild();if(Ue(h))h.append(u,kr(" "));else{const m=Or();m.append(u,kr(" ")),f.append(m)}})})};return l.jsxs("div",{className:"flex h-7 items-center gap-0.5 border-b border-border/60 px-1",children:[l.jsx(x2,{active:!!n.bold,ariaLabel:"Bold",onClick:()=>i("bold"),children:l.jsx(rZ,{className:"h-3 w-3"})}),l.jsx(x2,{active:!!n.italic,ariaLabel:"Italic",onClick:()=>i("italic"),children:l.jsx(NZ,{className:"h-3 w-3"})}),l.jsx(x2,{active:!!n.underline,ariaLabel:"Underline",onClick:()=>i("underline"),children:l.jsx(zve,{className:"h-3 w-3"})}),l.jsx("div",{className:"ml-auto",children:o.length>0?l.jsx(Oxt,{choices:o,onInsert:a}):null})]})}function x2({active:e,ariaLabel:t,children:n,onClick:r}){return l.jsx("button",{type:"button","aria-label":t,title:t,onMouseDown:o=>o.preventDefault(),onClick:r,className:p.cn("inline-flex h-5 w-5 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",e&&"bg-muted text-foreground"),children:n})}function _xt({content:e,disabled:t,inputs:n,multiline:r,onChange:o,syncSignature:s}){const[i]=Xi(),a=v.useRef(s);return v.useEffect(()=>{i.setEditable(!t)},[t,i]),v.useEffect(()=>{a.current!==s&&(i.update(()=>{rpe(e,n,r)},{tag:jK}),a.current=s)},[e,i,n,r,s]),v.useEffect(()=>{if(!r)return i.registerCommand(U0,c=>(c==null||c.preventDefault(),!0),w7)},[i,r]),v.useEffect(()=>{if(!r)return i.registerCommand(xw,c=>{const u=Txt(c);if(!u||!/[\r\n]/.test(u))return!1;c.preventDefault();const d=spe(u),f=Nt();return ut(f)?f.insertText(d):vI([kr(d)]),!0},w7)},[i,r]),l.jsx(hae,{ignoreSelectionChange:!0,onChange:(c,u,d)=>{d.has(jK)||c.read(()=>{const f=Ixt(n,r),h=upe(f,n);a.current=h,o(f)})}})}function rpe(e,t,n){const r=Cr();r.clear();let o=Or();r.append(o);for(const s of n?e:ope(e)){if(s.type==="variable"){const a=x4(s.ref,c4(s.ref,t));_K(a,s.format),o.append(a);continue}s.value.split(`
|
|
1338
1338
|
`).forEach((a,c)=>{if(c>0&&(o=Or(),r.append(o)),a.length===0)return;const u=kr(a);_K(u,s.format),o.append(u)})}}function Ixt(e,t){const n=[],r=[],o=Cr(),s=()=>{r.length!==0&&(n.push(...ape(r,e).content),r.length=0)};o.getChildren().forEach((a,c)=>{c>0&&(s(),n.push({type:"text",value:`
|
|
1339
1339
|
`})),ipe(a,n,e,r,s)}),s();const i=ST(n);return t?i:ope(i)}function ope(e){const t=e.map(n=>n.type==="variable"?n:{...n,value:spe(n.value)});return ST(t)}function spe(e){return e.replace(/[\r\n]+/g," ")}function Txt(e){const t="clipboardData"in e?e.clipboardData:void 0;if(kK(t))return t.getData("text/plain");const n="dataTransfer"in e?e.dataTransfer:void 0;return kK(n)?n.getData("text/plain"):""}function kK(e){return typeof e=="object"&&e!==null&&"getData"in e&&typeof e.getData=="function"}function ipe(e,t,n,r,o){if(jxt(e)){o();const s=TK(e);t.push({type:"variable",ref:e.getRef(),...s?{format:s}:{}});return}if(jt(e)){const s=e.getTextContent();if(!s)return;r.push({value:s,format:TK(e)});return}if(qh(e)){o(),t.push({type:"text",value:`
|
|
1340
|
-
`});return}Ue(e)&&e.getChildren().forEach(s=>ipe(s,t,n,r,o))}function ape(e,t){const n=e.map(i=>i.value).join(""),r=Ext(e),o=dpt(n,t),s=[];for(const i of o.content){if(i.type==="variable"){const a=Mxt(r,i.sourceStart,i.sourceEnd);s.push({type:"variable",ref:i.ref,...a?{format:a}:{}});continue}Dxt(s,n,r,i.sourceStart,i.sourceEnd)}return{content:ST(s),unresolvedTokens:o.unresolvedTokens}}function Ext(e){let t=0;return e.map(n=>{const r=t,o=r+n.value.length;return t=o,{...n,start:r,end:o}})}function Dxt(e,t,n,r,o){for(const s of n){const i=Math.max(r,s.start),a=Math.min(o,s.end);i>=a||e.push({type:"text",value:t.slice(i,a),...s.format?{format:s.format}:{}})}}function Mxt(e,t,n){var o,s,i;const r={};for(const a of e)Math.max(t,a.start)>=Math.min(n,a.end)||(r.bold||(r.bold=(o=a.format)==null?void 0:o.bold),r.italic||(r.italic=(s=a.format)==null?void 0:s.italic),r.underline||(r.underline=(i=a.format)==null?void 0:i.underline));return r.bold||r.italic||r.underline?r:void 0}function _K(e,t){let n=0;t!=null&&t.bold&&(n|=rse),t!=null&&t.italic&&(n|=ose),t!=null&&t.underline&&(n|=sse),e.setFormat(n)}function IK(e){return p.cn("rounded-[2px] bg-emerald-50 px-0.5 font-mono text-[0.92em] font-medium text-emerald-700 ring-1 ring-inset ring-emerald-200/80",e.hasFormat("bold")&&"font-semibold",e.hasFormat("italic")&&"italic",e.hasFormat("underline")&&"underline")}function TK(e){const t={bold:e.hasFormat("bold"),italic:e.hasFormat("italic"),underline:e.hasFormat("underline")};return t.bold||t.italic||t.underline?t:void 0}function lpe(e,t){const n=[],r=[],o=[],s=()=>{if(r.length===0)return;const i=ape(r,t);n.push(...i.content),o.push(...i.unresolvedTokens),r.length=0};for(const i of e){if(i.type==="variable"){s(),n.push(i);continue}r.push({value:i.value,format:i.format})}return s(),{content:ST(n),unresolvedTokens:o}}function ST(e){const t=[];for(const n of e){const r=t[t.length-1];if(n.type==="text"&&(r==null?void 0:r.type)==="text"&&cpe(n.format,r.format)){r.value+=n.value;continue}t.push(n)}return t}function cpe(e,t){return!!(e!=null&&e.bold)==!!(t!=null&&t.bold)&&!!(e!=null&&e.italic)==!!(t!=null&&t.italic)&&!!(e!=null&&e.underline)==!!(t!=null&&t.underline)}function Rxt(e){return JSON.stringify(e||[])}function upe(e,t){return JSON.stringify({content:e||[],variableLabels:(e||[]).filter(n=>n.type==="variable").map(n=>c4(n.ref,t))})}function Axt(e,t){return e!=null&&e.some(n=>n.type==="text")?lpe(e,t).content.some(n=>n.type==="variable"):!1}function Pxt(e,t){const n=e||[],r=t||[];return n.length!==r.length?!1:n.every((o,s)=>{const i=r[s];return o.type!==i.type||!cpe(o.format,i.format)?!1:o.type==="text"&&i.type==="text"?o.value===i.value:o.type==="variable"&&i.type==="variable"?o.ref.source!==i.ref.source?!1:o.ref.source==="documentMeta"&&i.ref.source==="documentMeta"?o.ref.key===i.ref.key:o.ref.source==="input"&&i.ref.source==="input"&&o.ref.inputId===i.ref.inputId&&o.ref.export===i.ref.export:!1})}function Fxt(e){const t=new Map,n={key:"__document__",label:"Document",choices:[]};for(const o of e){if(o.ref.source==="documentMeta"){n.choices.push(o);continue}const s=o.label.split(".")[0];let i=t.get(s);i||(i={key:`input:${s}`,label:s,choices:[]},t.set(s,i)),i.choices.push(o)}const r=Array.from(t.values());return n.choices.length>0?[...r,n]:r}function Oxt({choices:e,onInsert:t}){const[n,r]=v.useState(!1),[o,s]=v.useState(""),i=v.useMemo(()=>Fxt(e),[e]),a=v.useMemo(()=>{const u=o.trim().toLowerCase();return u?i.map(d=>({...d,choices:d.choices.filter(f=>f.label.toLowerCase().includes(u)||f.token.toLowerCase().includes(u))})).filter(d=>d.choices.length>0):i},[i,o]);function c(u){t(u),s(""),r(!1)}return l.jsxs(p.Popover,{open:n,onOpenChange:r,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Insert variable",title:"Insert variable",className:"inline-flex h-5 items-center gap-0.5 rounded-[3px] border border-transparent px-1.5 text-[10px] font-medium text-muted-foreground transition-colors hover:border-border hover:bg-muted hover:text-foreground",children:[l.jsx(Tr,{className:"h-2.5 w-2.5"}),"Variable"]})}),l.jsxs(p.PopoverContent,{align:"end",side:"bottom",sideOffset:6,className:"w-72 p-0",children:[l.jsxs("div",{className:"flex items-center gap-2 border-b border-border/60 px-2.5 py-1.5",children:[l.jsx(Ft.Search,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("input",{type:"text",value:o,onChange:u=>s(u.target.value),placeholder:"Search variables...",autoFocus:!0,className:"h-6 flex-1 bg-transparent text-[12px] outline-none placeholder:text-muted-foreground"})]}),l.jsx("div",{className:"max-h-[280px] overflow-y-auto p-1",children:a.length===0?l.jsxs("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:['No matches for "',o,'".']}):a.map(u=>l.jsxs("div",{className:"space-y-0.5 pb-1",children:[l.jsx("div",{className:"px-2 pb-0.5 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:u.label}),u.choices.map(d=>l.jsx("button",{type:"button",onClick:()=>c(d),className:"flex w-full items-center justify-between gap-2 rounded-[4px] px-2 py-1 text-left transition-colors hover:bg-muted",children:l.jsx("span",{className:"truncate font-mono text-[11px] text-foreground",children:d.label})},d.token))]},u.key))})]})]})}function Oo({label:e,children:t}){return l.jsxs("div",{children:[l.jsx("label",{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),t]})}function dpe({label:e,enabled:t,onToggle:n}){return l.jsxs("label",{className:"flex h-8 cursor-pointer items-center justify-between gap-3 rounded-[5px] border border-border/60 bg-background px-2.5 text-[12px]",children:[l.jsx("span",{className:p.cn(t?"text-foreground":"text-muted-foreground"),children:e}),l.jsx(p.Switch,{size:"sm",checked:t,onCheckedChange:n})]})}function fpe({columns:e,columnVisibility:t,onColumnVisibilityChange:n,onShowAllColumns:r,emptyMessage:o="Run the query or add fields to configure output columns.",helperText:s="Hidden columns stay available for conditional formatting triggers, but are omitted from table output and exports.",className:i}){const a=Object.values(t||{}).filter(c=>c===!1).length;return e.length===0?l.jsx("div",{className:p.cn("space-y-3",i),children:l.jsx("p",{className:"rounded-[6px] border border-dashed border-border/60 px-3 py-4 text-[12px] leading-5 text-muted-foreground",children:o})}):l.jsxs("div",{className:p.cn("space-y-3",i),children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:s}),l.jsx(p.Button,{type:"button",variant:"ghost",size:"xs",className:"h-6 shrink-0 px-2 text-[11px]",disabled:a===0,onClick:r,children:"Show all"})]}),l.jsx("div",{className:"overflow-hidden rounded-[6px] border border-border/60 bg-background",children:l.jsx("div",{className:"max-h-[calc(100vh-260px)] divide-y divide-border/60 overflow-y-auto",children:e.map(c=>{const u=roe(t,c.value);return l.jsxs("label",{className:"flex cursor-pointer items-center justify-between gap-3 px-3 py-2 transition-colors hover:bg-muted/40",children:[l.jsxs("span",{className:"min-w-0",children:[l.jsx("span",{className:"block truncate text-[13px] font-medium text-foreground",children:c.label}),c.label!==c.value?l.jsx("span",{className:"block truncate text-[11px] text-muted-foreground",children:c.value}):null]}),l.jsx(p.Switch,{size:"xs",checked:u,"aria-label":`${u?"Hide":"Show"} ${c.label}`,onCheckedChange:d=>n(c.value,d)})]},c.value)})})})]})}const Lxt=[null,"#fee2e2","#fef3c7","#dcfce7","#dbeafe","#ede9fe","#ffe4e6","#f4f4f5"],$xt=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function hpe(e){return typeof e=="string"&&$xt.test(e)}function zxt(e){const t=e.trim();return t?t.startsWith("#")?t:`#${t}`:""}function Bxt(e,t="#000000"){if(hpe(e)){if(e.length===7)return e;if(e.length===4){const n=e[1],r=e[2],o=e[3];return`#${n}${n}${r}${r}${o}${o}`}if(e.length===9)return e.slice(0,7)}return t}const Vxt=120;function da({value:e,onChange:t,defaultValue:n,allowEmpty:r=!0,presets:o=Lxt,ariaLabel:s,placeholder:i="#000000",id:a,className:c,disabled:u=!1}){const[d,f]=te.useState(!1),[h,m]=te.useState(e??""),[g,b]=te.useState(e),x=te.useRef(null),y=te.useRef(void 0),w=te.useRef(t);te.useEffect(()=>{w.current=t},[t]),te.useEffect(()=>{x.current===null&&(m(e??""),b(e))},[e]),te.useEffect(()=>()=>{x.current!==null&&clearTimeout(x.current)},[]);const C=te.useCallback(()=>{if(x.current===null)return;clearTimeout(x.current),x.current=null;const T=y.current;y.current=void 0,T!==void 0&&w.current(T)},[]),N=te.useCallback(T=>{b(T),m(T),y.current=T,x.current!==null&&clearTimeout(x.current),x.current=setTimeout(()=>{const I=y.current;x.current=null,y.current=void 0,I!==void 0&&w.current(I)},Vxt)},[]),S=te.useCallback(T=>{x.current!==null&&(clearTimeout(x.current),x.current=null,y.current=void 0),b(T),t(T)},[t]),j=g??e,_=n!==void 0&&(j??void 0)!==n,k=T=>{const I=zxt(T);if(!I){if(r){S(void 0);return}m(e??"");return}if(hpe(I)){S(I),m(I);return}m(e??"")};return l.jsxs("div",{className:p.cn("flex h-7 items-center gap-1.5",c),children:[l.jsxs(p.Popover,{open:d,onOpenChange:T=>{T||C(),f(T)},children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsx("button",{type:"button",disabled:u,"aria-label":s?`Pick ${s}`:"Pick a color",className:p.cn("relative size-6 shrink-0 overflow-hidden rounded-[5px] border border-border/60 transition-colors","hover:border-border","focus-visible:border-ring focus-visible:outline-none",u&&"cursor-not-allowed opacity-50"),style:j?{backgroundColor:j}:{backgroundImage:"linear-gradient(to top right, transparent calc(50% - 0.5px), hsl(var(--border)) calc(50% - 0.5px), hsl(var(--border)) calc(50% + 0.5px), transparent calc(50% + 0.5px))"}})}),l.jsxs(p.PopoverContent,{align:"start",sideOffset:6,className:"z-[60] w-[220px] space-y-2.5 rounded-[6px] p-2.5",children:[l.jsx("div",{className:"flex flex-wrap items-center gap-1",children:o.map((T,I)=>{const E=T===null,D=(j??null)===T||T!==null&&(j==null?void 0:j.toLowerCase())===T.toLowerCase(),R=()=>{if(E){r&&S(void 0);return}S(T)};return E&&!r?null:l.jsx("button",{type:"button",onClick:R,"aria-label":E?"No color":T,className:p.cn("relative flex size-6 items-center justify-center rounded-[4px] border transition-colors",D?"border-foreground":"border-border/60 hover:border-border"),style:E?{backgroundImage:"linear-gradient(to top right, transparent calc(50% - 0.5px), hsl(var(--border)) calc(50% - 0.5px), hsl(var(--border)) calc(50% + 0.5px), transparent calc(50% + 0.5px))"}:{backgroundColor:T??void 0},children:D&&!E&&l.jsx(p.Check,{className:"size-3",strokeWidth:3,style:{color:"#fff",mixBlendMode:"difference"}})},`${T??"none"}-${I}`)})}),l.jsx("div",{className:"h-px bg-border/60"}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("input",{type:"color","aria-label":"Custom color",value:Bxt(j),onChange:T=>N(T.target.value),onBlur:C,className:"h-7 w-10 shrink-0 cursor-pointer rounded-[5px] border border-border/60 bg-background p-0.5"}),l.jsx(p.Input,{size:"xs",value:h,onChange:T=>m(T.target.value),onBlur:T=>k(T.target.value),onKeyDown:T=>{T.key==="Enter"?(k(h),f(!1)):T.key==="Escape"&&(m(e??""),f(!1))},placeholder:i,className:p.cn("w-full font-mono text-[11px]",p.removeRing)})]}),l.jsxs("div",{className:"flex items-center justify-between pt-0.5",children:[_?l.jsxs("button",{type:"button",onClick:()=>S(n),className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(p.RotateCcw,{className:"size-3"}),"Reset to default"]}):l.jsx("span",{}),l.jsx("button",{type:"button",onClick:()=>{C(),f(!1)},className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground","aria-label":"Close color picker",children:"Done"})]})]})]}),l.jsx(p.Input,{size:"xs",id:a,"aria-label":s,value:h,onChange:T=>m(T.target.value),onBlur:T=>k(T.target.value),onKeyDown:T=>{T.key==="Enter"?(k(h),T.target.blur()):T.key==="Escape"&&(m(e??""),T.target.blur())},placeholder:i,disabled:u,className:p.cn("w-full font-mono text-[11px]",p.removeRing)}),_&&l.jsx("button",{type:"button",onClick:()=>S(n),"aria-label":"Reset color",className:"inline-flex size-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(p.RotateCcw,{className:"size-3"})})]})}function mpe({style:e,onDensityChange:t,onStyleChange:n,totals:r,showFullStyle:o=!0,showBorderStyle:s=!0,extraSection:i,onReset:a,className:c}){const u=(r==null?void 0:r.enabled)??e.totalsStyle.enabled,d=!!r,f=!!(r!=null&&r.onStyleChange)&&(u||!(r!=null&&r.onEnabledChange)),h=qoe[e.headerStyle],m=b=>{n({headerBackgroundColor:b===h.background?void 0:b})},g=b=>{n({headerTextColor:b===h.color?void 0:b})};return l.jsxs("div",{className:p.cn("space-y-5",c),children:[l.jsxs(JS,{label:"Layout",children:[l.jsx(wl,{label:"Density",children:l.jsxs(p.Select,{value:e.density,onValueChange:b=>t(b),children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table density",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:zoe.map(b=>l.jsx(p.SelectItem,{value:b,children:q4e[b]},b))})]})}),o&&l.jsx(e1,{label:"Wrap text",checked:e.wrapText,onCheckedChange:b=>n({wrapText:b})})]}),o&&l.jsxs(l.Fragment,{children:[l.jsxs(JS,{label:"Header",children:[l.jsx(e1,{label:"Wrap header",checked:e.headerWrapText,onCheckedChange:b=>n({headerWrapText:b})}),l.jsx(wl,{label:"Style",children:l.jsxs(p.Select,{value:e.headerStyle,onValueChange:b=>n({headerStyle:b}),children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table header style",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:Boe.map(b=>l.jsx(p.SelectItem,{value:b,children:U4e[b]},b))})]})}),l.jsx(wl,{label:"Background",children:l.jsx(da,{value:e.headerBackgroundColor,onChange:m,defaultValue:h.background,allowEmpty:!1,ariaLabel:"Header background"})}),l.jsx(wl,{label:"Text",children:l.jsx(da,{value:e.headerTextColor,onChange:g,defaultValue:h.color,allowEmpty:!1,ariaLabel:"Header text"})})]}),l.jsxs(JS,{label:"Rows",children:[s&&l.jsx(wl,{label:"Borders",children:l.jsxs(p.Select,{value:e.gridLines,onValueChange:b=>n({gridLines:b}),children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table borders",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:Voe.map(b=>l.jsx(p.SelectItem,{value:b,children:W4e[b]},b))})]})}),l.jsx(e1,{label:"Row striping",checked:e.stripedRows,onCheckedChange:b=>n({stripedRows:b})})]})]}),o&&d&&l.jsxs(JS,{label:"Totals",action:r!=null&&r.onEnabledChange?l.jsx(p.Switch,{size:"xs","aria-label":"Show totals row",checked:u,onCheckedChange:b=>{var x;return(x=r==null?void 0:r.onEnabledChange)==null?void 0:x.call(r,!!b)}}):null,children:[r!=null&&r.helperText?l.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:r.helperText}):null,f?l.jsxs(l.Fragment,{children:[l.jsx(wl,{label:"Background",children:l.jsx(da,{value:e.totalsStyle.backgroundColor,onChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{backgroundColor:b})},defaultValue:ha.backgroundColor,allowEmpty:!1,ariaLabel:"Totals background"})}),l.jsx(wl,{label:"Text",children:l.jsx(da,{value:e.totalsStyle.textColor,onChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{textColor:b})},defaultValue:ha.textColor,allowEmpty:!1,ariaLabel:"Totals text"})}),l.jsx(wl,{label:"Weight",children:l.jsxs(p.Select,{value:e.totalsStyle.fontWeight,onValueChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{fontWeight:b})},children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table totals weight",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:Hoe.map(b=>l.jsx(p.SelectItem,{value:b,children:K4e[b]},b))})]})}),l.jsx(e1,{label:"Top border",checked:e.totalsStyle.borderTop,onCheckedChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{borderTop:b})}}),e.totalsStyle.borderTop?l.jsxs(l.Fragment,{children:[l.jsx(wl,{label:"Border style",children:l.jsxs(p.Select,{value:e.totalsStyle.borderTopStyle,onValueChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{borderTopStyle:b})},children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table totals border style",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:G4e.map(b=>l.jsx(p.SelectItem,{value:b,children:Y4e[b]},b))})]})}),l.jsx(wl,{label:"Border color",children:l.jsx(da,{value:e.totalsStyle.borderTopColor,onChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{borderTopColor:b})},defaultValue:ha.borderTopColor,allowEmpty:!1,ariaLabel:"Totals border color"})})]}):null]}):null]}),i,a?l.jsx(p.Button,{type:"button",variant:"ghost",size:"xs",className:"w-full",onClick:a,children:"Reset appearance"}):null]})}function JS({label:e,action:t,children:n}){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),t]}),l.jsx("div",{className:"space-y-2",children:n})]})}function wl({label:e,htmlFor:t,children:n}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("label",{htmlFor:t,className:"w-20 shrink-0 text-[12px] text-foreground",children:e}),l.jsx("div",{className:"min-w-0 flex-1",children:n})]})}function e1({label:e,checked:t,onCheckedChange:n}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"w-20 shrink-0 text-[12px] text-foreground",children:e}),l.jsx("div",{className:"min-w-0 flex-1",children:l.jsx(p.Switch,{size:"xs",checked:t,onCheckedChange:r=>n(!!r)})})]})}const la="__semaphor_unassigned_trigger__";function ppe(e){return e==="table"}function gpe(e){return e.label||e.alias||e.name||e.id||""}function bpe(e){return e.alias||e.name||e.id||e.label||""}function Hxt(e){var n,r,o;const t=((o=(r=(n=e==null?void 0:e.preferences)==null?void 0:n.tablePrefs)==null?void 0:r.conditionalFormatting)==null?void 0:o.rules)||[];return new Set(t.flatMap(s=>[s.condition.columnId,...s.target.columnIds||[],...s.target.applyToColumnIds||[]]).filter(s=>s&&s!==la))}function ih(e,t,n){t&&t!==la&&(e.has(t)||e.set(t,{value:t,label:n||p.toLabel(t)}))}function xpe(e,t=[]){var u;const n=e==null?void 0:e.config,r=(u=e==null?void 0:e.preferences)==null?void 0:u.tablePrefs,o=new Map,s=new Map,i=Hxt(e),a=new Set(t);return t.forEach(d=>ih(o,d,d)),[...(n==null?void 0:n.detailColumns)||[],...(n==null?void 0:n.groupByColumns)||[],...(n==null?void 0:n.metricColumns)||[],...(n==null?void 0:n.pivotByColumns)||[]].forEach(d=>{const f=gpe(d),h=bpe(d);ih(o,h,f);const m={value:h,label:f||p.toLabel(h)};[d.id,d.alias,d.name,d.label].forEach(g=>{g&&s.set(g,m)}),d.id&&i.has(d.id)&&ih(o,d.id,f)}),[...Object.keys((r==null?void 0:r.columnSettingsMap)||{}),...Object.keys((r==null?void 0:r.columnVisibility)||{}),...Object.keys((r==null?void 0:r.columnSizing)||{})].forEach(d=>{const f=s.get(d),h=a.has(d)||o.has(d),m=i.has(d);!f&&!h&&!m||f&&!i.has(d)||ih(o,d,f==null?void 0:f.label)}),i.forEach(d=>ih(o,d)),Array.from(o.values())}function ype(e,t=[]){const n=new Map;if(t.length>0)return t.forEach(s=>ih(n,s,s)),Array.from(n.values());const r=e==null?void 0:e.config;return[...(r==null?void 0:r.detailColumns)||[],...(r==null?void 0:r.groupByColumns)||[],...(r==null?void 0:r.metricColumns)||[],...(r==null?void 0:r.pivotByColumns)||[]].forEach(s=>{ih(n,bpe(s),gpe(s))}),Array.from(n.values())}function qxt(e,t){var n;return{...e,preferences:{...e.preferences,tablePrefs:{...(n=e.preferences)==null?void 0:n.tablePrefs,conditionalFormatting:t}}}}const vpe=[{value:"gt",label:"Greater than"},{value:"gte",label:"Greater than or equal"},{value:"lt",label:"Less than"},{value:"lte",label:"Less than or equal"},{value:"eq",label:"Equals"},{value:"neq",label:"Does not equal"},{value:"between",label:"Between"},{value:"contains",label:"Contains"},{value:"blank",label:"Is blank"},{value:"notBlank",label:"Is not blank"}];function NT(e){return e===la}function y2(e){return e!=null&&String(e).trim()!==""}function EK(e){return typeof e=="number"&&Number.isFinite(e)}function Uxt(e){return e.condition.kind==="comparison"||e.condition.kind==="between"||e.condition.kind==="contains"||e.condition.kind==="blank"?"comparison":e.condition.kind}function wpe(e){return e.condition.kind==="blank"?e.condition.isBlank?"blank":"notBlank":e.condition.kind==="contains"?"contains":e.condition.kind==="between"?"between":e.condition.kind==="comparison"?e.condition.operator:"gt"}function RF(e){return e.condition.kind==="comparison"||e.condition.kind==="contains"?String(e.condition.value??""):e.condition.kind==="between"?String(e.condition.min??""):""}function Wxt(e){return e.condition.kind==="between"?String(e.condition.max??""):""}function qx(e){return typeof e=="number"&&Number.isFinite(e)?String(e):""}function Ux(e){if(!e.trim())return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Kxt(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Gxt(e){var n;if(NT(e.condition.columnId))return"Select a trigger column";const t=e.condition;return t.kind==="comparison"?`${(((n=vpe.find(o=>o.value===t.operator))==null?void 0:n.label)??t.operator).toLowerCase()} ${t.value??""}`.trim():t.kind==="between"?`between ${t.min??"?"}...${t.max??"?"}`:t.kind==="contains"?`contains "${t.value??""}"`:t.kind==="blank"?t.isBlank?"is blank":"is not blank":t.kind==="topBottom"?`${t.direction} ${t.count}`:t.kind==="colorScale"?t.range==="manual"?`scale ${t.min??"auto"}...${t.max??"auto"}`:"scale (auto)":t.kind==="dataBar"?t.range==="manual"?`bar ${t.min??"auto"}...${t.max??"auto"}`:"bar (auto)":""}function Cpe(e){return NT(e.condition.columnId)?"":e.condition.columnId}function DK(e){const t=new Map;return e.forEach(n=>{const r=typeof n=="string"?{value:n,label:n}:n;!r.value||t.has(r.value)||t.set(r.value,{value:r.value,label:r.label||r.value})}),Array.from(t.values())}function Yxt(e,t){var r,o;const n=((o=(r=globalThis.crypto)==null?void 0:r.randomUUID)==null?void 0:o.call(r))??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return`cf-${e||"unassigned"}-${t}-${n}`}function Spe(e){return e.condition.kind==="colorScale"||e.condition.kind==="dataBar"}function Zxt(e){return e==="colorScale"||e==="dataBar"}function u0(e){if(NT(e.condition.columnId))return!1;switch(e.condition.kind){case"comparison":case"contains":return y2(e.condition.value);case"between":return y2(e.condition.min)&&y2(e.condition.max);case"blank":case"topBottom":return!0;case"colorScale":case"dataBar":return e.condition.range==="manual"?EK(e.condition.min)&&EK(e.condition.max):!0;default:return!1}}function wy(e,t){return u0(t)?e.enabled===!1&&!u0(e)&&u0(t)?{...t,enabled:!0}:t:{...t,enabled:!1}}function Xxt(e){return u0(e)?e:{...e,enabled:!1}}function t1({columnId:e,existingRule:t,index:n,kind:r="comparison",operator:o="gt",value:s="",conditionColumnId:i}){var m,g,b,x,y;const a=i??(t==null?void 0:t.condition.columnId)??e,c=NT(a),u=Zxt(r),d=c?"":u?a:e||a;if(!d&&!a)return;const f={id:(t==null?void 0:t.id)??Yxt(c?"unassigned":d||a,r),name:(t==null?void 0:t.name)??`${c?"New formatting":d||"New formatting"} rule ${n+1}`,enabled:(t==null?void 0:t.enabled)??!c,target:{level:"cell",columnIds:!u&&((m=t==null?void 0:t.target.columnIds)!=null&&m.length)?t.target.columnIds:d?[d]:void 0,applyToColumnIds:t==null?void 0:t.target.applyToColumnIds,tableParts:["body"]},style:{backgroundColor:((g=t==null?void 0:t.style)==null?void 0:g.backgroundColor)??"#fee2e2",textColor:((b=t==null?void 0:t.style)==null?void 0:b.textColor)??"#b91c1c",fontWeight:(x=t==null?void 0:t.style)==null?void 0:x.fontWeight,italic:(y=t==null?void 0:t.style)==null?void 0:y.italic}},h=w=>t?wy(t,w):Xxt(w);if(r==="topBottom"){const w=(t==null?void 0:t.condition.kind)==="topBottom"?t.condition:void 0;return h({...f,condition:{kind:"topBottom",columnId:a||la,direction:(w==null?void 0:w.direction)??"top",count:(w==null?void 0:w.count)??10}})}if(r==="colorScale"){const w=(t==null?void 0:t.condition.kind)==="colorScale"?t.condition:void 0;return h({...f,style:void 0,condition:{kind:"colorScale",columnId:a||la,range:(w==null?void 0:w.range)??"auto",min:w==null?void 0:w.min,mid:w==null?void 0:w.mid,max:w==null?void 0:w.max,colors:(w==null?void 0:w.colors)??{min:"#fee2e2",mid:"#fef3c7",max:"#dcfce7"}}})}if(r==="dataBar"){const w=(t==null?void 0:t.condition.kind)==="dataBar"?t.condition:void 0;return h({...f,style:void 0,condition:{kind:"dataBar",columnId:a||la,range:(w==null?void 0:w.range)??"auto",min:w==null?void 0:w.min,max:w==null?void 0:w.max,color:(w==null?void 0:w.color)??"#3b82f6",showValue:(w==null?void 0:w.showValue)!==!1}})}if(o==="blank"||o==="notBlank")return h({...f,condition:{kind:"blank",columnId:a||la,isBlank:o==="blank"}});if(o==="contains")return h({...f,condition:{kind:"contains",columnId:a||la,value:String(s??"")}});if(o==="between"){const w=(t==null?void 0:t.condition.kind)==="between"?t.condition:void 0;return h({...f,condition:{kind:"between",columnId:a||la,min:s,max:(w==null?void 0:w.max)??"",inclusive:(w==null?void 0:w.inclusive)!==!1}})}return h({...f,condition:{kind:"comparison",columnId:a||la,operator:o,value:s}})}const Qxt=[{value:"comparison",label:"Compare"},{value:"topBottom",label:"Top/Bot."},{value:"colorScale",label:"Scale"},{value:"dataBar",label:"Data bar"}],Jxt=[{name:"none",bg:void 0,text:void 0},{name:"red",bg:"#fee2e2",text:"#b91c1c"},{name:"amber",bg:"#fef3c7",text:"#92400e"},{name:"emerald",bg:"#dcfce7",text:"#15803d"},{name:"sky",bg:"#dbeafe",text:"#1d4ed8"},{name:"zinc",bg:"#f4f4f5",text:"#52525b"}],eyt=["#fb923c","#22c55e","#3b82f6","#a855f7","#ec4899","#71717a"],tyt={emerald:["#fee2e2","#fef3c7","#dcfce7"],sky:["#fee2e2","#fef3c7","#dbeafe"],rose:["#dcfce7","#fef3c7","#fee2e2"],zinc:["#fef2f2","#f4f4f5","#e4e4e7"]};function kp({value:e,onChange:t,options:n,ariaLabel:r}){return l.jsx("div",{role:"radiogroup","aria-label":r,className:"inline-flex h-7 w-fit max-w-full items-center rounded-[5px] border border-border/60 bg-background p-0.5",children:n.map(o=>{const s=o.value===e;return l.jsx("button",{type:"button",role:"radio","aria-checked":s,"aria-label":o.ariaLabel??String(o.label),disabled:o.disabled,onClick:()=>t(o.value),className:p.cn("inline-flex h-full items-center rounded-[4px] px-2 text-[11px] font-medium transition-colors",o.disabled?"cursor-not-allowed text-muted-foreground/40":s?"bg-foreground text-background":"text-muted-foreground hover:text-foreground"),children:o.label},o.value)})})}function nyt({value:e,onChange:t}){return l.jsx("div",{className:"flex items-center gap-1",children:Jxt.map(n=>{const r=(e??"none")===(n.bg??"none");return l.jsx("button",{type:"button",onClick:()=>t(n.bg,n.text),"aria-label":n.name,className:p.cn("flex h-6 w-6 items-center justify-center rounded-[4px] border transition-colors",r?"border-foreground":"border-border/60 hover:border-border"),style:{backgroundColor:n.bg??"transparent"},children:r&&l.jsx(p.Check,{className:"size-3",strokeWidth:3,style:{color:n.text??"currentColor"}})},n.name)})})}function ryt({value:e,onChange:t}){return l.jsx("div",{className:"flex items-center gap-1",children:Object.entries(tyt).map(([n,r])=>{const[o,s,i]=r,a=e.min===o&&e.max===i;return l.jsx("button",{type:"button","aria-label":n,onClick:()=>t({min:o,mid:s,max:i}),className:p.cn("flex h-6 w-7 items-center justify-center rounded-[4px] border transition-colors",a?"border-foreground":"border-border/60 hover:border-border"),style:{background:`linear-gradient(to right, ${o}, ${s}, ${i})`},children:a&&l.jsx(p.Check,{className:"size-3 text-foreground mix-blend-difference",strokeWidth:3,style:{color:"#fff"}})},n)})})}function oyt({value:e,onChange:t}){return l.jsx("div",{className:"flex items-center gap-1",children:eyt.map(n=>{const r=e===n;return l.jsx("button",{type:"button","aria-label":n,onClick:()=>t(n),className:p.cn("flex h-6 w-6 items-center justify-center rounded-[4px] border transition-colors",r?"border-foreground":"border-border/60 hover:border-border"),style:{backgroundColor:n},children:r&&l.jsx(p.Check,{className:"size-3 text-white",strokeWidth:3})},n)})})}function syt({rule:e}){var o,s;const t=e.condition;if(t.kind==="colorScale")return l.jsx("span",{"aria-hidden":!0,className:"inline-block h-3 w-7 shrink-0 rounded-[3px] border border-border/60",style:{background:`linear-gradient(to right, ${t.colors.min}, ${t.colors.mid??t.colors.max}, ${t.colors.max})`}});if(t.kind==="dataBar")return l.jsx("span",{"aria-hidden":!0,className:"relative inline-block h-3 w-7 shrink-0 overflow-hidden rounded-[3px] border border-border/60 bg-muted",children:l.jsx("span",{className:"absolute inset-y-0 left-0 w-3/5",style:{backgroundColor:t.color}})});const n=(o=e.style)==null?void 0:o.backgroundColor,r=(s=e.style)==null?void 0:s.textColor;return l.jsx("span",{"aria-hidden":!0,className:"inline-flex h-3 w-7 shrink-0 items-center justify-center rounded-[3px] border border-border/60 text-[8px] font-bold leading-none",style:{backgroundColor:n??"transparent",color:r??"currentColor"},children:"Aa"})}function Wx({label:e,children:t}){return l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),l.jsx("div",{className:"flex flex-col gap-1.5",children:t})]})}function Gr({label:e,htmlFor:t,children:n,align:r="center"}){return l.jsxs("div",{className:p.cn("flex gap-2",r==="start"?"items-start":"items-center"),children:[l.jsx("label",{htmlFor:t,className:p.cn("w-20 shrink-0 text-[11px] text-muted-foreground",r==="start"&&"pt-1.5"),children:e}),l.jsx("div",{className:"min-w-0 flex-1",children:n})]})}function Cl({value:e,onValueChange:t,commitDelayMs:n=250,onBlur:r,onKeyDown:o,...s}){const[i,a]=v.useState(e),c=v.useRef(e),u=v.useRef(t);v.useEffect(()=>{u.current=t},[t]),v.useEffect(()=>{c.current=e,a(e)},[e]);const d=v.useCallback(f=>{f!==c.current&&(c.current=f,v.startTransition(()=>{u.current(f)}))},[]);return v.useEffect(()=>{if(i===c.current)return;const f=window.setTimeout(()=>d(i),n);return()=>window.clearTimeout(f)},[n,d,i]),l.jsx(p.Input,{...s,value:i,onChange:f=>a(f.target.value),onBlur:f=>{d(f.currentTarget.value),r==null||r(f)},onKeyDown:f=>{f.key==="Enter"&&d(f.currentTarget.value),o==null||o(f)}})}function Npe({columnId:e,availableColumns:t=[],conditionalRules:n,onConditionalRulesChange:r,startRulesWithNoTrigger:o=!1}){const[s,i]=v.useState(()=>n.length===1?new Set([n[0].id]):new Set);if(v.useEffect(()=>{i(k=>{const T=new Set(n.map(D=>D.id));let I=!1;const E=new Set(k);for(const D of E)T.has(D)||(E.delete(D),I=!0);return I?E:k})},[n]),!r)return null;const a=k=>{i(T=>{const I=new Set(T);return I.has(k)?I.delete(k):I.add(k),I})},c=(k,T)=>{r(n.map((I,E)=>I.id===k?T(I,E):I))},u=()=>{const k=t1({columnId:e,index:n.length,kind:"comparison",conditionColumnId:o?la:void 0});k&&(i(T=>new Set(T).add(k.id)),r([...n,k]))},d=k=>{const T=n.findIndex(R=>R.id===k);if(T<0)return;const I=n[T],E={...I,id:`${I.id}-copy-${Date.now()}`,name:`${I.name??"Rule"} (copy)`},D=[...n];D.splice(T+1,0,E),i(R=>new Set(R).add(E.id)),r(D)},f=k=>{r(n.filter(T=>T.id!==k))},h=(k,T)=>{const I=n.findIndex(A=>A.id===k),E=I+T;if(I<0||E<0||E>=n.length)return;const D=[...n],[R]=D.splice(I,1);D.splice(E,0,R),r(D)},m=(k,T,I)=>{const E=t1({columnId:e,existingRule:k,index:I,kind:T});E&&r(n.map(D=>D.id===k.id?E:D))},g=(k,T,I)=>{r(n.map(E=>E.id===k.id?t1({columnId:e,existingRule:E,index:I,kind:"comparison",operator:T,value:RF(E)}):E))},b=(k,T,I)=>{r(n.map(E=>E.id===k.id?t1({columnId:e,existingRule:E,index:I,kind:"comparison",operator:wpe(E),value:T}):E))},x=(k,T)=>{c(k,I=>I.condition.kind==="between"?wy(I,{...I,condition:{...I.condition,max:T}}):I)},y=(k,T)=>{c(k,I=>({...I,style:{...I.style,...T}}))},w=(k,T)=>{c(k,I=>I.condition.kind==="topBottom"?{...I,condition:{...I.condition,...T,count:T.count!==void 0?Math.max(1,Math.floor(T.count)):I.condition.count}}:I)},C=(k,T)=>{c(k,I=>I.condition.kind==="colorScale"?wy(I,{...I,condition:{...I.condition,...T,colors:{...I.condition.colors,...T.colors}}}):I)},N=(k,T)=>{c(k,I=>I.condition.kind==="dataBar"?wy(I,{...I,condition:{...I.condition,...T}}):I)},S=(k,T)=>{c(k,I=>{const E={...I,target:I.target.level==="cell"?{...I.target,columnIds:[T]}:I.target,condition:{...I.condition,columnId:T}};return wy(I,E)})},j=(k,T)=>{c(k,I=>{var R,A,F;if(Spe(I)&&T==="row")return I;const E=Cpe(I),D=((R=I.target.columnIds)==null?void 0:R[0])||E||void 0;return{...I,target:T==="row"?{...I.target,level:"row",columnIds:void 0,applyToColumnIds:I.target.applyToColumnIds,tableParts:(A=I.target.tableParts)!=null&&A.length?I.target.tableParts:["body"]}:{...I.target,level:"cell",columnIds:D?[D]:void 0,applyToColumnIds:void 0,tableParts:(F=I.target.tableParts)!=null&&F.length?I.target.tableParts:["body"]}}})},_=n.filter(k=>k.enabled!==!1).length;return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Conditional formatting"}),n.length>0&&l.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[_," enabled · ",n.length," total"]})]}),l.jsxs(p.Button,{type:"button",variant:"ghost",size:"xs",disabled:!e,onClick:u,className:"h-6 gap-1 px-2 text-[12px]",children:[l.jsx(Tr,{className:"size-3"}),"Add rule"]})]}),n.length===0?l.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"No conditional formatting rules for this column."}):l.jsx("ol",{className:"overflow-hidden rounded-[6px] border border-border/60",children:n.map((k,T)=>{const I=s.has(k.id);return l.jsxs("li",{className:"border-b border-border/60 bg-background last:border-b-0",children:[l.jsx(iyt,{rule:k,index:T,expanded:I,isFirst:T===0,isLast:T===n.length-1,onToggleExpand:()=>a(k.id),onToggleEnabled:E=>c(k.id,D=>E&&!u0(D)?D:{...D,enabled:E}),onMoveUp:()=>h(k.id,-1),onMoveDown:()=>h(k.id,1),onDuplicate:()=>d(k.id),onDelete:()=>f(k.id)}),I&&l.jsx(ayt,{rule:k,index:T,onUpdateName:E=>c(k.id,D=>({...D,name:E})),onUpdateRuleKind:E=>m(k,E,T),onUpdateConditionalOperator:E=>g(k,E,T),onUpdateConditionalValue:E=>b(k,E,T),onUpdateConditionalMaxValue:E=>x(k.id,E),onUpdateStyle:E=>y(k.id,E),onUpdateTopBottom:E=>w(k.id,E),onUpdateColorScale:E=>C(k.id,E),onUpdateDataBar:E=>N(k.id,E),availableColumns:t,onUpdateConditionColumn:E=>S(k.id,E),onUpdateTargetLevel:E=>j(k.id,E)})]},k.id)})})]})}function iyt({rule:e,index:t,expanded:n,isFirst:r,isLast:o,onToggleExpand:s,onToggleEnabled:i,onMoveUp:a,onMoveDown:c,onDuplicate:u,onDelete:d}){const f=Gxt(e),h=e.enabled!==!1;return l.jsxs("div",{className:p.cn("flex items-stretch gap-1 px-2 py-1.5 transition-colors",n?"bg-muted/40 shadow-[inset_2px_0_0] shadow-foreground":"hover:bg-muted/40"),children:[l.jsxs("div",{className:"flex shrink-0 flex-col items-center gap-0.5 pt-1 text-muted-foreground",children:[l.jsx("button",{type:"button","aria-label":`Move rule ${t+1} up`,disabled:r,onClick:a,className:"rounded-[3px] p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-30 disabled:hover:bg-transparent",children:l.jsx(bs,{className:"size-3"})}),l.jsx("button",{type:"button","aria-label":`Move rule ${t+1} down`,disabled:o,onClick:c,className:"rounded-[3px] p-0.5 text-muted-foreground hover:bg-foreground/10 hover:text-foreground disabled:opacity-30 disabled:hover:bg-transparent",children:l.jsx(es,{className:"size-3"})})]}),l.jsx("button",{type:"button",onClick:s,"aria-expanded":n,"aria-label":`${n?"Collapse":"Expand"} rule ${t+1}`,className:"flex min-w-0 flex-1 items-start py-0.5 text-left",children:l.jsxs("span",{className:"min-w-0 flex-1",children:[l.jsxs("span",{className:"flex items-center gap-2",children:[l.jsxs("span",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground",children:["#",t+1]}),l.jsx("span",{className:p.cn("truncate text-[12px] font-medium",h?"text-foreground":"text-muted-foreground line-through"),children:e.name??`Rule ${t+1}`})]}),l.jsxs("span",{className:"mt-0.5 flex flex-wrap items-center gap-1.5",children:[l.jsx(syt,{rule:e}),l.jsx("span",{className:"truncate text-[11px] text-muted-foreground",children:f})]})]})}),l.jsxs("div",{className:"flex shrink-0 items-start gap-1 pt-1",children:[l.jsx(p.Switch,{size:"xs","aria-label":h?`Disable rule ${t+1}`:`Enable rule ${t+1}`,checked:h,onCheckedChange:i}),l.jsxs(Uo,{children:[l.jsx(Wo,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":`Rule ${t+1} actions`,className:"inline-flex h-4 w-4 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(Rm,{className:"size-3"})})}),l.jsxs(Do,{align:"end",className:"min-w-[140px]",children:[l.jsxs(kn,{className:"gap-2 text-[12px]",onClick:u,children:[l.jsx(Jh,{className:"size-3"}),"Duplicate"]}),l.jsxs(kn,{className:"gap-2 text-[12px] text-destructive focus:text-destructive",onClick:d,children:[l.jsx(el,{className:"size-3"}),"Delete"]})]})]})]})]})}function ayt({rule:e,index:t,availableColumns:n,onUpdateName:r,onUpdateConditionColumn:o,onUpdateTargetLevel:s,onUpdateRuleKind:i,onUpdateConditionalOperator:a,onUpdateConditionalValue:c,onUpdateConditionalMaxValue:u,onUpdateStyle:d,onUpdateTopBottom:f,onUpdateColorScale:h,onUpdateDataBar:m}){var N,S,j,_;const g=Uxt(e),b=wpe(e),x=e.id,y=Cpe(e),w=DK(n),C=!Spe(e);return l.jsxs("div",{className:"space-y-3 border-t border-border/60 bg-muted/20 px-3 py-3",children:[l.jsx(Gr,{label:"Name",htmlFor:`cf-name-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-name-${x}`,value:e.name??"",onValueChange:r,className:`w-full ${p.removeRing}`,placeholder:`Rule ${t+1}`})}),l.jsxs(Wx,{label:"Target",children:[l.jsxs(Gr,{label:"Target",children:[l.jsx(kp,{ariaLabel:"Formatting target",value:e.target.level,onChange:s,options:[{value:"cell",label:"Cell"},{value:"row",label:"Row",ariaLabel:C?"Row":"Row target is not available for this rule type",disabled:!C}]}),!C&&l.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"Color scales and data bars format cells because their values are column-specific."})]}),l.jsx(Gr,{label:"Trigger",htmlFor:`cf-trigger-${x}`,children:l.jsxs(p.Select,{value:y||"",onValueChange:o,children:[l.jsx(p.SelectTrigger,{size:"xs",id:`cf-trigger-${x}`,className:`w-full ${p.simpleRing}`,children:l.jsx(p.SelectValue,{placeholder:""})}),l.jsx(p.SelectContent,{children:(w.length?w:DK([y])).filter(k=>!!k.value).map(k=>l.jsx(p.SelectItem,{value:k.value,children:k.label},k.value))})]})})]}),l.jsxs(Wx,{label:"Condition",children:[l.jsx(kp,{ariaLabel:"Rule type",value:g,onChange:i,options:Qxt}),g==="comparison"&&l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Operator",htmlFor:`cf-operator-${x}`,children:l.jsxs(p.Select,{value:b,onValueChange:k=>a(k),children:[l.jsx(p.SelectTrigger,{size:"xs",id:`cf-operator-${x}`,className:`w-full ${p.simpleRing}`,children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:vpe.map(k=>l.jsx(p.SelectItem,{value:k.value,children:k.label},k.value))})]})}),b==="between"?l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Min",htmlFor:`cf-value-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-value-${x}`,"aria-label":"Value",value:RF(e),onValueChange:c,className:`w-full ${p.removeRing}`,placeholder:"Minimum…"})}),l.jsx(Gr,{label:"Max",htmlFor:`cf-max-value-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-max-value-${x}`,value:Wxt(e),onValueChange:u,className:`w-full ${p.removeRing}`,placeholder:"Maximum…"})})]}):b!=="blank"&&b!=="notBlank"?l.jsx(Gr,{label:"Value",htmlFor:`cf-value-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-value-${x}`,value:RF(e),onValueChange:c,className:`w-full ${p.removeRing}`,placeholder:b==="contains"?"Text to match…":"Value…"})}):null]}),e.condition.kind==="topBottom"&&l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Direction",children:l.jsx(kp,{ariaLabel:"Direction",value:e.condition.direction,onChange:k=>f({direction:k}),options:[{value:"top",label:"Top"},{value:"bottom",label:"Bottom"}]})}),l.jsx(Gr,{label:"Count",htmlFor:`cf-count-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-count-${x}`,type:"number",min:1,value:String(e.condition.count),onValueChange:k=>f({count:Kxt(k,1)}),className:`w-full ${p.removeRing}`})})]}),e.condition.kind==="colorScale"&&l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Range",children:l.jsx(kp,{ariaLabel:"Range",value:e.condition.range,onChange:k=>h({range:k}),options:[{value:"auto",label:"Auto"},{value:"manual",label:"Manual"}]})}),e.condition.range==="manual"&&l.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[l.jsx(Cl,{size:"xs",type:"number","aria-label":"Min",placeholder:"Min",value:qx(e.condition.min),onValueChange:k=>h({min:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`}),l.jsx(Cl,{size:"xs",type:"number","aria-label":"Mid",placeholder:"Mid",value:qx(e.condition.mid),onValueChange:k=>h({mid:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`}),l.jsx(Cl,{size:"xs",type:"number","aria-label":"Max",placeholder:"Max",value:qx(e.condition.max),onValueChange:k=>h({max:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`})]}),l.jsx(Gr,{label:"Palette",children:l.jsx(ryt,{value:e.condition.colors,onChange:k=>h({colors:k})})})]}),e.condition.kind==="dataBar"&&l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Range",children:l.jsx(kp,{ariaLabel:"Range",value:e.condition.range,onChange:k=>m({range:k}),options:[{value:"auto",label:"Auto"},{value:"manual",label:"Manual"}]})}),e.condition.range==="manual"&&l.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[l.jsx(Cl,{size:"xs",type:"number","aria-label":"Min",placeholder:"Min",value:qx(e.condition.min),onValueChange:k=>m({min:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`}),l.jsx(Cl,{size:"xs",type:"number","aria-label":"Max",placeholder:"Max",value:qx(e.condition.max),onValueChange:k=>m({max:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`})]}),l.jsx(Gr,{label:"Show value",children:l.jsx(p.Switch,{size:"xs","aria-label":"Show cell value on data bar",checked:e.condition.showValue!==!1,onCheckedChange:k=>m({showValue:k})})})]})]}),(g==="comparison"||e.condition.kind==="topBottom")&&l.jsxs(Wx,{label:"Format",children:[l.jsx(Gr,{label:"Preset",children:l.jsx(nyt,{value:(N=e.style)==null?void 0:N.backgroundColor,onChange:(k,T)=>d({backgroundColor:k,textColor:T})})}),l.jsx(Gr,{label:"Fill",htmlFor:`cf-fill-${x}`,children:l.jsx(da,{id:`cf-fill-${x}`,ariaLabel:"Fill Color",value:((S=e.style)==null?void 0:S.backgroundColor)||void 0,onChange:k=>d({backgroundColor:k}),defaultValue:"#fee2e2"})}),l.jsx(Gr,{label:"Text",htmlFor:`cf-text-${x}`,children:l.jsx(da,{id:`cf-text-${x}`,ariaLabel:"Text Color",value:((j=e.style)==null?void 0:j.textColor)||void 0,onChange:k=>d({textColor:k}),defaultValue:"#b91c1c"})}),l.jsx(Gr,{label:"Weight",children:l.jsx(kp,{ariaLabel:"Font weight",value:((_=e.style)==null?void 0:_.fontWeight)??"normal",onChange:k=>d({fontWeight:k==="normal"?void 0:k}),options:[{value:"normal",label:"R",ariaLabel:"Regular"},{value:"medium",label:"M",ariaLabel:"Medium"},{value:"bold",label:"B",ariaLabel:"Bold"}]})})]}),e.condition.kind==="colorScale"&&l.jsxs(Wx,{label:"Colors",children:[l.jsx(Gr,{label:"Low",htmlFor:`cf-low-color-${x}`,children:l.jsx(da,{id:`cf-low-color-${x}`,ariaLabel:"Low color",value:e.condition.colors.min,onChange:k=>h({colors:{min:k??"#fee2e2"}}),defaultValue:"#fee2e2",allowEmpty:!1})}),l.jsx(Gr,{label:"Mid",htmlFor:`cf-mid-color-${x}`,children:l.jsx(da,{id:`cf-mid-color-${x}`,ariaLabel:"Mid color",value:e.condition.colors.mid||void 0,onChange:k=>h({colors:{mid:k}}),defaultValue:"#fef3c7"})}),l.jsx(Gr,{label:"High",htmlFor:`cf-high-color-${x}`,children:l.jsx(da,{id:`cf-high-color-${x}`,ariaLabel:"High color",value:e.condition.colors.max,onChange:k=>h({colors:{max:k??"#dcfce7"}}),defaultValue:"#dcfce7",allowEmpty:!1})})]}),e.condition.kind==="dataBar"&&l.jsxs(Wx,{label:"Bar color",children:[l.jsx(Gr,{label:"Preset",children:l.jsx(oyt,{value:e.condition.color,onChange:k=>m({color:k})})}),l.jsx(Gr,{label:"Color",htmlFor:`cf-bar-color-${x}`,children:l.jsx(da,{id:`cf-bar-color-${x}`,ariaLabel:"Bar color",value:e.condition.color,onChange:k=>m({color:k??"#3b82f6"}),defaultValue:"#3b82f6",allowEmpty:!1})})]})]})}function lyt({field:e,dataSource:t,connectionId:n,connectionType:r,filterId:o}){var f,h;const{qualifiedColumnName:s,qualifiedTableName:i}=Khe(e),a=p.getDataType(e.dataType),c=a==="date"?"between":"in",u=Kz(e),d=Gz(t,{connectionId:n,connectionType:r});return{id:o||dt.v4(),title:e.label||e.name,connectionId:n||(t==null?void 0:t.connectionId)||"",column:s,dataType:e.dataType,table:e.entityName||"",database:((h=(f=t==null?void 0:t.selectedEntities)==null?void 0:f[0])==null?void 0:h.database)||"",qualifiedTableName:i,operation:c,sql:"",fieldMeta:u,semanticContext:d,...a==="date"?{dateSelectionMode:"range"}:{type:"single"}}}function cyt(e,t){return e.kind==="filter"&&rb(e.filter,t)}function jT(e){return p.getDataType(e.dataType)==="date"?["label","start","end","range"]:["label","value"]}function jpe(e){return uyt(e)?["label","value"]:["value"]}function uyt(e){return e.type==="enum"||e.type==="multi_enum"||e.type==="field_selector"||e.type==="metric_selector"||e.type==="aggregation_selector"||e.type==="grain_selector"}function rx(e,t){return(e.inputs||[]).filter(n=>Qh(n,{sheetId:t,sheetKind:"document"}))}function kpe(e,t){const n=dyt(e,t);return(e.inputs||[]).some(r=>Qh(r,{sheetId:t,sheetKind:"document"})||r.scope.kind==="documentSections"&&r.scope.sheetId===t||r.scope.kind==="cards"&&r.scope.cardIds.some(o=>n.has(o)))}function dyt(e,t){var o,s,i;const n=new Set,r=(o=e.sheets)==null?void 0:o.find(a=>a.id===t);for(const a of((s=r==null?void 0:r.document)==null?void 0:s.sections)||[])(a.type==="table"||a.type==="chart")&&((i=a.card)!=null&&i.id)&&n.add(a.card.id);return n}function lC(e){const t={id:e.id,label:e.label,variableName:e.variableName,requiredAtExecution:!!e.requiredAtExecution,documentPlacement:"input_bar",description:e.description};return e.kind==="filter"?{...t,kind:"filter",filter:e.filter,exports:e.exports}:{...t,kind:"control",control:e.control,exports:e.exports}}function fyt({field:e,existingInputs:t,sheetId:n,dataSource:r,connectionId:o,connectionType:s,inputId:i,filterId:a}){const c=e.label||e.name,u=lyt({field:e,dataSource:r,connectionId:o,connectionType:s,filterId:a}),d=bO(c,t);return{id:i||dt.v4(),kind:"filter",label:c,variableName:d,requiredAtExecution:!1,scope:{kind:"sheets",sheetIds:[n]},runtimeScope:"perSheet",presentation:{placement:"toolbar"},filter:{...u,variableName:d},exports:jT(u)}}function hyt({control:e,existingInputs:t,sheetId:n,inputId:r}){const o=Od(e.id||e.label,t),s=e.id===o?e:{...e,id:o};return{id:r||dt.v4(),kind:"control",label:s.label,variableName:o,requiredAtExecution:s.requiredAtExecution,scope:{kind:"sheets",sheetIds:[n]},runtimeScope:"perSheet",presentation:{placement:"toolbar"},control:s,exports:jpe(s)}}function AF({input:e,allInputs:t,label:n,variableName:r}){const o=(n==null?void 0:n.trim())||e.label,s=r===void 0?e.variableName:Od(r,t.filter(a=>a.id!==e.id));if(e.kind==="filter"){const a={...e.filter,title:o,variableName:s};return{...e,label:o,variableName:s,filter:a,exports:jT(a)}}const i={...e.control,id:s,label:o};return{...e,label:o,variableName:s,requiredAtExecution:i.requiredAtExecution,control:i,exports:jpe(i)}}function PF(e,t,n){return!t||!n||t===n?e:{...e,sections:e.sections.map(r=>r.type!=="table"&&r.type!=="chart"||!r.card?r:{...r,card:myt(r.card,t,n)})}}function myt(e,t,n){var s;const r=`[[param.${t}]]`,o=`[[param.${n}]]`;return{...e,...(s=e.sql)!=null&&s.includes(r)?{sql:e.sql.split(r).join(o)}:{},...e.controls?{controls:e.controls.map(i=>i.id===t?{...i,id:n}:i)}:{},...e.controlBindings?{controlBindings:e.controlBindings.map(i=>({...i,controlId:i.controlId===t?n:i.controlId,...i.target==="sql_param"&&i.paramId===t?{paramId:n}:{}}))}:{}}}function pyt(e,t){return e.kind==="filter"&&cyt(lC(e),t)}function gyt(e){var n;const t={};for(const r of e)r.kind==="filter"&&(t[r.id]=((n=r.slot)==null?void 0:n.status)==="cleared"?void 0:r.filterValue);return t}function byt(e){var n;const t={};for(const r of e)r.kind==="control"&&((n=r.slot)==null?void 0:n.status)==="set"&&(t[r.id]=r.controlValue);return t}function xyt({dashboard:e,sheetId:t,filterValuesByInputId:n,controlValuesByInputId:r}){var i;const o=rx(e,t);let s={};for(const a of o)if(((i=a.compatibility)==null?void 0:i.source)==="documentInput"){if(a.kind==="filter"&&n&&Object.prototype.hasOwnProperty.call(n,a.id)){const c=n[a.id];s=p.setDashboardInputRuntimeSlot(s,a,{sheetId:t},c?{status:"set",value:{kind:"filter",filterValue:c}}:{status:"cleared"})}if(a.kind==="control"&&r&&Object.prototype.hasOwnProperty.call(r,a.id)){const c=r[a.id];s=p.setDashboardInputRuntimeSlot(s,a,{sheetId:t},c===void 0?{status:"cleared"}:{status:"set",value:{kind:"control",value:c}})}}return dR({dashboard:e,dashboardInputValues:s,sheetId:t})}const yyt=[],vyt={},wyt={},Cyt={};function Syt(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Nyt({sheet:e}){var sn;const n=p.useDashboardStore(Le=>{var et,at,ht;return(ht=(at=(et=Le.dashboard)==null?void 0:et.sheets)==null?void 0:at.find(Vt=>Vt.id===e.id))==null?void 0:ht.document})||e.document||p.createDefaultDocumentDefinition(),r=p.useDashboardStore(Le=>Le.dashboard),o=p.useDashboardStore(Le=>Le.dashboardInputValues),s=p.useDashboardStore(Le=>Le.filterValues),i=p.useDashboardStore(Le=>Le.controlValues),a=p.useDashboardStore(Le=>Le.inlineFilterValuesMap),c=p.useDashboardStore(Le=>Le.cardControlValuesMap),u=v.useMemo(()=>rx(r,e.id),[r,e.id]),d=u.length>0,f=v.useMemo(()=>kpe(r,e.id),[r,e.id]),h=v.useMemo(()=>d?u.map(lC):n.inputs||yyt,[n.inputs,u,d]),m=v.useMemo(()=>new Map(u.map(Le=>[Le.id,Le])),[u]),g=v.useMemo(()=>h.filter(Ql).map(Le=>Le.control),[h]),{authToken:b,tokenProps:x,documentInputValues:y,dashboardInputExecutionSnapshot:w,renderMode:C}=It(),{displayPreferences:N}=cl(),S=dl()??void 0,j=p.useDashboardStore(Le=>Le.isDashboardEditing),_=p.useDashboardStore(Le=>Le.isDownloadingPdf),k=eee({displayMode:N.mode,renderMode:C}),T=k?"print":j?"edit":"view",{updateSheetDocument:I,setSelectedDocumentSectionId:E,setDocumentInspectorTab:D,setDocumentInputFilterValues:R,setDocumentInputFilterValue:A,setDocumentInputFilterModes:F,setDocumentInputFilterMode:z,removeDocumentInputFilterValue:L,setDocumentInputControlValues:$,setDocumentInputControlValue:H,upsertDashboardInput:M,removeDashboardInput:B,setDashboardInputSlot:W,clearDashboardInputSlot:P}=p.useDashboardActions(),G=p.useDashboardStore(Le=>Le.documentInspectorTabsBySheetId[e.id]||"page"),Z=Gpt(),[X,Y]=v.useState(null),[O,q]=v.useState(null),[U,V]=v.useState("edit"),[K,Q]=v.useState({pageNumber:1,pageCount:1}),[se,oe]=v.useState({}),[me,le]=v.useState(!1),ue=Wr(),[ne,de]=v.useState(100),Ce=p.useDashboardStore(Le=>Le.documentInputRuntimeBySheetId[e.id]),ce=v.useMemo(()=>Cme(h,S),[h,S]),ie=v.useMemo(()=>Sme(h),[h]),we=y!=null&&y.sheetId&&y.sheetId!==e.id?void 0:y,fe=we==null?void 0:we.filterValuesByInputId,ae=we==null?void 0:we.controlValuesByInputId,ee=v.useMemo(()=>!w&&we?xyt({dashboard:r,sheetId:e.id,filterValuesByInputId:fe,controlValuesByInputId:ae}):void 0,[w,r,ae,we,fe,e.id]),J=v.useMemo(()=>Rpt(h),[h]),re=v.useMemo(()=>Nme(h),[h]),pe=v.useRef(re),Ee=v.useMemo(()=>Yi({dashboard:r,sheetId:e.id,sheetKind:"document",runtimeValues:{...ee?{dashboardInputValues:ee}:{dashboardInputValues:o},filterValues:s,controlValues:i,inlineFilterValuesMap:a,cardControlValuesMap:c},mode:k?"print":"interactive",timezone:S}),[r,c,i,s,a,o,S,k,ee,e.id]),Te=v.useMemo(()=>gyt(Ee.resolvedInputs),[Ee.resolvedInputs]),ze=v.useMemo(()=>byt(Ee.resolvedInputs),[Ee.resolvedInputs]),Pe=v.useMemo(()=>d?Te:we?fe||vyt:(Ce==null?void 0:Ce.filterValuesByInputId)||ce,[ce,Te,we,fe,d,Ce==null?void 0:Ce.filterValuesByInputId]),He=v.useMemo(()=>d?Uyt(h,Te):(Ce==null?void 0:Ce.filterModesByInputId)||wyt,[Te,h,d,Ce==null?void 0:Ce.filterModesByInputId]),ye=v.useMemo(()=>d?ze:we?ae||Cyt:(Ce==null?void 0:Ce.controlValuesByInputId)||ie,[ie,ze,ae,we,d,Ce==null?void 0:Ce.controlValuesByInputId]),[Ke,We]=v.useState({}),[Qe,xe]=v.useState((w==null?void 0:w.generatedAt)||(we==null?void 0:we.generatedAt)||new Date().toISOString()),Ve=v.useMemo(()=>n.sections.find(Le=>Le.type==="table")||null,[n.sections]),Ae=v.useMemo(()=>n.sections.find(Le=>Le.id===X)||null,[n.sections,X]),ke=(Ae==null?void 0:Ae.type)==="table"?Ae:Ve,Be=(ke==null?void 0:ke.id)||X||null;v.useEffect(()=>{E(e.id,Be)},[Be,E,e.id]),v.useEffect(()=>{const Le=pe.current;if(we){we.generatedAt&&xe(et=>et===we.generatedAt?et:we.generatedAt),pe.current=re;return}d||(R(e.id,Apt(Pe,h,ce,re,Le)),$(e.id,Ppt(ye,h,ie,re,Le))),pe.current=re},[ye,J,Pe,h,ce,ie,re,we,d,$,R,e.id]),v.useEffect(()=>{d||F(e.id,Opt(He,h))},[He,J,h,d,F,e.id]);const Ie=v.useCallback((Le,et)=>{const at=h.find(Xn=>Xn.id===Le),ht=at&&cc(at)?gv(at,et):et;if(!ht)return;const Vt=m.get(Le);if(Vt){W(Vt,{sheetId:e.id},{status:"set",value:{kind:"filter",filterValue:ht}});return}A(e.id,Le,ht)},[m,h,W,A,e.id]),$e=v.useCallback((Le,et)=>{const at=h.find(Xn=>Xn.id===Le),ht=m.get(Le);ht||z(e.id,Le,et);const Vt=at&&cc(at)?gv(at,Pe[Le]):Pe[Le];if(!(!Vt||!vT(Vt.operation))){if(ht){W(ht,{sheetId:e.id},{status:"set",value:{kind:"filter",filterValue:{...Vt,operation:DF(et)}}});return}A(e.id,Le,{...Vt,operation:DF(et)})}},[Pe,h,m,W,z,A,e.id]),st=v.useCallback(Le=>{const et=m.get(Le);if(et){P(et,{sheetId:e.id});return}L(e.id,Le)},[P,m,L,e.id]),ct=v.useCallback((Le,et,at)=>{const ht=m.get(Le);if((ht==null?void 0:ht.kind)==="filter"){M(AF({input:{...ht,label:et.title||ht.label,filter:et,exports:jT(et)},allInputs:r.inputs||[],label:et.title||ht.label,variableName:at==null?void 0:at.variableName}));return}I(e.id,Vt=>Hyt(Vt,Le,et,at))},[r.inputs,m,e.id,I,M]),rt=v.useCallback((Le,et)=>{const at=m.get(Le);if((at==null?void 0:at.kind)==="control"){const ht=AF({input:{...at,requiredAtExecution:et.requiredAtExecution,control:et},allInputs:r.inputs||[],label:et.label||at.label,variableName:et.id||at.variableName});M(ht),ht.kind==="control"&&at.control.id!==ht.control.id&&I(e.id,Vt=>PF(Vt,at.control.id,ht.control.id));return}I(e.id,ht=>{const Vt=(ht.inputs||[]).find(Go=>Go.id===Le&&Ql(Go)),Xn=qyt(ht,Le,et);return Vt&&Vt.control.id!==et.id?PF(Xn,Vt.control.id,et.id):Xn})},[r.inputs,m,e.id,I,M]),Ct=v.useCallback(Le=>{if(m.has(Le)){B(Le);return}I(e.id,et=>({...et,inputs:(et.inputs||[]).filter(at=>at.id!==Le)}))},[m,B,e.id,I]),Lt=v.useCallback((Le,et)=>{const at=m.get(Le);if(at){if(et===void 0){P(at,{sheetId:e.id});return}W(at,{sheetId:e.id},{status:"set",value:{kind:"control",value:et}});return}H(e.id,Le,et)},[P,m,W,H,e.id]),vt=v.useCallback((Le,et)=>{We(at=>Kyt(at[Le]||[],et)?at:{...at,[Le]:et})},[]);v.useEffect(()=>{const Le=new Set(h.filter(Ql).map(et=>et.id));We(et=>{const at=Object.fromEntries(Object.entries(et).filter(([ht])=>Le.has(ht)));return Object.keys(at).length===Object.keys(et).length?et:at})},[h]);const Tt=v.useMemo(()=>d?Ee.activeFilters:Bpt(Pe,h,re,pe.current),[Ee.activeFilters,Pe,h,re,d]),Me=v.useMemo(()=>d?Ee.controlValues:Vpt(ye,h,re,pe.current),[Ee.controlValues,ye,h,re,d]),Je=v.useMemo(()=>d?Ee.missingRequiredInputs.map(Le=>Le.label):_me(h,Pe,ye,re,pe.current),[Ee.missingRequiredInputs,h,Pe,ye,re,d]),kt=v.useMemo(()=>f?YY({dashboard:r,sheetId:e.id,sheetKind:"document",sectionIds:n.sections.map(Le=>Le.id),mode:"document",runtimeValues:{dashboardInputValues:o,filterValues:s,controlValues:i,inlineFilterValuesMap:a,cardControlValuesMap:c},timezone:S}):Je,[r,c,i,s,a,o,n.sections,S,f,Je,e.id]),mt=v.useMemo(()=>{var Le;return hpt({inputs:h,filterValuesByInputId:Pe,controlValuesByInputId:ye,controlOptionsByInputId:Ke,generatedAt:Qe,timezone:S,generatedAtFormat:(Le=n.runtime)==null?void 0:Le.generatedAtFormat})},[h,Pe,ye,Ke,Qe,S,(sn=n.runtime)==null?void 0:sn.generatedAtFormat]),_t=v.useCallback(Le=>{I(e.id,Le)},[e.id,I]),Rt=v.useCallback(Le=>D(e.id,Le),[D,e.id]),Pt=v.useCallback((Le,et,at)=>{oe(ht=>{const Vt=ht[Le];if(et.length===0){if((Vt==null?void 0:Vt.schemaSignature)===at||!Vt)return ht;const Xn={...ht};return delete Xn[Le],Xn}return(Vt==null?void 0:Vt.schemaSignature)===at&&Syt(Vt.columns,et)?ht:{...ht,[Le]:{schemaSignature:at,columns:et}}})},[]),wt=(Le,et={})=>{Y(Le),!Le&&G==="section"?Rt("page"):Le&&et.activateSectionInspector!==!1&&Rt("section"),q(null)},Et=(Le,et)=>{const at=jpt(Le);_t(ht=>({...ht,sections:[...ht.sections.slice(0,et),at,...ht.sections.slice(et)]})),Y(at.id),Rt("section"),q(null),at.type==="table"&&Z(e.id,at)},Bt=Le=>{X&&_t(et=>({...et,sections:et.sections.map(at=>at.id===X?Le(at):at)}))},un=()=>{X&&Ge(X)},Ge=Le=>{var ht;const et=Le===X,at=n.sections.filter(Vt=>Vt.id!==Le);_t(Vt=>({...Vt,sections:Vt.sections.filter(Xn=>Xn.id!==Le)})),et&&(Y(((ht=at[0])==null?void 0:ht.id)||null),Rt(at[0]?"section":"page"))},Re=(Le,et,at)=>{Le!==et&&(_t(ht=>{const Vt=ht.sections.findIndex(Qi=>Qi.id===Le),Xn=ht.sections.findIndex(Qi=>Qi.id===et);if(Vt===-1||Xn===-1)return ht;const Go=[...ht.sections],[Rs]=Go.splice(Vt,1),Lr=at==="after"?Xn+1:Xn,Co=Vt<Lr?Lr-1:Lr;return Go.splice(Math.min(Co,Go.length),0,Rs),{...ht,sections:Go}}),Y(Le))},De=Le=>{_t(et=>({...et,page:Le}))},he=v.useCallback((Le,et)=>{_t(at=>({...at,sections:at.sections.map(ht=>ht.id===Le&&ht.type==="table"?et(ht):ht)}))},[_t]),Fe=Le=>{_t(et=>({...et,header:Le(et.header)}))},ot=Le=>{_t(et=>({...et,footer:Le(et.footer)}))},Dt=v.useCallback(Le=>{Z(e.id,Le,Tt,g,Me,Je)},[g,Me,Tt,Je,Z,e.id]),nt=v.useCallback(async()=>{if(!(x!=null&&x.apiServiceUrl)||!b){lt.error("Unable to export document PDF without an active session");return}if(kt.length>0){lt.error(`Set ${kt.join(", ")} before exporting`);return}const Le=new Date().toISOString(),et=f?ZY({dashboard:r,sheetId:e.id,sheetKind:"document",sectionIds:n.sections.map(ht=>ht.id),mode:"document",runtimeValues:{dashboardInputValues:o,filterValues:s,controlValues:i,inlineFilterValuesMap:a,cardControlValuesMap:c},generatedAt:Le,timezone:S}).snapshot:void 0,at=lt.loading("Generating document PDF...");try{await Q5(x.apiServiceUrl,b,{sheetId:e.id,title:e.title||"Document",pageSize:n.page.size,orientation:n.page.orientation,timezone:S,inputSnapshot:et,...et?{}:{inputValues:{sheetId:e.id,filterValuesByInputId:Pe,controlValuesByInputId:ye,generatedAt:Le}}}),lt.dismiss(at),lt.success("Document PDF downloaded")}catch(ht){lt.dismiss(at),lt.error("Failed to export document PDF",{description:j_(ht,"Please try again or contact support."),descriptionClassName:N_,closeButton:!0,duration:1/0}),console.error("Document PDF export error:",ht)}},[b,n.page.orientation,n.page.size,n.sections,r,c,i,s,a,o,ye,Pe,S,kt,f,e.id,e.title,x==null?void 0:x.apiServiceUrl]),ge=l.jsxs("button",{type:"button",disabled:_||kt.length>0,onClick:nt,title:kt.length>0?`Set ${kt.join(", ")} before exporting`:void 0,className:p.cn(v2,"disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[_?l.jsx(p.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):l.jsx(Su,{className:"h-3.5 w-3.5"}),"Export"]}),Se=U==="preview",Oe=l.jsx("button",{type:"button",onClick:()=>{Se?V("edit"):(V("preview"),q(null))},"aria-pressed":Se,className:p.cn(v2,Se?"bg-primary text-primary-foreground hover:bg-primary/90":"text-foreground hover:bg-muted"),children:Se?"Exit preview":"Show preview"}),Ye=v.useCallback(Le=>{Q(et=>{const at=Math.max(1,et.pageCount),ht=Math.min(at,Math.max(1,Math.round(Le)));return et.pageNumber===ht?et:{...et,pageNumber:ht}})},[]),bt=v.useCallback(Le=>{Q(et=>{const at=Math.max(et.pageCount,Le,1),ht=Math.min(et.pageNumber,at);return et.pageNumber===ht&&et.pageCount===at?et:{pageNumber:ht,pageCount:at}})},[]),St=v.useCallback(async()=>{le(!0),xe(new Date().toISOString());try{await ue.invalidateQueries({refetchType:"active",predicate:Le=>{const et=Le.queryKey;return Array.isArray(et)&&(et.includes("documentSection")||et[0]==="documentTableRows")}})}finally{le(!1)}},[ue]),on=l.jsxs(p.Button,{type:"button",variant:"ghost",size:"sm",className:p.cn(v2,"font-normal text-foreground hover:bg-muted hover:text-foreground"),onClick:St,disabled:me,"aria-label":"Refresh report",children:[l.jsx(tc,{className:p.cn("h-3.5 w-3.5",me&&"animate-spin")}),"Refresh"]});return T==="print"?l.jsxs(l.Fragment,{children:[l.jsx(d2,{inputs:h,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,onOptionsChange:vt}),l.jsx(sxt,{document:n,inputs:h,textRenderContext:mt,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,documentDashboardInputValues:ee,missingRequiredInputLabels:Je})]}):T==="view"?l.jsxs(l.Fragment,{children:[l.jsx(d2,{inputs:h,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,onOptionsChange:vt}),l.jsx(rxt,{document:n,inputs:h,textRenderContext:mt,filterValuesByInputId:Pe,filterModesByInputId:He,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,documentDashboardInputValues:ee,missingRequiredInputLabels:Je,onSetFilterValue:Ie,onSetFilterMode:$e,onRemoveFilterValue:st,controlValuesByInputId:ye,onSetControlValue:Lt,actions:l.jsxs(MK,{children:[on,l.jsx(w2,{}),ge]})})]}):l.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-muted/60 text-foreground",children:[l.jsx(d2,{inputs:h,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,onOptionsChange:vt}),l.jsx(Hgt,{sections:n.sections,inputs:h,selectedSectionId:X,onSelectSection:wt,onDeleteSection:Ge,onReorderSection:Re,onInsertSection:Le=>Et(Le,n.sections.length)}),l.jsxs("main",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[l.jsx(Ume,{inputs:h,filterValuesByInputId:Pe,filterModesByInputId:He,documentFilterValues:Tt,documentControlValues:Me,onSetFilterValue:Ie,onSetFilterMode:$e,onUpdateFilterInput:ct,onUpdateControlInput:rt,onRemoveFilterValue:st,onRemoveInput:Ct,controlValuesByInputId:ye,onSetControlValue:Lt,actions:l.jsxs(MK,{children:[on,l.jsx(w2,{}),l.jsx(Gyt,{zoom:ne,onZoomChange:de}),l.jsx(w2,{}),Oe]}),isEditing:!0}),l.jsxs("div",{className:"relative min-h-0 flex-1 overflow-auto",onClick:Le=>{Le.target===Le.currentTarget&&wt(null)},children:[l.jsx("div",{style:{zoom:ne/100},className:"flex justify-center px-6 py-8",children:l.jsx(b4,{document:n,inputs:h,textRenderContext:mt,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,documentDashboardInputValues:ee,missingRequiredInputLabels:Je,isEditing:!Se,selectedSectionId:Se?void 0:X,activeAddIndex:Se?null:O,onSelectSection:wt,onToggleAddIndex:q,onInsertSection:Et,onEditTableSection:Dt,onUpdateTableSection:he,onTableResultColumnsChange:Pt,onReorderSection:Re,pageNumber:K.pageNumber,onPageCountChange:bt,measurementScale:ne/100})}),l.jsx(Eyt,{pageNumber:K.pageNumber,pageCount:K.pageCount,onFirst:()=>Ye(1),onPrevious:()=>Ye(K.pageNumber-1),onNext:()=>Ye(K.pageNumber+1),onLast:()=>Ye(K.pageCount)})]})]}),l.jsx(jyt,{sheetId:e.id,tab:G,onTabChange:Rt,document:n,selectedSection:Ae,inputSourceSection:ke,tableResultColumnCacheBySectionId:se,onSelectSection:wt,onUpdatePage:De,onUpdateSelectedSection:Bt,onDeleteSelectedSection:un,onUpdateHeader:Fe,onUpdateFooter:ot,onEditTableSection:Dt})]})}function jyt({sheetId:e,tab:t,onTabChange:n,document:r,selectedSection:o,inputSourceSection:s,tableResultColumnCacheBySectionId:i,onSelectSection:a,onUpdatePage:c,onUpdateSelectedSection:u,onDeleteSelectedSection:d,onUpdateHeader:f,onUpdateFooter:h,onEditTableSection:m,actions:g}){const b=[{id:"page",label:"Page"},{id:"header",label:"Header"},{id:"footer",label:"Footer"},{id:"inputs",label:"Inputs"}],x=p.useDashboardStore(S=>S.dashboard),y=v.useMemo(()=>{const S=rx(x,e);return S.length>0?S.map(lC):r.inputs||[]},[x,r.inputs,e]),w=t==="section"&&o!=null,C=t==="section"?"page":t,N=v.useMemo(()=>{if((o==null?void 0:o.type)!=="table")return[];const S=i[o.id];if(!S)return[];const j=wme(o);return S.schemaSignature===j?S.columns:[]},[o,i]);return l.jsxs("aside",{className:"flex w-[360px] shrink-0 flex-col border-l bg-background",children:[w?l.jsx(kyt,{section:o,onBack:()=>a(null),actions:g}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b px-3",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(Pm,{className:"h-3.5 w-3.5 text-muted-foreground"}),l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Document"})]}),g]}),l.jsx("div",{className:"flex shrink-0 items-center gap-3 overflow-x-auto border-b px-3",children:b.map(S=>l.jsx("button",{type:"button",onClick:()=>n(S.id),className:p.cn("-mb-px border-b-2 py-2 text-[12px] transition-colors",C===S.id?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:S.label},S.id))})]}),l.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:w?l.jsx(Iyt,{section:o,inputs:y,tableResultColumns:N,onUpdateSection:u,onEditTableSection:m}):C==="page"?l.jsx(Tyt,{page:r.page,onUpdatePage:c}):C==="header"?l.jsx(Fyt,{header:r.header,inputs:y,onUpdateHeader:f}):C==="footer"?l.jsx(Oyt,{footer:r.footer,inputs:y,onUpdateFooter:h}):C==="inputs"?l.jsx(Lyt,{sheetId:e,document:r,selectedSection:s,inputCount:y.length,onSelectSection:S=>a(S,{activateSectionInspector:!1}),onEditTableSection:m}):null})]})}function kyt({section:e,onBack:t,actions:n}){const r=pv(e.type);return l.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b px-2",children:[l.jsx("button",{type:"button",onClick:t,"aria-label":"Back to document",className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(zv,{className:"h-3.5 w-3.5"})}),l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l.jsx(r,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:sC[e.type]})]}),n]})}const _yt=[{value:"style",label:"Style"},{value:"columns",label:"Columns"},{value:"conditionalFormatting",label:"Conditional formatting"}];function Iyt({section:e,inputs:t,tableResultColumns:n=[],onUpdateSection:r,onEditTableSection:o}){var k,T,I,E,D,R,A,F,z;const[s,i]=v.useState("style");if(!e)return l.jsxs("div",{className:"flex flex-col items-center py-12 text-center",children:[l.jsx(Qs,{className:"mb-2 h-5 w-5 text-muted-foreground/50"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Select a section"})]});const a=L=>{r($=>$.type!=="text"?$:{...$,style:{...$.style,...L}})},c=L=>{r($=>{var G;if($.type!=="table")return $;const H=(G=$.card.preferences)==null?void 0:G.tablePrefs,{density:M,...B}=L,W={...H==null?void 0:H.tableStyle,...B},P=M??(H==null?void 0:H.density);return{...$,card:{...$.card,preferences:{...$.card.preferences,tablePrefs:{...H,...P?{density:P}:{},tableStyle:W}}},table:{...$.table,...M?{rowHeightPx:EF(M)}:{}}}})},u=L=>{r($=>{var B;if($.type!=="table")return $;const H=(B=$.card.preferences)==null?void 0:B.tablePrefs,M=H==null?void 0:H.tableStyle;return{...$,card:{...$.card,preferences:{...$.card.preferences,tablePrefs:{...H,tableStyle:{...M,totals:{...M==null?void 0:M.totals,...L}}}}}}})},d=()=>{r(L=>{var $;return L.type==="table"?{...L,table:{...L.table,repeatHeaderOnPageBreak:!0,rowHeightPx:EF($f.density)},card:{...L.card,preferences:{...L.card.preferences,tablePrefs:{...($=L.card.preferences)==null?void 0:$.tablePrefs,density:$f.density,tableStyle:{headerStyle:$f.headerStyle,headerWrapText:$f.headerWrapText,stripedRows:$f.stripedRows,gridLines:$f.gridLines,wrapText:$f.wrapText,totals:{enabled:zf.enabled,backgroundColor:zf.backgroundColor,textColor:zf.textColor,fontWeight:zf.fontWeight,borderTop:zf.borderTop,borderTopStyle:zf.borderTopStyle,borderTopColor:zf.borderTopColor}}}}}}:L})},f=L=>{r($=>{var W;if($.type!=="table")return $;const H=(W=$.card.preferences)==null?void 0:W.tablePrefs,M=H==null?void 0:H.tableStyle;return{...$,card:{...$.card,preferences:{...$.card.preferences,tablePrefs:{...H,tableStyle:{...M,totals:{...M==null?void 0:M.totals,enabled:L}}}}},table:{...$.table,totalsRow:L}}})},h=(L,$)=>{r(H=>{var B;if(H.type!=="table")return H;const M=(B=H.card.preferences)==null?void 0:B.tablePrefs;return{...H,card:{...H.card,preferences:{...H.card.preferences,tablePrefs:{...M,columnVisibility:ooe(M==null?void 0:M.columnVisibility,L,$)}}}}})},m=()=>{r(L=>{var H;if(L.type!=="table")return L;const $=(H=L.card.preferences)==null?void 0:H.tablePrefs;return{...L,card:{...L.card,preferences:{...L.card.preferences,tablePrefs:{...$,columnVisibility:void 0}}}}})},g=e.type==="table"?A5((T=(k=e.card.preferences)==null?void 0:k.tablePrefs)==null?void 0:T.conditionalFormatting):{rules:[]},b=e.type==="table"&&ppe(e.card.type),x=b?xpe(e.card,n):[],y=e.type==="table"&&e.card.type==="table"?ype(e.card,n):[],w=b&&x.length>0,C=e.type==="table"&&e.card.type==="table",N=_yt.filter(L=>L.value==="style"||L.value==="columns"&&C||L.value==="conditionalFormatting"&&w),S=N.some(L=>L.value===s)?s:"style",j=((I=x[0])==null?void 0:I.value)??la,_=L=>{r($=>$.type==="table"?{...$,card:qxt($.card,{version:1,rules:L})}:$)};return l.jsxs("div",{className:"space-y-4",children:[e.type==="text"&&l.jsxs(l.Fragment,{children:[l.jsx(Oo,{label:"Content",children:l.jsx(xv,{content:e.content,inputs:t,multiline:!0,onChange:L=>r($=>$.type==="text"?{...$,content:L}:$)})}),l.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[l.jsx(Oo,{label:"Size",children:l.jsxs(p.Select,{value:String(((E=e.style)==null?void 0:E.fontSize)||13),onValueChange:L=>a({fontSize:Number(L)}),children:[l.jsx(p.SelectTrigger,{size:"sm","aria-label":"Text size",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:[11,12,13,14,16,18,20,24].map(L=>l.jsxs(p.SelectItem,{value:String(L),children:[L,"px"]},L))})]})}),l.jsx(Oo,{label:"Weight",children:l.jsxs(p.Select,{value:((D=e.style)==null?void 0:D.fontWeight)||"normal",onValueChange:L=>a({fontWeight:L}),children:[l.jsx(p.SelectTrigger,{size:"sm","aria-label":"Text weight",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"normal",children:"Regular"}),l.jsx(p.SelectItem,{value:"medium",children:"Medium"}),l.jsx(p.SelectItem,{value:"semibold",children:"Semibold"}),l.jsx(p.SelectItem,{value:"bold",children:"Bold"})]})]})})]}),l.jsx(Oo,{label:"Alignment",children:l.jsx("div",{className:"inline-flex h-8 items-center rounded-md border bg-background p-0.5",children:["left","center","right"].map(L=>{var M;const $=L==="left"?fve:L==="center"?dve:hve,H=((M=e.style)==null?void 0:M.align)||"left";return l.jsx(p.Button,{type:"button",variant:H===L?"secondary":"ghost",size:"icon",className:"h-6 w-7","aria-label":`Align ${L}`,onClick:()=>a({align:L}),children:l.jsx($,{className:"h-3.5 w-3.5"})},L)})})}),l.jsx(Oo,{label:"Color",children:l.jsx(Ayt,{value:((R=e.style)==null?void 0:R.color)||"#27272a","aria-label":"Text color",onValueChange:L=>a({color:L})})})]}),e.type==="table"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"inline-flex h-8 items-center rounded-md border bg-background p-0.5",children:N.map(L=>l.jsx(p.Button,{type:"button",variant:S===L.value?"secondary":"ghost",size:"xs",className:"h-6 px-2 text-[11px]",onClick:()=>i(L.value),children:L.label},L.value))}),S==="style"?l.jsxs(l.Fragment,{children:[l.jsx(Oo,{label:"Title",children:l.jsx(p.Input,{size:"xs",value:e.title||e.card.title,onChange:L=>r($=>$.type==="table"?{...$,title:L.target.value,card:{...$.card,title:L.target.value}}:$)})}),l.jsx(mpe,{style:d4(e),onDensityChange:L=>c({density:L}),onStyleChange:c,showFullStyle:e.card.type==="table",totals:e.card.type==="table"&&!((A=e.card.sql)!=null&&A.trim())?{enabled:e.table.totalsRow===!0,onEnabledChange:f,onStyleChange:u}:void 0,onReset:e.card.type==="table"?d:void 0})]}):S==="columns"?l.jsx(fpe,{columns:y,columnVisibility:(z=(F=e.card.preferences)==null?void 0:F.tablePrefs)==null?void 0:z.columnVisibility,onColumnVisibilityChange:h,onShowAllColumns:m,emptyMessage:"Run the table query or add fields before hiding output columns."}):l.jsx(l.Fragment,{children:l.jsx(Npe,{columnId:j,availableColumns:x,conditionalRules:g.rules,onConditionalRulesChange:_,startRulesWithNoTrigger:!0})}),l.jsx("div",{className:"flex flex-col gap-1.5 pt-1",children:l.jsxs(p.Button,{type:"button",variant:"secondary",size:"xs",className:"w-full gap-1.5",onClick:()=>o(e),children:[l.jsx(p.Table2,{className:"h-3 w-3"}),"Edit table"]})})]}),e.type==="spacer"&&l.jsx(Oo,{label:"Height",children:l.jsx(y4,{"aria-label":"Spacer height",min:8,max:240,value:e.heightPx,onValueChange:L=>r($=>$.type==="spacer"?{...$,heightPx:L}:$)})})]})}function Tyt({page:e,onUpdatePage:t}){const n=(r,o)=>{t({...e,margins:{...e.margins,[r]:o}})};return l.jsxs("div",{className:"space-y-5",children:[l.jsx(Oo,{label:"Page size",children:l.jsxs(p.Select,{value:e.size,onValueChange:r=>t({...e,size:r}),children:[l.jsx(p.SelectTrigger,{"aria-label":"Page size",size:"sm",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"letter",children:"Letter"}),l.jsx(p.SelectItem,{value:"a4",children:"A4"})]})]})}),l.jsx(Oo,{label:"Orientation",children:l.jsxs(p.Select,{value:e.orientation,onValueChange:r=>t({...e,orientation:r}),children:[l.jsx(p.SelectTrigger,{"aria-label":"Orientation",size:"sm",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"portrait",children:"Portrait"}),l.jsx(p.SelectItem,{value:"landscape",children:"Landscape"})]})]})}),l.jsx(Oo,{label:"Margins",children:l.jsx("div",{className:"grid grid-cols-2 gap-2",children:["top","bottom","left","right"].map(r=>l.jsxs("label",{className:"block",children:[l.jsx("span",{className:"mb-1 block text-[10px] capitalize text-muted-foreground",children:r}),l.jsx(y4,{"aria-label":`${r} margin`,min:0,step:.125,value:e.margins[r],onValueChange:o=>n(r,o)})]},r))})})]})}function y4({value:e,onValueChange:t,min:n=0,max:r,step:o,disabled:s,"aria-label":i}){const[a,c]=v.useState(()=>String(e)),[u,d]=v.useState(!1);v.useEffect(()=>{u||c(String(e))},[u,e]);const f=v.useCallback((h,m=!1)=>{if(h.trim()===""){m&&c(String(e));return}const g=Number(h);if(!Number.isFinite(g)){m&&c(String(e));return}const b=m?Math.min(r??g,Math.max(n,g)):g;b<n||r!==void 0&&b>r||(t(b),m&&c(String(b)))},[r,n,t,e]);return l.jsx(p.Input,{"aria-label":i,size:"sm",type:"number",min:n,max:r,step:o,value:a,disabled:s,onFocus:()=>d(!0),onChange:h=>{c(h.target.value),f(h.target.value)},onBlur:()=>{d(!1),f(a,!0)}})}function Eyt({pageNumber:e,pageCount:t,onFirst:n,onPrevious:r,onNext:o,onLast:s}){return t<=1?null:l.jsxs("div",{className:"sticky bottom-4 z-20 mx-auto mt-[-44px] flex w-max items-center gap-1.5 rounded-full border border-zinc-200 bg-white/95 px-2.5 py-1 text-[13px] text-zinc-700 shadow-[0_8px_24px_rgba(0,0,0,0.14)] backdrop-blur",children:[l.jsx("button",{type:"button","aria-label":"First document page",disabled:e<=1,className:"inline-flex h-5 w-5 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-zinc-500",onClick:n,children:l.jsx(pZ,{className:"h-3.5 w-3.5"})}),l.jsx("button",{type:"button","aria-label":"Previous document page",disabled:e<=1,className:"inline-flex h-5 w-5 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-zinc-500",onClick:r,children:l.jsx(Mm,{className:"h-3.5 w-3.5"})}),l.jsxs("span",{className:"min-w-[44px] text-center text-[12px] tabular-nums",children:[e," / ",t]}),l.jsx("button",{type:"button","aria-label":"Next document page",disabled:e>=t,className:"inline-flex h-5 w-5 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-zinc-500",onClick:o,children:l.jsx(Ft.ChevronRight,{className:"h-3.5 w-3.5"})}),l.jsx("button",{type:"button","aria-label":"Last document page",disabled:e>=t,className:"inline-flex h-5 w-5 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-zinc-500",onClick:s,children:l.jsx(gZ,{className:"h-3.5 w-3.5"})})]})}const Dyt=["#ffffff","#fafafa","#f4f4f5","#e4e4e7","#a1a1aa","#52525b","#27272a","#0f172a","#eff6ff","#eef2ff","#ecfdf5","#fefce8"];function Myt(e){return e.startsWith("#")?e.toLowerCase():`#${e.toLowerCase()}`}function Ryt(e){return/^#[0-9a-fA-F]{6}$/.test(e)}function Ayt({value:e,onValueChange:t,"aria-label":n}){const[r,o]=v.useState(!1),[s,i]=v.useState(e.toUpperCase());v.useEffect(()=>{i(e.toUpperCase())},[e]);const a=v.useCallback(u=>{const d=Myt(u.trim());if(!Ryt(d)){i(e.toUpperCase());return}if(d===e.toLowerCase()){i(d.toUpperCase());return}t(d)},[t,e]),c=e.toLowerCase();return l.jsxs(p.Popover,{open:r,onOpenChange:o,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":n,className:"flex h-7 w-full items-center gap-2 rounded-[5px] border border-input bg-background px-1.5 text-[12px] text-foreground transition-colors hover:bg-muted/40 focus-visible:border-ring focus-visible:outline-none",children:[l.jsx("span",{"aria-hidden":"true",className:"h-4 w-4 shrink-0 rounded-[3px] border border-border/60",style:{backgroundColor:e}}),l.jsx("span",{className:"font-mono text-[11px] uppercase tracking-wide text-foreground",children:e.toUpperCase()}),l.jsx(Mm,{"aria-hidden":"true",className:"ml-auto h-3 w-3 shrink-0 -rotate-90 text-muted-foreground/60"})]})}),l.jsxs(p.PopoverContent,{align:"start",sideOffset:4,className:"w-[224px] space-y-2 p-2",onMouseDown:u=>u.stopPropagation(),children:[l.jsx("div",{role:"radiogroup","aria-label":"Color presets",className:"grid grid-cols-6 gap-1",children:Dyt.map(u=>{const d=u.toLowerCase()===c;return l.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-label":u,title:u.toUpperCase(),onClick:()=>{t(u),o(!1)},className:p.cn("relative flex h-7 w-7 items-center justify-center rounded-[4px] border border-border/60 transition-shadow",d&&"ring-1 ring-foreground ring-offset-1"),style:{backgroundColor:u},children:d&&l.jsx(p.Check,{"aria-hidden":"true",className:p.cn("h-3 w-3",Pyt(u)?"text-zinc-900":"text-white"),strokeWidth:3})},u)})}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("span",{"aria-hidden":"true",className:"text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:"Hex"}),l.jsx(p.Input,{size:"xs",value:s,onChange:u=>i(u.target.value.toUpperCase()),onBlur:u=>a(u.currentTarget.value),onKeyDown:u=>{u.key==="Enter"?u.currentTarget.blur():u.key==="Escape"&&(i(e.toUpperCase()),u.currentTarget.blur())},className:"font-mono text-[11px]"}),l.jsxs("label",{className:"relative inline-flex h-7 w-7 shrink-0 cursor-pointer items-center justify-center rounded-[4px] border border-border/60 bg-background hover:bg-muted/60",title:"Custom color",children:[l.jsx("span",{"aria-hidden":"true",className:"absolute inset-1 rounded-[3px]",style:{backgroundImage:"conic-gradient(from 0deg, #ef4444, #f59e0b, #84cc16, #06b6d4, #6366f1, #ec4899, #ef4444)"}}),l.jsx("input",{"aria-label":`${n??"Color"} (custom)`,type:"color",value:e,onChange:u=>t(u.target.value),className:"absolute inset-0 h-full w-full cursor-pointer opacity-0"})]})]})]})]})}function Pyt(e){const t=e.replace("#","");if(t.length!==6)return!0;const n=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),o=parseInt(t.slice(4,6),16);return .2126*n+.7152*r+.0722*o>150}function Fyt({header:e,inputs:t,onUpdateHeader:n}){const r=e?p.getRegionImageBlock(e.blocks,"logo"):void 0,o=e?p.getRegionTextBlock(e.blocks,"title"):void 0,s=e?p.getRegionTextBlock(e.blocks,"metadata"):void 0,i=(r==null?void 0:r.area)==="center"||(r==null?void 0:r.area)==="right"?r.area:"left",a=(u,d,f)=>{n(h=>{const m=h||p.createHeaderRegion();return{...m,enabled:!0,blocks:p.upsertTextRegionBlock(m.blocks,{id:`header_${u}`,role:u,area:d,content:f})}})},c=u=>{n(d=>{const f=d||p.createHeaderRegion(),h=p.getRegionImageBlock(f.blocks,"logo");return{...f,enabled:!0,blocks:p.upsertImageRegionBlock(f.blocks,{id:"header_logo",type:"image",role:"logo",area:"left",src:"",alt:"Logo",widthPx:120,...h,...u})}})};return e?l.jsxs("div",{className:"space-y-4",children:[l.jsx(dpe,{label:"Enabled",enabled:!!(e!=null&&e.enabled),onToggle:u=>n(d=>Ipe(d,p.createHeaderRegion,u))}),l.jsx(Oo,{label:"Logo URL",children:l.jsx(p.Input,{"aria-label":"Logo URL",size:"sm",value:(r==null?void 0:r.src)||"",disabled:!(e!=null&&e.enabled),onChange:u=>c({src:u.target.value})})}),l.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_5rem] gap-2",children:[l.jsx(Oo,{label:"Logo placement",children:l.jsxs(p.Select,{value:i,disabled:!(e!=null&&e.enabled),onValueChange:u=>c({area:u}),children:[l.jsx(p.SelectTrigger,{"aria-label":"Logo placement",size:"sm",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"left",children:"Left"}),l.jsx(p.SelectItem,{value:"center",children:"Center"}),l.jsx(p.SelectItem,{value:"right",children:"Right"})]})]})}),l.jsx(Oo,{label:"Width",children:l.jsx(y4,{"aria-label":"Logo width",min:24,max:320,step:4,value:(r==null?void 0:r.widthPx)||120,disabled:!(e!=null&&e.enabled),onValueChange:u=>c({widthPx:u})})})]}),l.jsx(Oo,{label:"Logo alt text",children:l.jsx(p.Input,{"aria-label":"Logo alt text",size:"sm",value:(r==null?void 0:r.alt)||"",disabled:!(e!=null&&e.enabled),onChange:u=>c({alt:u.target.value})})}),l.jsx(Oo,{label:"Title",children:l.jsx(xv,{content:o==null?void 0:o.content,inputs:t,disabled:!(e!=null&&e.enabled),onChange:u=>a("title","title",u)})}),l.jsx(Oo,{label:"Metadata",children:l.jsx(xv,{content:s==null?void 0:s.content,inputs:t,disabled:!(e!=null&&e.enabled),onChange:u=>a("metadata","metadata",u)})})]}):l.jsx(_pe,{title:"No header",description:"Logo, title, and metadata.",actionLabel:"Add header",onAdd:()=>n(()=>p.createHeaderRegion())})}function Oyt({footer:e,inputs:t,onUpdateFooter:n}){const r=e?p.getRegionTextBlock(e.blocks,"note"):void 0,o=e?p.getRegionTextBlock(e.blocks,"pageInfo"):void 0,s=(i,a,c)=>{n(u=>{const d=u||p.createFooterRegion();return{...d,enabled:!0,blocks:p.upsertTextRegionBlock(d.blocks,{id:`footer_${i}`,role:i,area:a,content:c})}})};return e?l.jsxs("div",{className:"space-y-4",children:[l.jsx(dpe,{label:"Enabled",enabled:!!(e!=null&&e.enabled),onToggle:i=>n(a=>Ipe(a,p.createFooterRegion,i))}),l.jsx(Oo,{label:"Note",children:l.jsx(xv,{content:r==null?void 0:r.content,inputs:t,disabled:!(e!=null&&e.enabled),onChange:i=>s("note","note",i)})}),l.jsx(Oo,{label:"Page info",children:l.jsx(xv,{content:o==null?void 0:o.content,inputs:t,disabled:!(e!=null&&e.enabled),onChange:i=>s("pageInfo","pageInfo",i)})})]}):l.jsx(_pe,{title:"No footer",description:"Note and page info.",actionLabel:"Add footer",onAdd:()=>n(()=>Wyt())})}function _pe({title:e,description:t,actionLabel:n,onAdd:r}){return l.jsxs("div",{className:"rounded border border-dashed border-border bg-muted/20 p-4",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-[13px] font-medium text-foreground",children:e}),l.jsx("p",{className:"text-[12px] leading-4 text-muted-foreground",children:t})]}),l.jsx(p.Button,{type:"button",size:"sm",variant:"outline",className:"mt-4 h-8 w-full justify-center text-[12px]",onClick:r,children:n})]})}function Lyt({sheetId:e,document:t,selectedSection:n,inputCount:r,onSelectSection:o,onEditTableSection:s}){const i=p.useDashboardStore(w=>w.dashboard),{upsertDashboardInput:a,removeDashboardInput:c,updateSheetDocument:u}=p.useDashboardActions(),d=(n==null?void 0:n.type)==="table"?n:null,f=v.useMemo(()=>rx(i,e),[i,e]),h=v.useMemo(()=>f.map(lC),[f]),m=t.sections.filter(w=>w.type==="table"),g=v.useCallback(w=>{var S,j;const C=d==null?void 0:d.card;if(!C||f.some(_=>pyt(_,w)))return;const N=fyt({field:w,existingInputs:i.inputs||[],sheetId:e,dataSource:C.dataSource,connectionId:((S=C.dataSource)==null?void 0:S.connectionId)||C.connectionId,connectionType:(j=C.dataSource)==null?void 0:j.connectionType});a(N)},[i.inputs,f,d==null?void 0:d.card,e,a]),b=v.useCallback(w=>{c(w)},[c]),x=v.useCallback((w,C)=>{const N=f.find(S=>S.id===w);N&&a({...N,requiredAtExecution:C,...N.kind==="control"?{control:{...N.control,requiredAtExecution:C}}:{}})},[f,a]),y=v.useCallback((w,C)=>{const N=f.find(j=>j.id===w);if(!N)return;const S=AF({input:N,allInputs:i.inputs||[],...C});a(S),N.kind==="control"&&S.kind==="control"&&N.control.id!==S.control.id&&u(e,j=>PF(j,N.control.id,S.control.id))},[i.inputs,f,e,u,a]);return l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("h3",{className:"text-[12px] font-medium text-foreground",children:"Document inputs"}),l.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground",children:r})]}),l.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Add document-wide filter inputs from the selected table fields."})]}),l.jsx($yt,{selectedTableSection:d,tableSections:m,inputs:h,onSelectTable:o,onEditTableSection:s,onAddField:g}),l.jsx(Byt,{inputs:h,onUpdateMetadata:y,onRemove:b,onSetRequired:x})]})}function $yt({selectedTableSection:e,tableSections:t,inputs:n,onSelectTable:r,onEditTableSection:o,onAddField:s}){return t.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border bg-muted/20 px-4 py-6 text-center",children:[l.jsx(Qs,{className:"mb-2 h-5 w-5 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-1 text-[12px] font-medium text-foreground",children:"No table sections"}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add a document table before creating filter inputs."})]}):e?e.card?l.jsx(zyt,{section:e,inputs:n,onAddField:s}):l.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3 text-[12px] text-muted-foreground",children:[l.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[l.jsx(ss,{className:"h-3.5 w-3.5"}),l.jsx("span",{className:"font-medium",children:"Configure this table"})]}),l.jsx("p",{children:"Choose a data source before adding document inputs."}),l.jsxs(p.Button,{type:"button",variant:"secondary",size:"sm",className:"h-8 w-full gap-2",onClick:()=>o(e),children:[l.jsx(p.Table2,{className:"h-3.5 w-3.5"}),"Configure table"]})]}):l.jsxs("div",{className:"rounded-md border bg-background",children:[l.jsx("div",{className:"border-b px-2.5 py-2 text-[11px] font-medium text-muted-foreground",children:"Choose a table section"}),l.jsx("div",{className:"space-y-1 p-1.5",children:t.map(i=>{var a;return l.jsxs(p.Button,{type:"button",variant:"ghost",size:"sm",className:"h-8 w-full justify-start gap-2 px-2 text-xs",onClick:()=>r(i.id),children:[l.jsx(p.Table2,{className:"h-3.5 w-3.5"}),i.title||((a=i.card)==null?void 0:a.title)||"Table"]},i.id)})})]})}function zyt({section:e,inputs:t,onAddField:n}){var i,a;const r=p.useEditorStore(c=>{var u;return(u=c.card)==null?void 0:u.id}),{setCard:o}=p.useEditorActions(),s=v.useMemo(()=>t.filter(cc).map(c=>({id:c.filter.id,column:c.filter.column,title:c.filter.title,dataType:c.filter.dataType,table:c.filter.table||"",database:c.filter.database||"",qualifiedTableName:c.filter.qualifiedTableName,connectionId:c.filter.connectionId,operation:c.filter.operation,sql:c.filter.sql,fieldMeta:c.filter.fieldMeta,semanticContext:c.filter.semanticContext})),[t]);return v.useEffect(()=>{e.card&&o(e.card)},[e.card,o]),r!==((i=e.card)==null?void 0:i.id)?l.jsx("div",{className:"rounded border border-dashed p-4 text-[12px] text-muted-foreground",children:"Loading fields..."}):l.jsxs("div",{className:"flex flex-col overflow-hidden rounded-md border bg-background",children:[l.jsxs("div",{className:"border-b px-2.5 py-2 text-[12px] text-muted-foreground",children:["Fields from"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.title||((a=e.card)==null?void 0:a.title)||"this table"})]}),l.jsx(mme,{className:"h-[300px]",context:"document-filter",inlineFilters:s,onFieldSelect:n})]})}function Byt({inputs:e,onUpdateMetadata:t,onRemove:n,onSetRequired:r}){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:"Active inputs"}),e.length>0?l.jsx("span",{className:"rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground",children:e.length}):null]}),e.length===0?l.jsx("div",{className:"rounded-md border bg-muted/20 px-3 py-2 text-[11px] text-muted-foreground",children:"No document inputs yet."}):l.jsx("div",{className:"space-y-1",children:e.map(o=>l.jsx(Vyt,{input:o,onUpdateMetadata:s=>t(o.id,s),onRemove:()=>n(o.id),onSetRequired:s=>r(o.id,s)},o.id))})]})}function Vyt({input:e,onUpdateMetadata:t,onSetRequired:n,onRemove:r}){const[o,s]=v.useState(e.label);v.useEffect(()=>{s(e.label)},[e.id,e.label]);const i=v.useCallback(()=>{const c=o.trim();if(!c){s(e.label);return}c!==e.label&&t({label:c})},[e.label,o,t]),a=c=>{c.key==="Enter"&&(c.preventDefault(),c.currentTarget.blur())};return l.jsxs("div",{className:"rounded-md border bg-background px-2.5 py-2",children:[l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[l.jsx(p.Input,{size:"xs",className:"h-6 min-w-0 border-0 bg-transparent px-0 py-0 text-[12px] font-medium shadow-none focus-visible:ring-0",value:o,onChange:c=>s(c.target.value),onBlur:i,onKeyDown:a,"aria-label":`${e.label} input label`}),l.jsx("span",{className:"shrink-0 rounded bg-muted px-1.5 py-0.5 text-[9px] font-medium uppercase text-muted-foreground",children:e.kind==="control"?"Control":"Filter"})]}),l.jsx(p.Input,{size:"xs",className:"h-6 min-w-0 rounded border bg-muted/20 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground shadow-none focus-visible:ring-0",value:`{{${e.variableName}}}`,readOnly:!0,"aria-label":`${e.label} input token`})]}),l.jsx("div",{className:"flex shrink-0 items-center gap-1",children:l.jsx(p.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 hover:bg-destructive/10 hover:text-destructive",onClick:r,"aria-label":`Remove ${e.label} document input`,children:l.jsx(el,{className:"h-3 w-3"})})})]}),l.jsxs("label",{className:"mt-2 flex items-center justify-between gap-2 border-t pt-1.5 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:"Required"}),l.jsx(p.Switch,{size:"xs",checked:e.requiredAtExecution,onCheckedChange:n,"aria-label":`Required ${e.label}`})]})]})}function Hyt(e,t,n,r){return{...e,inputs:(e.inputs||[]).map(o=>{if(o.id!==t||!cc(o))return o;const s={...o.filter,...n};return{...o,label:s.title||o.label,variableName:(r==null?void 0:r.variableName)||o.variableName,filter:s,exports:jT(s)}})}}function qyt(e,t,n){return{...e,inputs:(e.inputs||[]).map(r=>r.id!==t||!Ql(r)?r:{...r,label:n.label||r.label,requiredAtExecution:n.requiredAtExecution,control:n})}}function Uyt(e,t){return e.reduce((n,r)=>{if(!cc(r))return n;const o=t[r.id];return o&&vT(o.operation)&&(n[r.id]=kme(o.operation)),n},{})}function Ipe(e,t,n){return e?{...e,enabled:n}:n?t():void 0}function Wyt(){const e=p.createFooterRegion();return{...e,blocks:p.upsertTextRegionBlock(e.blocks,{id:"footer_pageInfo",role:"pageInfo",area:"pageInfo",content:[{type:"text",value:"Page "},{type:"variable",ref:{source:"documentMeta",key:"pageNumber"}},{type:"text",value:" of "},{type:"variable",ref:{source:"documentMeta",key:"pageCount"}}]})}}function Kyt(e,t){return e.length!==t.length?!1:e.every((n,r)=>{var o,s;return n.value===((o=t[r])==null?void 0:o.value)&&n.label===((s=t[r])==null?void 0:s.label)})}const Vf=[50,75,100,125,150],v2="inline-flex h-full items-center gap-1.5 rounded-none border-0 bg-transparent px-2 text-[12px] transition-colors";function MK({children:e}){return l.jsx("div",{className:"inline-flex h-7 shrink-0 items-center overflow-hidden rounded-[5px] border border-border bg-background text-foreground",children:e})}function w2(){return l.jsx("span",{"aria-hidden":"true",className:"h-full w-px bg-border"})}function Gyt({zoom:e,onZoomChange:t}){const n=Vf.indexOf(e),r=n>0,o=n>=0&&n<Vf.length-1;return l.jsxs("div",{className:"inline-flex h-full items-center gap-0.5 bg-transparent px-1",children:[l.jsx("button",{type:"button",disabled:!r,onClick:()=>{const s=Vf.indexOf(e);s>0&&t(Vf[s-1])},"aria-label":"Zoom out",className:"inline-flex h-5 w-5 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-muted-foreground",children:l.jsx($c,{className:"h-3 w-3"})}),l.jsxs("span",{className:"min-w-[34px] px-1 text-center text-[11px] tabular-nums text-foreground",children:[e,"%"]}),l.jsx("button",{type:"button",disabled:!o,onClick:()=>{const s=Vf.indexOf(e);s>=0&&s<Vf.length-1&&t(Vf[s+1])},"aria-label":"Zoom in",className:"inline-flex h-5 w-5 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-muted-foreground",children:l.jsx(Tr,{className:"h-3 w-3"})})]})}const Yyt=f6.WidthProvider(f6.Responsive),Zyt=["input","textarea","select","button","a",'[role="button"]','[role="menuitem"]','[contenteditable="true"]',"[data-rgl-drag-cancel]",".data-table-scroll-container"].join(", ");function C2(e){if(!e)return null;let t=!1;const n={};for(const[r,o]of Object.entries(e))n[r]=o.map(s=>{const i=Number(s.w),a=Number(s.h);if(i===1&&a===1)return s;const c=s.minH!==void 0&&s.minH!==null,u=Number(s.minH),d=c&&Number.isFinite(u)?Math.max(1,u):void 0,f=Number.isFinite(a)?Math.max(1,a):1,h=d!==void 0?Math.max(d,f):f;if((h!==s.h||d!==s.minH)&&(t=!0),d===void 0){const{minH:m,...g}=s;return{...g,h}}return{...s,h,minH:d}});return t?n:null}function Xyt(){const{open:e}=K5();return e?l.jsx(pht,{}):null}function RK({sheet:e}){return e.kind==="document"?l.jsx(Nyt,{sheet:e}):l.jsx(Qyt,{sheet:e})}function Qyt({sheet:e}){var A,F;const t=p.useDashboardStore(z=>z.isDashboardEditing),n=p.useDashboardStore(z=>z.currentBreakpoint),r=p.useDashboardStore(z=>z.themeStyle),o=Ru(),s=v.useRef(0),i=v.useRef(!1),a=v.useRef(null),c=p.useDashboardStore(z=>z.selectedSheetId),u=e.layouts,d=v.useMemo(()=>C2(u),[u]),f=d||u,[h,m]=v.useState(f),g=v.useRef(f),b=e.frames,{setSheetLayouts:x,setCurrentBreakpoint:y}=p.useDashboardStore(z=>z.actions);v.useEffect(()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},[e.id]),v.useEffect(()=>{i.current||jF(g.current,f)&&(g.current=f,m(f))},[f]),v.useEffect(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);function w(z){y(z)}const C=z=>{g.current=z,m(z)},N=z=>{a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{a.current=null,v.startTransition(()=>{x(e.id,z)})},0)};function S(z,L){if(!i.current){C2(L);const $=ght(u,d);c===e.id&&$&&(C($),N($));return}}const j=()=>{i.current=!0},_=z=>{if(z&&c===e.id){const L={...g.current||f||{},[n]:z},H=C2(L)||L;C(H),jF(u,H)&&N(H)}i.current=!1};if(!c)return null;const k=(z,L)=>l.jsx(Tpe,{className:"after:content-none",ref:L,handleAxis:z});function T(){return b==null?void 0:b.map(z=>l.jsx("div",{role:"dashboard-frame-container",className:p.cn("group isolate overflow-hidden",r==null?void 0:r.dashboardCardContainer),children:l.jsx(Si,{FallbackComponent:({error:L,resetErrorBoundary:$})=>l.jsx(ZJe,{error:L,resetErrorBoundary:$,frame:z}),children:l.jsx(iut,{frame:z})})},z.id))}const I=((A=r==null?void 0:r.gridLayout)==null?void 0:A.margin)??[10,10],E=o.gridMargin??I,D=o.gridContainerPadding??(o.gridMargin?I:void 0),R={...(r==null?void 0:r.cardBorderRadius)!==void 0?{"--placeholder-border-radius":`${r.cardBorderRadius}px`}:{},...o.gridStyle};return!b||b.length===0?l.jsx(fut,{sheetId:e.id}):l.jsxs(ATe,{children:[l.jsx(Yyt,{margin:E,containerPadding:D,isDraggable:t,draggableCancel:t?Zyt:void 0,resizeHandles:t?["s","w","e","n","sw","nw","se","ne"]:[],className:p.cn((F=r==null?void 0:r.gridLayout)==null?void 0:F.className),style:R,layouts:h,cols:{lg:48,md:36,sm:24,xs:12,xxs:6},rowHeight:1,onBreakpointChange:w,onLayoutChange:S,onDragStart:j,onDragStop:z=>_(z),onResizeStart:j,onResize:(z,L,$,H,M,B)=>{const W=Date.now();W-s.current>100&&(B.scrollIntoView({behavior:"auto",block:"nearest"}),s.current=W)},onResizeStop:(z,L,$,H,M,B)=>{B.scrollIntoView({behavior:"smooth",block:"nearest"}),_(z)},resizeHandle:k,children:T()}),l.jsx(Xyt,{})]})}const Tpe=v.forwardRef(({className:e,handleAxis:t,...n},r)=>{const o=p.useDashboardStore(s=>s.themeStyle);return o!=null&&o.cardBorderRadius,l.jsx("div",{ref:r,className:p.cn(`react-resizable-handle z-20 react-resizable-handle-${t} absolute border-foreground/40`,{"z-30 h-4 w-4":["sw","nw","se","ne"].includes(t),"bottom-0 left-0 cursor-sw-resize":t==="sw","left-0 top-0 cursor-nw-resize":t==="nw","bottom-0 right-0 cursor-se-resize":t==="se","right-0 top-0 cursor-ne-resize":t==="ne","!bottom-0 !left-0 !right-0 !h-2 !w-full cursor-ns-resize":t==="s","!left-0 !right-0 !top-0 !h-2 !w-full cursor-ns-resize":t==="n","!bottom-0 !right-0 !top-0 !h-full !w-2 cursor-ew-resize":t==="e","!bottom-0 !left-0 !top-0 !h-full !w-2 cursor-ew-resize":t==="w"},e),...n})});Tpe.displayName="ResizeHandle";const kT=v.createContext(null);kT.displayName="PanelGroupContext";const Jr={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},v4=10,Yh=v.useLayoutEffect,AK=te.useId,Jyt=typeof AK=="function"?AK:()=>null;let e0t=0;function w4(e=null){const t=Jyt(),n=v.useRef(e||t||null);return n.current===null&&(n.current=""+e0t++),e??n.current}function Epe({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:o,forwardedRef:s,id:i,maxSize:a,minSize:c,onCollapse:u,onExpand:d,onResize:f,order:h,style:m,tagName:g="div",...b}){const x=v.useContext(kT);if(x===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:y,expandPanel:w,getPanelSize:C,getPanelStyle:N,groupId:S,isPanelCollapsed:j,reevaluatePanelConstraints:_,registerPanel:k,resizePanel:T,unregisterPanel:I}=x,E=w4(i),D=v.useRef({callbacks:{onCollapse:u,onExpand:d,onResize:f},constraints:{collapsedSize:n,collapsible:r,defaultSize:o,maxSize:a,minSize:c},id:E,idIsFromProps:i!==void 0,order:h});v.useRef({didLogMissingDefaultSizeWarning:!1}),Yh(()=>{const{callbacks:A,constraints:F}=D.current,z={...F};D.current.id=E,D.current.idIsFromProps=i!==void 0,D.current.order=h,A.onCollapse=u,A.onExpand=d,A.onResize=f,F.collapsedSize=n,F.collapsible=r,F.defaultSize=o,F.maxSize=a,F.minSize=c,(z.collapsedSize!==F.collapsedSize||z.collapsible!==F.collapsible||z.maxSize!==F.maxSize||z.minSize!==F.minSize)&&_(D.current,z)}),Yh(()=>{const A=D.current;return k(A),()=>{I(A)}},[h,E,k,I]),v.useImperativeHandle(s,()=>({collapse:()=>{y(D.current)},expand:A=>{w(D.current,A)},getId(){return E},getSize(){return C(D.current)},isCollapsed(){return j(D.current)},isExpanded(){return!j(D.current)},resize:A=>{T(D.current,A)}}),[y,w,C,j,E,T]);const R=N(D.current,o);return v.createElement(g,{...b,children:e,className:t,id:E,style:{...R,...m},[Jr.groupId]:S,[Jr.panel]:"",[Jr.panelCollapsible]:r||void 0,[Jr.panelId]:E,[Jr.panelSize]:parseFloat(""+R.flexGrow).toFixed(1)})}const Dpe=v.forwardRef((e,t)=>v.createElement(Epe,{...e,forwardedRef:t}));Epe.displayName="Panel";Dpe.displayName="forwardRef(Panel)";let FF=null,eN=-1,sd=null;function t0t(e,t){if(t){const n=(t&Fpe)!==0,r=(t&Ope)!==0,o=(t&Lpe)!==0,s=(t&$pe)!==0;if(n)return o?"se-resize":s?"ne-resize":"e-resize";if(r)return o?"sw-resize":s?"nw-resize":"w-resize";if(o)return"s-resize";if(s)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function n0t(){sd!==null&&(document.head.removeChild(sd),FF=null,sd=null,eN=-1)}function S2(e,t){var n,r;const o=t0t(e,t);if(FF!==o){if(FF=o,sd===null&&(sd=document.createElement("style"),document.head.appendChild(sd)),eN>=0){var s;(s=sd.sheet)===null||s===void 0||s.removeRule(eN)}eN=(n=(r=sd.sheet)===null||r===void 0?void 0:r.insertRule(`*{cursor: ${o} !important;}`))!==null&&n!==void 0?n:-1}}function Mpe(e){return e.type==="keydown"}function Rpe(e){return e.type.startsWith("pointer")}function Ape(e){return e.type.startsWith("mouse")}function _T(e){if(Rpe(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(Ape(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function r0t(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function o0t(e,t,n){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function s0t(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:OK(e),b:OK(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;Nn(r,"Stacking order can only be calculated for elements with a common ancestor");const o={a:FK(PK(n.a)),b:FK(PK(n.b))};if(o.a===o.b){const s=r.childNodes,i={a:n.a.at(-1),b:n.b.at(-1)};let a=s.length;for(;a--;){const c=s[a];if(c===i.a)return 1;if(c===i.b)return-1}}return Math.sign(o.a-o.b)}const i0t=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function a0t(e){var t;const n=getComputedStyle((t=Ppe(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function l0t(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||a0t(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||i0t.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function PK(e){let t=e.length;for(;t--;){const n=e[t];if(Nn(n,"Missing node"),l0t(n))return n}return null}function FK(e){return e&&Number(getComputedStyle(e).zIndex)||0}function OK(e){const t=[];for(;e;)t.push(e),e=Ppe(e);return t}function Ppe(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const Fpe=1,Ope=2,Lpe=4,$pe=8,c0t=r0t()==="coarse";let Ja=[],fg=!1,ah=new Map,IT=new Map;const yv=new Set;function u0t(e,t,n,r,o){var s;const{ownerDocument:i}=t,a={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:o},c=(s=ah.get(i))!==null&&s!==void 0?s:0;return ah.set(i,c+1),yv.add(a),hk(),function(){var d;IT.delete(e),yv.delete(a);const f=(d=ah.get(i))!==null&&d!==void 0?d:1;if(ah.set(i,f-1),hk(),f===1&&ah.delete(i),Ja.includes(a)){const h=Ja.indexOf(a);h>=0&&Ja.splice(h,1),S4(),o("up",!0,null)}}}function d0t(e){const{target:t}=e,{x:n,y:r}=_T(e);fg=!0,C4({target:t,x:n,y:r}),hk(),Ja.length>0&&(mk("down",e),e.preventDefault(),zpe(t)||e.stopImmediatePropagation())}function N2(e){const{x:t,y:n}=_T(e);if(fg&&e.buttons===0&&(fg=!1,mk("up",e)),!fg){const{target:r}=e;C4({target:r,x:t,y:n})}mk("move",e),S4(),Ja.length>0&&e.preventDefault()}function j2(e){const{target:t}=e,{x:n,y:r}=_T(e);IT.clear(),fg=!1,Ja.length>0&&(e.preventDefault(),zpe(t)||e.stopImmediatePropagation()),mk("up",e),C4({target:t,x:n,y:r}),S4(),hk()}function zpe(e){let t=e;for(;t;){if(t.hasAttribute(Jr.resizeHandle))return!0;t=t.parentElement}return!1}function C4({target:e,x:t,y:n}){Ja.splice(0);let r=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(r=e),yv.forEach(o=>{const{element:s,hitAreaMargins:i}=o,a=s.getBoundingClientRect(),{bottom:c,left:u,right:d,top:f}=a,h=c0t?i.coarse:i.fine;if(t>=u-h&&t<=d+h&&n>=f-h&&n<=c+h){if(r!==null&&document.contains(r)&&s!==r&&!s.contains(r)&&!r.contains(s)&&s0t(r,s)>0){let g=r,b=!1;for(;g&&!g.contains(s);){if(o0t(g.getBoundingClientRect(),a)){b=!0;break}g=g.parentElement}if(b)return}Ja.push(o)}})}function k2(e,t){IT.set(e,t)}function S4(){let e=!1,t=!1;Ja.forEach(r=>{const{direction:o}=r;o==="horizontal"?e=!0:t=!0});let n=0;IT.forEach(r=>{n|=r}),e&&t?S2("intersection",n):e?S2("horizontal",n):t?S2("vertical",n):n0t()}let _2=new AbortController;function hk(){_2.abort(),_2=new AbortController;const e={capture:!0,signal:_2.signal};yv.size&&(fg?(Ja.length>0&&ah.forEach((t,n)=>{const{body:r}=n;t>0&&(r.addEventListener("contextmenu",j2,e),r.addEventListener("pointerleave",N2,e),r.addEventListener("pointermove",N2,e))}),window.addEventListener("pointerup",j2,e),window.addEventListener("pointercancel",j2,e)):ah.forEach((t,n)=>{const{body:r}=n;t>0&&(r.addEventListener("pointerdown",d0t,e),r.addEventListener("pointermove",N2,e))}))}function mk(e,t){yv.forEach(n=>{const{setResizeHandlerState:r}=n,o=Ja.includes(n);r(e,o,t)})}function f0t(){const[e,t]=v.useState(0);return v.useCallback(()=>t(n=>n+1),[])}function Nn(e,t){if(!e)throw console.error(t),Error(t)}function Tm(e,t,n=v4){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function Hc(e,t,n=v4){return Tm(e,t,n)===0}function Pi(e,t,n){return Tm(e,t,n)===0}function h0t(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){const o=e[r],s=t[r];if(!Pi(o,s,n))return!1}return!0}function Jp({panelConstraints:e,panelIndex:t,size:n}){const r=e[t];Nn(r!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:o=0,collapsible:s,maxSize:i=100,minSize:a=0}=r;if(Tm(n,a)<0)if(s){const c=(o+a)/2;Tm(n,c)<0?n=o:n=a}else n=a;return n=Math.min(i,n),n=parseFloat(n.toFixed(v4)),n}function Cy({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:o,trigger:s}){if(Pi(e,0))return t;const i=[...t],[a,c]=r;Nn(a!=null,"Invalid first pivot index"),Nn(c!=null,"Invalid second pivot index");let u=0;if(s==="keyboard"){{const f=e<0?c:a,h=n[f];Nn(h,`Panel constraints not found for index ${f}`);const{collapsedSize:m=0,collapsible:g,minSize:b=0}=h;if(g){const x=t[f];if(Nn(x!=null,`Previous layout not found for panel index ${f}`),Pi(x,m)){const y=b-x;Tm(y,Math.abs(e))>0&&(e=e<0?0-y:y)}}}{const f=e<0?a:c,h=n[f];Nn(h,`No panel constraints found for index ${f}`);const{collapsedSize:m=0,collapsible:g,minSize:b=0}=h;if(g){const x=t[f];if(Nn(x!=null,`Previous layout not found for panel index ${f}`),Pi(x,b)){const y=x-m;Tm(y,Math.abs(e))>0&&(e=e<0?0-y:y)}}}}{const f=e<0?1:-1;let h=e<0?c:a,m=0;for(;;){const b=t[h];Nn(b!=null,`Previous layout not found for panel index ${h}`);const y=Jp({panelConstraints:n,panelIndex:h,size:100})-b;if(m+=y,h+=f,h<0||h>=n.length)break}const g=Math.min(Math.abs(e),Math.abs(m));e=e<0?0-g:g}{let h=e<0?a:c;for(;h>=0&&h<n.length;){const m=Math.abs(e)-Math.abs(u),g=t[h];Nn(g!=null,`Previous layout not found for panel index ${h}`);const b=g-m,x=Jp({panelConstraints:n,panelIndex:h,size:b});if(!Pi(g,x)&&(u+=g-x,i[h]=x,u.toPrecision(3).localeCompare(Math.abs(e).toPrecision(3),void 0,{numeric:!0})>=0))break;e<0?h--:h++}}if(h0t(o,i))return o;{const f=e<0?c:a,h=t[f];Nn(h!=null,`Previous layout not found for panel index ${f}`);const m=h+u,g=Jp({panelConstraints:n,panelIndex:f,size:m});if(i[f]=g,!Pi(g,m)){let b=m-g,y=e<0?c:a;for(;y>=0&&y<n.length;){const w=i[y];Nn(w!=null,`Previous layout not found for panel index ${y}`);const C=w+b,N=Jp({panelConstraints:n,panelIndex:y,size:C});if(Pi(w,N)||(b-=N-w,i[y]=N),Pi(b,0))break;e>0?y--:y++}}}const d=i.reduce((f,h)=>h+f,0);return Pi(d,100)?i:o}function m0t({layout:e,panelsArray:t,pivotIndices:n}){let r=0,o=100,s=0,i=0;const a=n[0];Nn(a!=null,"No pivot index found"),t.forEach((f,h)=>{const{constraints:m}=f,{maxSize:g=100,minSize:b=0}=m;h===a?(r=b,o=g):(s+=b,i+=g)});const c=Math.min(o,100-s),u=Math.max(r,100-i),d=e[a];return{valueMax:c,valueMin:u,valueNow:d}}function vv(e,t=document){return Array.from(t.querySelectorAll(`[${Jr.resizeHandleId}][data-panel-group-id="${e}"]`))}function Bpe(e,t,n=document){const o=vv(e,n).findIndex(s=>s.getAttribute(Jr.resizeHandleId)===t);return o??null}function Vpe(e,t,n){const r=Bpe(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function Hpe(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function TT(e,t=document){const n=t.querySelector(`[${Jr.resizeHandleId}="${e}"]`);return n||null}function p0t(e,t,n,r=document){var o,s,i,a;const c=TT(t,r),u=vv(e,r),d=c?u.indexOf(c):-1,f=(o=(s=n[d])===null||s===void 0?void 0:s.id)!==null&&o!==void 0?o:null,h=(i=(a=n[d+1])===null||a===void 0?void 0:a.id)!==null&&i!==void 0?i:null;return[f,h]}function g0t({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:o,panelGroupElement:s,setLayout:i}){v.useRef({didWarnAboutMissingResizeHandle:!1}),Yh(()=>{if(!s)return;const a=vv(n,s);for(let c=0;c<o.length-1;c++){const{valueMax:u,valueMin:d,valueNow:f}=m0t({layout:r,panelsArray:o,pivotIndices:[c,c+1]}),h=a[c];if(h!=null){const m=o[c];Nn(m,`No panel data found for index "${c}"`),h.setAttribute("aria-controls",m.id),h.setAttribute("aria-valuemax",""+Math.round(u)),h.setAttribute("aria-valuemin",""+Math.round(d)),h.setAttribute("aria-valuenow",f!=null?""+Math.round(f):"")}}return()=>{a.forEach((c,u)=>{c.removeAttribute("aria-controls"),c.removeAttribute("aria-valuemax"),c.removeAttribute("aria-valuemin"),c.removeAttribute("aria-valuenow")})}},[n,r,o,s]),v.useEffect(()=>{if(!s)return;const a=t.current;Nn(a,"Eager values not found");const{panelDataArray:c}=a,u=Hpe(n,s);Nn(u!=null,`No group found for id "${n}"`);const d=vv(n,s);Nn(d,`No resize handles found for group id "${n}"`);const f=d.map(h=>{const m=h.getAttribute(Jr.resizeHandleId);Nn(m,"Resize handle element has no handle id attribute");const[g,b]=p0t(n,m,c,s);if(g==null||b==null)return()=>{};const x=y=>{if(!y.defaultPrevented)switch(y.key){case"Enter":{y.preventDefault();const w=c.findIndex(C=>C.id===g);if(w>=0){const C=c[w];Nn(C,`No panel data found for index ${w}`);const N=r[w],{collapsedSize:S=0,collapsible:j,minSize:_=0}=C.constraints;if(N!=null&&j){const k=Cy({delta:Pi(N,S)?_-S:S-N,initialLayout:r,panelConstraints:c.map(T=>T.constraints),pivotIndices:Vpe(n,m,s),prevLayout:r,trigger:"keyboard"});r!==k&&i(k)}}break}}};return h.addEventListener("keydown",x),()=>{h.removeEventListener("keydown",x)}});return()=>{f.forEach(h=>h())}},[s,e,t,n,r,o,i])}function LK(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function qpe(e,t){const n=e==="horizontal",{x:r,y:o}=_T(t);return n?r:o}function b0t(e,t,n,r,o){const s=n==="horizontal",i=TT(t,o);Nn(i,`No resize handle element found for id "${t}"`);const a=i.getAttribute(Jr.groupId);Nn(a,"Resize handle element has no group id attribute");let{initialCursorPosition:c}=r;const u=qpe(n,e),d=Hpe(a,o);Nn(d,`No group element found for id "${a}"`);const f=d.getBoundingClientRect(),h=s?f.width:f.height;return(u-c)/h*100}function x0t(e,t,n,r,o,s){if(Mpe(e)){const i=n==="horizontal";let a=0;e.shiftKey?a=100:o!=null?a=o:a=10;let c=0;switch(e.key){case"ArrowDown":c=i?0:a;break;case"ArrowLeft":c=i?-a:0;break;case"ArrowRight":c=i?a:0;break;case"ArrowUp":c=i?0:-a;break;case"End":c=100;break;case"Home":c=-100;break}return c}else return r==null?0:b0t(e,t,n,r,s)}function y0t({panelDataArray:e}){const t=Array(e.length),n=e.map(s=>s.constraints);let r=0,o=100;for(let s=0;s<e.length;s++){const i=n[s];Nn(i,`Panel constraints not found for index ${s}`);const{defaultSize:a}=i;a!=null&&(r++,t[s]=a,o-=a)}for(let s=0;s<e.length;s++){const i=n[s];Nn(i,`Panel constraints not found for index ${s}`);const{defaultSize:a}=i;if(a!=null)continue;const c=e.length-r,u=o/c;r++,t[s]=u,o-=u}return t}function _p(e,t,n){t.forEach((r,o)=>{const s=e[o];Nn(s,`Panel data not found for index ${o}`);const{callbacks:i,constraints:a,id:c}=s,{collapsedSize:u=0,collapsible:d}=a,f=n[c];if(f==null||r!==f){n[c]=r;const{onCollapse:h,onExpand:m,onResize:g}=i;g&&g(r,f),d&&(h||m)&&(m&&(f==null||Hc(f,u))&&!Hc(r,u)&&m(),h&&(f==null||!Hc(f,u))&&Hc(r,u)&&h())}})}function n1(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function v0t({defaultSize:e,dragState:t,layout:n,panelData:r,panelIndex:o,precision:s=3}){const i=n[o];let a;return i==null?a=e!=null?e.toPrecision(s):"1":r.length===1?a="1":a=i.toPrecision(s),{flexBasis:0,flexGrow:a,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function w0t(e,t=10){let n=null;return(...o)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...o)},t)}}function $K(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function Upe(e){return`react-resizable-panels:${e}`}function Wpe(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:o,order:s}=t;return o?r:s?`${s}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function Kpe(e,t){try{const n=Upe(e),r=t.getItem(n);if(r){const o=JSON.parse(r);if(typeof o=="object"&&o!=null)return o}}catch{}return null}function C0t(e,t,n){var r,o;const s=(r=Kpe(e,n))!==null&&r!==void 0?r:{},i=Wpe(t);return(o=s[i])!==null&&o!==void 0?o:null}function S0t(e,t,n,r,o){var s;const i=Upe(e),a=Wpe(t),c=(s=Kpe(e,o))!==null&&s!==void 0?s:{};c[a]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{o.setItem(i,JSON.stringify(c))}catch(u){console.error(u)}}function zK({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((s,i)=>s+i,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(s=>`${s}%`).join(", ")}`);if(!Pi(r,100)&&n.length>0)for(let s=0;s<t.length;s++){const i=n[s];Nn(i!=null,`No layout data found for index ${s}`);const a=100/r*i;n[s]=a}let o=0;for(let s=0;s<t.length;s++){const i=n[s];Nn(i!=null,`No layout data found for index ${s}`);const a=Jp({panelConstraints:t,panelIndex:s,size:i});i!=a&&(o+=i-a,n[s]=a)}if(!Pi(o,0))for(let s=0;s<t.length;s++){const i=n[s];Nn(i!=null,`No layout data found for index ${s}`);const a=i+o,c=Jp({panelConstraints:t,panelIndex:s,size:a});if(i!==c&&(o-=c-i,n[s]=c,Pi(o,0)))break}return n}const N0t=100,Sy={getItem:e=>($K(Sy),Sy.getItem(e)),setItem:(e,t)=>{$K(Sy),Sy.setItem(e,t)}},BK={};function Gpe({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:o,id:s=null,onLayout:i=null,keyboardResizeBy:a=null,storage:c=Sy,style:u,tagName:d="div",...f}){const h=w4(s),m=v.useRef(null),[g,b]=v.useState(null),[x,y]=v.useState([]),w=f0t(),C=v.useRef({}),N=v.useRef(new Map),S=v.useRef(0),j=v.useRef({autoSaveId:e,direction:r,dragState:g,id:h,keyboardResizeBy:a,onLayout:i,storage:c}),_=v.useRef({layout:x,panelDataArray:[],panelDataArrayChanged:!1});v.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),v.useImperativeHandle(o,()=>({getId:()=>j.current.id,getLayout:()=>{const{layout:P}=_.current;return P},setLayout:P=>{const{onLayout:G}=j.current,{layout:Z,panelDataArray:X}=_.current,Y=zK({layout:P,panelConstraints:X.map(O=>O.constraints)});LK(Z,Y)||(y(Y),_.current.layout=Y,G&&G(Y),_p(X,Y,C.current))}}),[]),Yh(()=>{j.current.autoSaveId=e,j.current.direction=r,j.current.dragState=g,j.current.id=h,j.current.onLayout=i,j.current.storage=c}),g0t({committedValuesRef:j,eagerValuesRef:_,groupId:h,layout:x,panelDataArray:_.current.panelDataArray,setLayout:y,panelGroupElement:m.current}),v.useEffect(()=>{const{panelDataArray:P}=_.current;if(e){if(x.length===0||x.length!==P.length)return;let G=BK[e];G==null&&(G=w0t(S0t,N0t),BK[e]=G);const Z=[...P],X=new Map(N.current);G(e,Z,X,x,c)}},[e,x,c]),v.useEffect(()=>{});const k=v.useCallback(P=>{const{onLayout:G}=j.current,{layout:Z,panelDataArray:X}=_.current;if(P.constraints.collapsible){const Y=X.map(V=>V.constraints),{collapsedSize:O=0,panelSize:q,pivotIndices:U}=Hf(X,P,Z);if(Nn(q!=null,`Panel size not found for panel "${P.id}"`),!Hc(q,O)){N.current.set(P.id,q);const K=zp(X,P)===X.length-1?q-O:O-q,Q=Cy({delta:K,initialLayout:Z,panelConstraints:Y,pivotIndices:U,prevLayout:Z,trigger:"imperative-api"});n1(Z,Q)||(y(Q),_.current.layout=Q,G&&G(Q),_p(X,Q,C.current))}}},[]),T=v.useCallback((P,G)=>{const{onLayout:Z}=j.current,{layout:X,panelDataArray:Y}=_.current;if(P.constraints.collapsible){const O=Y.map(se=>se.constraints),{collapsedSize:q=0,panelSize:U=0,minSize:V=0,pivotIndices:K}=Hf(Y,P,X),Q=G??V;if(Hc(U,q)){const se=N.current.get(P.id),oe=se!=null&&se>=Q?se:Q,le=zp(Y,P)===Y.length-1?U-oe:oe-U,ue=Cy({delta:le,initialLayout:X,panelConstraints:O,pivotIndices:K,prevLayout:X,trigger:"imperative-api"});n1(X,ue)||(y(ue),_.current.layout=ue,Z&&Z(ue),_p(Y,ue,C.current))}}},[]),I=v.useCallback(P=>{const{layout:G,panelDataArray:Z}=_.current,{panelSize:X}=Hf(Z,P,G);return Nn(X!=null,`Panel size not found for panel "${P.id}"`),X},[]),E=v.useCallback((P,G)=>{const{panelDataArray:Z}=_.current,X=zp(Z,P);return v0t({defaultSize:G,dragState:g,layout:x,panelData:Z,panelIndex:X})},[g,x]),D=v.useCallback(P=>{const{layout:G,panelDataArray:Z}=_.current,{collapsedSize:X=0,collapsible:Y,panelSize:O}=Hf(Z,P,G);return Nn(O!=null,`Panel size not found for panel "${P.id}"`),Y===!0&&Hc(O,X)},[]),R=v.useCallback(P=>{const{layout:G,panelDataArray:Z}=_.current,{collapsedSize:X=0,collapsible:Y,panelSize:O}=Hf(Z,P,G);return Nn(O!=null,`Panel size not found for panel "${P.id}"`),!Y||Tm(O,X)>0},[]),A=v.useCallback(P=>{const{panelDataArray:G}=_.current;G.push(P),G.sort((Z,X)=>{const Y=Z.order,O=X.order;return Y==null&&O==null?0:Y==null?-1:O==null?1:Y-O}),_.current.panelDataArrayChanged=!0,w()},[w]);Yh(()=>{if(_.current.panelDataArrayChanged){_.current.panelDataArrayChanged=!1;const{autoSaveId:P,onLayout:G,storage:Z}=j.current,{layout:X,panelDataArray:Y}=_.current;let O=null;if(P){const U=C0t(P,Y,Z);U&&(N.current=new Map(Object.entries(U.expandToSizes)),O=U.layout)}O==null&&(O=y0t({panelDataArray:Y}));const q=zK({layout:O,panelConstraints:Y.map(U=>U.constraints)});LK(X,q)||(y(q),_.current.layout=q,G&&G(q),_p(Y,q,C.current))}}),Yh(()=>{const P=_.current;return()=>{P.layout=[]}},[]);const F=v.useCallback(P=>{let G=!1;const Z=m.current;return Z&&window.getComputedStyle(Z,null).getPropertyValue("direction")==="rtl"&&(G=!0),function(Y){Y.preventDefault();const O=m.current;if(!O)return()=>null;const{direction:q,dragState:U,id:V,keyboardResizeBy:K,onLayout:Q}=j.current,{layout:se,panelDataArray:oe}=_.current,{initialLayout:me}=U??{},le=Vpe(V,P,O);let ue=x0t(Y,P,q,U,K,O);const ne=q==="horizontal";ne&&G&&(ue=-ue);const de=oe.map(ie=>ie.constraints),Ce=Cy({delta:ue,initialLayout:me??se,panelConstraints:de,pivotIndices:le,prevLayout:se,trigger:Mpe(Y)?"keyboard":"mouse-or-touch"}),ce=!n1(se,Ce);(Rpe(Y)||Ape(Y))&&S.current!=ue&&(S.current=ue,!ce&&ue!==0?ne?k2(P,ue<0?Fpe:Ope):k2(P,ue<0?Lpe:$pe):k2(P,0)),ce&&(y(Ce),_.current.layout=Ce,Q&&Q(Ce),_p(oe,Ce,C.current))}},[]),z=v.useCallback((P,G)=>{const{onLayout:Z}=j.current,{layout:X,panelDataArray:Y}=_.current,O=Y.map(se=>se.constraints),{panelSize:q,pivotIndices:U}=Hf(Y,P,X);Nn(q!=null,`Panel size not found for panel "${P.id}"`);const K=zp(Y,P)===Y.length-1?q-G:G-q,Q=Cy({delta:K,initialLayout:X,panelConstraints:O,pivotIndices:U,prevLayout:X,trigger:"imperative-api"});n1(X,Q)||(y(Q),_.current.layout=Q,Z&&Z(Q),_p(Y,Q,C.current))},[]),L=v.useCallback((P,G)=>{const{layout:Z,panelDataArray:X}=_.current,{collapsedSize:Y=0,collapsible:O}=G,{collapsedSize:q=0,collapsible:U,maxSize:V=100,minSize:K=0}=P.constraints,{panelSize:Q}=Hf(X,P,Z);Q!=null&&(O&&U&&Hc(Q,Y)?Hc(Y,q)||z(P,q):Q<K?z(P,K):Q>V&&z(P,V))},[z]),$=v.useCallback((P,G)=>{const{direction:Z}=j.current,{layout:X}=_.current;if(!m.current)return;const Y=TT(P,m.current);Nn(Y,`Drag handle element not found for id "${P}"`);const O=qpe(Z,G);b({dragHandleId:P,dragHandleRect:Y.getBoundingClientRect(),initialCursorPosition:O,initialLayout:X})},[]),H=v.useCallback(()=>{b(null)},[]),M=v.useCallback(P=>{const{panelDataArray:G}=_.current,Z=zp(G,P);Z>=0&&(G.splice(Z,1),delete C.current[P.id],_.current.panelDataArrayChanged=!0,w())},[w]),B=v.useMemo(()=>({collapsePanel:k,direction:r,dragState:g,expandPanel:T,getPanelSize:I,getPanelStyle:E,groupId:h,isPanelCollapsed:D,isPanelExpanded:R,reevaluatePanelConstraints:L,registerPanel:A,registerResizeHandle:F,resizePanel:z,startDragging:$,stopDragging:H,unregisterPanel:M,panelGroupElement:m.current}),[k,g,r,T,I,E,h,D,R,L,A,F,z,$,H,M]),W={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return v.createElement(kT.Provider,{value:B},v.createElement(d,{...f,children:t,className:n,id:s,ref:m,style:{...W,...u},[Jr.group]:"",[Jr.groupDirection]:r,[Jr.groupId]:h}))}const Ype=v.forwardRef((e,t)=>v.createElement(Gpe,{...e,forwardedRef:t}));Gpe.displayName="PanelGroup";Ype.displayName="forwardRef(PanelGroup)";function zp(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function Hf(e,t,n){const r=zp(e,t),s=r===e.length-1?[r-1,r]:[r,r+1],i=n[r];return{...t.constraints,panelSize:i,pivotIndices:s}}function j0t({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){v.useEffect(()=>{if(e||n==null||r==null)return;const o=TT(t,r);if(o==null)return;const s=i=>{if(!i.defaultPrevented)switch(i.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{i.preventDefault(),n(i);break}case"F6":{i.preventDefault();const a=o.getAttribute(Jr.groupId);Nn(a,`No group element found for id "${a}"`);const c=vv(a,r),u=Bpe(a,t,r);Nn(u!==null,`No resize element found for id "${t}"`);const d=i.shiftKey?u>0?u-1:c.length-1:u+1<c.length?u+1:0;c[d].focus();break}}};return o.addEventListener("keydown",s),()=>{o.removeEventListener("keydown",s)}},[r,e,t,n])}function ET({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:o,onBlur:s,onClick:i,onDragging:a,onFocus:c,onPointerDown:u,onPointerUp:d,style:f={},tabIndex:h=0,tagName:m="div",...g}){var b,x;const y=v.useRef(null),w=v.useRef({onClick:i,onDragging:a,onPointerDown:u,onPointerUp:d});v.useEffect(()=>{w.current.onClick=i,w.current.onDragging=a,w.current.onPointerDown=u,w.current.onPointerUp=d});const C=v.useContext(kT);if(C===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:N,groupId:S,registerResizeHandle:j,startDragging:_,stopDragging:k,panelGroupElement:T}=C,I=w4(o),[E,D]=v.useState("inactive"),[R,A]=v.useState(!1),[F,z]=v.useState(null),L=v.useRef({state:E});Yh(()=>{L.current.state=E}),v.useEffect(()=>{if(n)z(null);else{const B=j(I);z(()=>B)}},[n,I,j]);const $=(b=r==null?void 0:r.coarse)!==null&&b!==void 0?b:15,H=(x=r==null?void 0:r.fine)!==null&&x!==void 0?x:5;v.useEffect(()=>{if(n||F==null)return;const B=y.current;Nn(B,"Element ref not attached");let W=!1;return u0t(I,B,N,{coarse:$,fine:H},(G,Z,X)=>{if(!Z){D("inactive");return}switch(G){case"down":{D("drag"),W=!1,Nn(X,'Expected event to be defined for "down" action'),_(I,X);const{onDragging:Y,onPointerDown:O}=w.current;Y==null||Y(!0),O==null||O();break}case"move":{const{state:Y}=L.current;W=!0,Y!=="drag"&&D("hover"),Nn(X,'Expected event to be defined for "move" action'),F(X);break}case"up":{D("hover"),k();const{onClick:Y,onDragging:O,onPointerUp:q}=w.current;O==null||O(!1),q==null||q(),W||Y==null||Y();break}}})},[$,N,n,H,j,I,F,_,k]),j0t({disabled:n,handleId:I,resizeHandler:F,panelGroupElement:T});const M={touchAction:"none",userSelect:"none"};return v.createElement(m,{...g,children:e,className:t,id:o,onBlur:()=>{A(!1),s==null||s()},onFocus:()=>{A(!0),c==null||c()},ref:y,role:"separator",style:{...M,...f},tabIndex:h,[Jr.groupDirection]:N,[Jr.groupId]:S,[Jr.resizeHandle]:"",[Jr.resizeHandleActive]:E==="drag"?"pointer":R?"keyboard":void 0,[Jr.resizeHandleEnabled]:!n,[Jr.resizeHandleId]:I,[Jr.resizeHandleState]:E})}ET.displayName="PanelResizeHandle";const Zpe=({className:e,...t})=>l.jsx(Ype,{className:p.cn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),OF=Dpe,k0t=({withHandle:e,className:t,...n})=>l.jsx(ET,{className:p.cn("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&l.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:l.jsx(Nu,{className:"h-2.5 w-2.5"})})}),_0t=({withHandle:e,className:t,onTabClick:n,open:r,...o})=>l.jsx(ET,{className:p.cn("relative flex w-px items-start justify-end bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",{"justify-start":r},t),...o,children:e&&!1});function I0t(e={}){const{initialPosition:t="bottom-right"}=e,[n,r]=v.useState(t),[o,s]=v.useState(!1),[i,a]=v.useState(null),c=v.useRef(null),u=v.useRef(!1),d=v.useRef(null);v.useEffect(()=>()=>{d.current&&(d.current(),d.current=null)},[]);const f=v.useCallback(g=>{const b="touches"in g?g.touches[0].clientX:g.clientX,x="touches"in g?g.touches[0].clientY:g.clientY;c.current={x:b,y:x},u.current=!1,a({x:b,y:x});const y=(_,k,T)=>{if(!c.current)return;const I=Math.abs(_-c.current.x),E=Math.abs(k-c.current.y);(I>10||E>10)&&(u.current?T.cancelable&&T.preventDefault():(T.cancelable&&T.preventDefault(),u.current=!0,s(!0))),a({x:_,y:k})},w={passive:!1},C=_=>{y(_.clientX,_.clientY,_)},N=_=>{if(_.touches.length===0)return;const k=_.touches[0];y(k.clientX,k.clientY,_)},S=()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j),document.removeEventListener("touchmove",N),document.removeEventListener("touchend",j),d.current=null},j=()=>{a(_=>{if(u.current&&_){const k=window.innerWidth,T=window.innerHeight,I=_.x<k/2,E=_.y<T/2;r(E&&I?"top-left":E&&!I?"top-right":!E&&I?"bottom-left":"bottom-right")}return null}),c.current=null,setTimeout(()=>{u.current=!1,s(!1)},100),S()};document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),document.addEventListener("touchmove",N,w),document.addEventListener("touchend",j),d.current=S},[]),h=v.useCallback(()=>{if(o&&i)return{position:"fixed",left:0,top:0,right:"auto",bottom:"auto",transform:`translate(${i.x-24}px, ${i.y-24}px)`,transition:"none",willChange:"transform"}},[o,i]),m=v.useCallback(()=>({horizontal:n.includes("left")?"left-6":"right-6",vertical:n.includes("top")?"top-6":"bottom-6"}),[n]);return{position:n,isDragging:o,dragPosition:i,handleDragStart:f,isDraggingRef:u,getStyle:h,getPositionClasses:m}}function T0t({open:e,setOpen:t}){const n=p.useDashboardStore(s=>s.selectedSheetId),{deleteSheet:r}=p.useDashboardActions();function o(){n&&(r(n),t(!1))}return l.jsx(ff,{open:e,onOpenChange:t,children:l.jsxs(ku,{children:[l.jsxs(_u,{children:[l.jsx(Tu,{children:"Delete Sheet"}),l.jsx(Eu,{children:"Are you sure you want to delete this sheet along with all its cards? This action cannot be undone."})]}),l.jsxs(Iu,{children:[l.jsx(Mu,{children:"Cancel"}),l.jsx(Du,{className:"bg-destructive hover:bg-destructive/90",onClick:o,children:"Delete"})]})]})})}function Xpe({placeholders:e,onClick:t}){return l.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:e==null?void 0:e.map(n=>l.jsxs("button",{type:"button",onClick:()=>t(n),className:"flex cursor-pointer flex-col items-start gap-1 rounded-control border border-border/60 bg-muted/30 px-2.5 py-2 text-left transition-colors hover:border-border hover:bg-muted/50",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:n.title}),l.jsx("span",{className:"text-[12px] leading-[1.45] text-foreground/80",children:n.subtitle})]},n.title))})}var Qpe="vercel.ai.error",E0t=Symbol.for(Qpe),Jpe,D0t=class ege extends Error{constructor({name:t,message:n,cause:r}){super(n),this[Jpe]=!0,this.name=t,this.cause=r}static isInstance(t){return ege.hasMarker(t,Qpe)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}};Jpe=E0t;var of=D0t;function tge(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var nge="AI_InvalidArgumentError",rge=`vercel.ai.error.${nge}`,M0t=Symbol.for(rge),oge,R0t=class extends of{constructor({message:e,cause:t,argument:n}){super({name:nge,message:e,cause:t}),this[oge]=!0,this.argument=n}static isInstance(e){return of.hasMarker(e,rge)}};oge=M0t;var sge="AI_JSONParseError",ige=`vercel.ai.error.${sge}`,A0t=Symbol.for(ige),age,VK=class extends of{constructor({text:e,cause:t}){super({name:sge,message:`JSON parsing failed: Text: ${e}.
|
|
1340
|
+
`});return}Ue(e)&&e.getChildren().forEach(s=>ipe(s,t,n,r,o))}function ape(e,t){const n=e.map(i=>i.value).join(""),r=Ext(e),o=dpt(n,t),s=[];for(const i of o.content){if(i.type==="variable"){const a=Mxt(r,i.sourceStart,i.sourceEnd);s.push({type:"variable",ref:i.ref,...a?{format:a}:{}});continue}Dxt(s,n,r,i.sourceStart,i.sourceEnd)}return{content:ST(s),unresolvedTokens:o.unresolvedTokens}}function Ext(e){let t=0;return e.map(n=>{const r=t,o=r+n.value.length;return t=o,{...n,start:r,end:o}})}function Dxt(e,t,n,r,o){for(const s of n){const i=Math.max(r,s.start),a=Math.min(o,s.end);i>=a||e.push({type:"text",value:t.slice(i,a),...s.format?{format:s.format}:{}})}}function Mxt(e,t,n){var o,s,i;const r={};for(const a of e)Math.max(t,a.start)>=Math.min(n,a.end)||(r.bold||(r.bold=(o=a.format)==null?void 0:o.bold),r.italic||(r.italic=(s=a.format)==null?void 0:s.italic),r.underline||(r.underline=(i=a.format)==null?void 0:i.underline));return r.bold||r.italic||r.underline?r:void 0}function _K(e,t){let n=0;t!=null&&t.bold&&(n|=rse),t!=null&&t.italic&&(n|=ose),t!=null&&t.underline&&(n|=sse),e.setFormat(n)}function IK(e){return p.cn("rounded-[2px] bg-emerald-50 px-0.5 font-mono text-[0.92em] font-medium text-emerald-700 ring-1 ring-inset ring-emerald-200/80",e.hasFormat("bold")&&"font-semibold",e.hasFormat("italic")&&"italic",e.hasFormat("underline")&&"underline")}function TK(e){const t={bold:e.hasFormat("bold"),italic:e.hasFormat("italic"),underline:e.hasFormat("underline")};return t.bold||t.italic||t.underline?t:void 0}function lpe(e,t){const n=[],r=[],o=[],s=()=>{if(r.length===0)return;const i=ape(r,t);n.push(...i.content),o.push(...i.unresolvedTokens),r.length=0};for(const i of e){if(i.type==="variable"){s(),n.push(i);continue}r.push({value:i.value,format:i.format})}return s(),{content:ST(n),unresolvedTokens:o}}function ST(e){const t=[];for(const n of e){const r=t[t.length-1];if(n.type==="text"&&(r==null?void 0:r.type)==="text"&&cpe(n.format,r.format)){r.value+=n.value;continue}t.push(n)}return t}function cpe(e,t){return!!(e!=null&&e.bold)==!!(t!=null&&t.bold)&&!!(e!=null&&e.italic)==!!(t!=null&&t.italic)&&!!(e!=null&&e.underline)==!!(t!=null&&t.underline)}function Rxt(e){return JSON.stringify(e||[])}function upe(e,t){return JSON.stringify({content:e||[],variableLabels:(e||[]).filter(n=>n.type==="variable").map(n=>c4(n.ref,t))})}function Axt(e,t){return e!=null&&e.some(n=>n.type==="text")?lpe(e,t).content.some(n=>n.type==="variable"):!1}function Pxt(e,t){const n=e||[],r=t||[];return n.length!==r.length?!1:n.every((o,s)=>{const i=r[s];return o.type!==i.type||!cpe(o.format,i.format)?!1:o.type==="text"&&i.type==="text"?o.value===i.value:o.type==="variable"&&i.type==="variable"?o.ref.source!==i.ref.source?!1:o.ref.source==="documentMeta"&&i.ref.source==="documentMeta"?o.ref.key===i.ref.key:o.ref.source==="input"&&i.ref.source==="input"&&o.ref.inputId===i.ref.inputId&&o.ref.export===i.ref.export:!1})}function Fxt(e){const t=new Map,n={key:"__document__",label:"Document",choices:[]};for(const o of e){if(o.ref.source==="documentMeta"){n.choices.push(o);continue}const s=o.label.split(".")[0];let i=t.get(s);i||(i={key:`input:${s}`,label:s,choices:[]},t.set(s,i)),i.choices.push(o)}const r=Array.from(t.values());return n.choices.length>0?[...r,n]:r}function Oxt({choices:e,onInsert:t}){const[n,r]=v.useState(!1),[o,s]=v.useState(""),i=v.useMemo(()=>Fxt(e),[e]),a=v.useMemo(()=>{const u=o.trim().toLowerCase();return u?i.map(d=>({...d,choices:d.choices.filter(f=>f.label.toLowerCase().includes(u)||f.token.toLowerCase().includes(u))})).filter(d=>d.choices.length>0):i},[i,o]);function c(u){t(u),s(""),r(!1)}return l.jsxs(p.Popover,{open:n,onOpenChange:r,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Insert variable",title:"Insert variable",className:"inline-flex h-5 items-center gap-0.5 rounded-[3px] border border-transparent px-1.5 text-[10px] font-medium text-muted-foreground transition-colors hover:border-border hover:bg-muted hover:text-foreground",children:[l.jsx(Tr,{className:"h-2.5 w-2.5"}),"Variable"]})}),l.jsxs(p.PopoverContent,{align:"end",side:"bottom",sideOffset:6,className:"w-72 p-0",children:[l.jsxs("div",{className:"flex items-center gap-2 border-b border-border/60 px-2.5 py-1.5",children:[l.jsx(Ft.Search,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("input",{type:"text",value:o,onChange:u=>s(u.target.value),placeholder:"Search variables...",autoFocus:!0,className:"h-6 flex-1 bg-transparent text-[12px] outline-none placeholder:text-[hsl(var(--semaphor-placeholder-foreground))]"})]}),l.jsx("div",{className:"max-h-[280px] overflow-y-auto p-1",children:a.length===0?l.jsxs("div",{className:"px-2 py-3 text-[12px] text-muted-foreground",children:['No matches for "',o,'".']}):a.map(u=>l.jsxs("div",{className:"space-y-0.5 pb-1",children:[l.jsx("div",{className:"px-2 pb-0.5 pt-1.5 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:u.label}),u.choices.map(d=>l.jsx("button",{type:"button",onClick:()=>c(d),className:"flex w-full items-center justify-between gap-2 rounded-[4px] px-2 py-1 text-left transition-colors hover:bg-muted",children:l.jsx("span",{className:"truncate font-mono text-[11px] text-foreground",children:d.label})},d.token))]},u.key))})]})]})}function Oo({label:e,children:t}){return l.jsxs("div",{children:[l.jsx("label",{className:"mb-1 block text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),t]})}function dpe({label:e,enabled:t,onToggle:n}){return l.jsxs("label",{className:"flex h-8 cursor-pointer items-center justify-between gap-3 rounded-[5px] border border-border/60 bg-background px-2.5 text-[12px]",children:[l.jsx("span",{className:p.cn(t?"text-foreground":"text-muted-foreground"),children:e}),l.jsx(p.Switch,{size:"sm",checked:t,onCheckedChange:n})]})}function fpe({columns:e,columnVisibility:t,onColumnVisibilityChange:n,onShowAllColumns:r,emptyMessage:o="Run the query or add fields to configure output columns.",helperText:s="Hidden columns stay available for conditional formatting triggers, but are omitted from table output and exports.",className:i}){const a=Object.values(t||{}).filter(c=>c===!1).length;return e.length===0?l.jsx("div",{className:p.cn("space-y-3",i),children:l.jsx("p",{className:"rounded-[6px] border border-dashed border-border/60 px-3 py-4 text-[12px] leading-5 text-muted-foreground",children:o})}):l.jsxs("div",{className:p.cn("space-y-3",i),children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:s}),l.jsx(p.Button,{type:"button",variant:"ghost",size:"xs",className:"h-6 shrink-0 px-2 text-[11px]",disabled:a===0,onClick:r,children:"Show all"})]}),l.jsx("div",{className:"overflow-hidden rounded-[6px] border border-border/60 bg-background",children:l.jsx("div",{className:"max-h-[calc(100vh-260px)] divide-y divide-border/60 overflow-y-auto",children:e.map(c=>{const u=roe(t,c.value);return l.jsxs("label",{className:"flex cursor-pointer items-center justify-between gap-3 px-3 py-2 transition-colors hover:bg-muted/40",children:[l.jsxs("span",{className:"min-w-0",children:[l.jsx("span",{className:"block truncate text-[13px] font-medium text-foreground",children:c.label}),c.label!==c.value?l.jsx("span",{className:"block truncate text-[11px] text-muted-foreground",children:c.value}):null]}),l.jsx(p.Switch,{size:"xs",checked:u,"aria-label":`${u?"Hide":"Show"} ${c.label}`,onCheckedChange:d=>n(c.value,d)})]},c.value)})})})]})}const Lxt=[null,"#fee2e2","#fef3c7","#dcfce7","#dbeafe","#ede9fe","#ffe4e6","#f4f4f5"],$xt=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;function hpe(e){return typeof e=="string"&&$xt.test(e)}function zxt(e){const t=e.trim();return t?t.startsWith("#")?t:`#${t}`:""}function Bxt(e,t="#000000"){if(hpe(e)){if(e.length===7)return e;if(e.length===4){const n=e[1],r=e[2],o=e[3];return`#${n}${n}${r}${r}${o}${o}`}if(e.length===9)return e.slice(0,7)}return t}const Vxt=120;function da({value:e,onChange:t,defaultValue:n,allowEmpty:r=!0,presets:o=Lxt,ariaLabel:s,placeholder:i="#000000",id:a,className:c,disabled:u=!1}){const[d,f]=te.useState(!1),[h,m]=te.useState(e??""),[g,b]=te.useState(e),x=te.useRef(null),y=te.useRef(void 0),w=te.useRef(t);te.useEffect(()=>{w.current=t},[t]),te.useEffect(()=>{x.current===null&&(m(e??""),b(e))},[e]),te.useEffect(()=>()=>{x.current!==null&&clearTimeout(x.current)},[]);const C=te.useCallback(()=>{if(x.current===null)return;clearTimeout(x.current),x.current=null;const T=y.current;y.current=void 0,T!==void 0&&w.current(T)},[]),N=te.useCallback(T=>{b(T),m(T),y.current=T,x.current!==null&&clearTimeout(x.current),x.current=setTimeout(()=>{const I=y.current;x.current=null,y.current=void 0,I!==void 0&&w.current(I)},Vxt)},[]),S=te.useCallback(T=>{x.current!==null&&(clearTimeout(x.current),x.current=null,y.current=void 0),b(T),t(T)},[t]),j=g??e,_=n!==void 0&&(j??void 0)!==n,k=T=>{const I=zxt(T);if(!I){if(r){S(void 0);return}m(e??"");return}if(hpe(I)){S(I),m(I);return}m(e??"")};return l.jsxs("div",{className:p.cn("flex h-7 items-center gap-1.5",c),children:[l.jsxs(p.Popover,{open:d,onOpenChange:T=>{T||C(),f(T)},children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsx("button",{type:"button",disabled:u,"aria-label":s?`Pick ${s}`:"Pick a color",className:p.cn("relative size-6 shrink-0 overflow-hidden rounded-[5px] border border-border/60 transition-colors","hover:border-border","focus-visible:border-ring focus-visible:outline-none",u&&"cursor-not-allowed opacity-50"),style:j?{backgroundColor:j}:{backgroundImage:"linear-gradient(to top right, transparent calc(50% - 0.5px), hsl(var(--border)) calc(50% - 0.5px), hsl(var(--border)) calc(50% + 0.5px), transparent calc(50% + 0.5px))"}})}),l.jsxs(p.PopoverContent,{align:"start",sideOffset:6,className:"z-[60] w-[220px] space-y-2.5 rounded-[6px] p-2.5",children:[l.jsx("div",{className:"flex flex-wrap items-center gap-1",children:o.map((T,I)=>{const E=T===null,D=(j??null)===T||T!==null&&(j==null?void 0:j.toLowerCase())===T.toLowerCase(),R=()=>{if(E){r&&S(void 0);return}S(T)};return E&&!r?null:l.jsx("button",{type:"button",onClick:R,"aria-label":E?"No color":T,className:p.cn("relative flex size-6 items-center justify-center rounded-[4px] border transition-colors",D?"border-foreground":"border-border/60 hover:border-border"),style:E?{backgroundImage:"linear-gradient(to top right, transparent calc(50% - 0.5px), hsl(var(--border)) calc(50% - 0.5px), hsl(var(--border)) calc(50% + 0.5px), transparent calc(50% + 0.5px))"}:{backgroundColor:T??void 0},children:D&&!E&&l.jsx(p.Check,{className:"size-3",strokeWidth:3,style:{color:"#fff",mixBlendMode:"difference"}})},`${T??"none"}-${I}`)})}),l.jsx("div",{className:"h-px bg-border/60"}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("input",{type:"color","aria-label":"Custom color",value:Bxt(j),onChange:T=>N(T.target.value),onBlur:C,className:"h-7 w-10 shrink-0 cursor-pointer rounded-[5px] border border-border/60 bg-background p-0.5"}),l.jsx(p.Input,{size:"xs",value:h,onChange:T=>m(T.target.value),onBlur:T=>k(T.target.value),onKeyDown:T=>{T.key==="Enter"?(k(h),f(!1)):T.key==="Escape"&&(m(e??""),f(!1))},placeholder:i,className:p.cn("w-full font-mono text-[11px]",p.removeRing)})]}),l.jsxs("div",{className:"flex items-center justify-between pt-0.5",children:[_?l.jsxs("button",{type:"button",onClick:()=>S(n),className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(p.RotateCcw,{className:"size-3"}),"Reset to default"]}):l.jsx("span",{}),l.jsx("button",{type:"button",onClick:()=>{C(),f(!1)},className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground transition-colors hover:text-foreground","aria-label":"Close color picker",children:"Done"})]})]})]}),l.jsx(p.Input,{size:"xs",id:a,"aria-label":s,value:h,onChange:T=>m(T.target.value),onBlur:T=>k(T.target.value),onKeyDown:T=>{T.key==="Enter"?(k(h),T.target.blur()):T.key==="Escape"&&(m(e??""),T.target.blur())},placeholder:i,disabled:u,className:p.cn("w-full font-mono text-[11px]",p.removeRing)}),_&&l.jsx("button",{type:"button",onClick:()=>S(n),"aria-label":"Reset color",className:"inline-flex size-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(p.RotateCcw,{className:"size-3"})})]})}function mpe({style:e,onDensityChange:t,onStyleChange:n,totals:r,showFullStyle:o=!0,showBorderStyle:s=!0,extraSection:i,onReset:a,className:c}){const u=(r==null?void 0:r.enabled)??e.totalsStyle.enabled,d=!!r,f=!!(r!=null&&r.onStyleChange)&&(u||!(r!=null&&r.onEnabledChange)),h=qoe[e.headerStyle],m=b=>{n({headerBackgroundColor:b===h.background?void 0:b})},g=b=>{n({headerTextColor:b===h.color?void 0:b})};return l.jsxs("div",{className:p.cn("space-y-5",c),children:[l.jsxs(JS,{label:"Layout",children:[l.jsx(wl,{label:"Density",children:l.jsxs(p.Select,{value:e.density,onValueChange:b=>t(b),children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table density",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:zoe.map(b=>l.jsx(p.SelectItem,{value:b,children:q4e[b]},b))})]})}),o&&l.jsx(e1,{label:"Wrap text",checked:e.wrapText,onCheckedChange:b=>n({wrapText:b})})]}),o&&l.jsxs(l.Fragment,{children:[l.jsxs(JS,{label:"Header",children:[l.jsx(e1,{label:"Wrap header",checked:e.headerWrapText,onCheckedChange:b=>n({headerWrapText:b})}),l.jsx(wl,{label:"Style",children:l.jsxs(p.Select,{value:e.headerStyle,onValueChange:b=>n({headerStyle:b}),children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table header style",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:Boe.map(b=>l.jsx(p.SelectItem,{value:b,children:U4e[b]},b))})]})}),l.jsx(wl,{label:"Background",children:l.jsx(da,{value:e.headerBackgroundColor,onChange:m,defaultValue:h.background,allowEmpty:!1,ariaLabel:"Header background"})}),l.jsx(wl,{label:"Text",children:l.jsx(da,{value:e.headerTextColor,onChange:g,defaultValue:h.color,allowEmpty:!1,ariaLabel:"Header text"})})]}),l.jsxs(JS,{label:"Rows",children:[s&&l.jsx(wl,{label:"Borders",children:l.jsxs(p.Select,{value:e.gridLines,onValueChange:b=>n({gridLines:b}),children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table borders",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:Voe.map(b=>l.jsx(p.SelectItem,{value:b,children:W4e[b]},b))})]})}),l.jsx(e1,{label:"Row striping",checked:e.stripedRows,onCheckedChange:b=>n({stripedRows:b})})]})]}),o&&d&&l.jsxs(JS,{label:"Totals",action:r!=null&&r.onEnabledChange?l.jsx(p.Switch,{size:"xs","aria-label":"Show totals row",checked:u,onCheckedChange:b=>{var x;return(x=r==null?void 0:r.onEnabledChange)==null?void 0:x.call(r,!!b)}}):null,children:[r!=null&&r.helperText?l.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:r.helperText}):null,f?l.jsxs(l.Fragment,{children:[l.jsx(wl,{label:"Background",children:l.jsx(da,{value:e.totalsStyle.backgroundColor,onChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{backgroundColor:b})},defaultValue:ha.backgroundColor,allowEmpty:!1,ariaLabel:"Totals background"})}),l.jsx(wl,{label:"Text",children:l.jsx(da,{value:e.totalsStyle.textColor,onChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{textColor:b})},defaultValue:ha.textColor,allowEmpty:!1,ariaLabel:"Totals text"})}),l.jsx(wl,{label:"Weight",children:l.jsxs(p.Select,{value:e.totalsStyle.fontWeight,onValueChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{fontWeight:b})},children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table totals weight",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:Hoe.map(b=>l.jsx(p.SelectItem,{value:b,children:K4e[b]},b))})]})}),l.jsx(e1,{label:"Top border",checked:e.totalsStyle.borderTop,onCheckedChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{borderTop:b})}}),e.totalsStyle.borderTop?l.jsxs(l.Fragment,{children:[l.jsx(wl,{label:"Border style",children:l.jsxs(p.Select,{value:e.totalsStyle.borderTopStyle,onValueChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{borderTopStyle:b})},children:[l.jsx(p.SelectTrigger,{size:"xs","aria-label":"Table totals border style",className:"w-full",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:G4e.map(b=>l.jsx(p.SelectItem,{value:b,children:Y4e[b]},b))})]})}),l.jsx(wl,{label:"Border color",children:l.jsx(da,{value:e.totalsStyle.borderTopColor,onChange:b=>{var x;return(x=r==null?void 0:r.onStyleChange)==null?void 0:x.call(r,{borderTopColor:b})},defaultValue:ha.borderTopColor,allowEmpty:!1,ariaLabel:"Totals border color"})})]}):null]}):null]}),i,a?l.jsx(p.Button,{type:"button",variant:"ghost",size:"xs",className:"w-full",onClick:a,children:"Reset appearance"}):null]})}function JS({label:e,action:t,children:n}){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),t]}),l.jsx("div",{className:"space-y-2",children:n})]})}function wl({label:e,htmlFor:t,children:n}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("label",{htmlFor:t,className:"w-20 shrink-0 text-[12px] text-foreground",children:e}),l.jsx("div",{className:"min-w-0 flex-1",children:n})]})}function e1({label:e,checked:t,onCheckedChange:n}){return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"w-20 shrink-0 text-[12px] text-foreground",children:e}),l.jsx("div",{className:"min-w-0 flex-1",children:l.jsx(p.Switch,{size:"xs",checked:t,onCheckedChange:r=>n(!!r)})})]})}const la="__semaphor_unassigned_trigger__";function ppe(e){return e==="table"}function gpe(e){return e.label||e.alias||e.name||e.id||""}function bpe(e){return e.alias||e.name||e.id||e.label||""}function Hxt(e){var n,r,o;const t=((o=(r=(n=e==null?void 0:e.preferences)==null?void 0:n.tablePrefs)==null?void 0:r.conditionalFormatting)==null?void 0:o.rules)||[];return new Set(t.flatMap(s=>[s.condition.columnId,...s.target.columnIds||[],...s.target.applyToColumnIds||[]]).filter(s=>s&&s!==la))}function ih(e,t,n){t&&t!==la&&(e.has(t)||e.set(t,{value:t,label:n||p.toLabel(t)}))}function xpe(e,t=[]){var u;const n=e==null?void 0:e.config,r=(u=e==null?void 0:e.preferences)==null?void 0:u.tablePrefs,o=new Map,s=new Map,i=Hxt(e),a=new Set(t);return t.forEach(d=>ih(o,d,d)),[...(n==null?void 0:n.detailColumns)||[],...(n==null?void 0:n.groupByColumns)||[],...(n==null?void 0:n.metricColumns)||[],...(n==null?void 0:n.pivotByColumns)||[]].forEach(d=>{const f=gpe(d),h=bpe(d);ih(o,h,f);const m={value:h,label:f||p.toLabel(h)};[d.id,d.alias,d.name,d.label].forEach(g=>{g&&s.set(g,m)}),d.id&&i.has(d.id)&&ih(o,d.id,f)}),[...Object.keys((r==null?void 0:r.columnSettingsMap)||{}),...Object.keys((r==null?void 0:r.columnVisibility)||{}),...Object.keys((r==null?void 0:r.columnSizing)||{})].forEach(d=>{const f=s.get(d),h=a.has(d)||o.has(d),m=i.has(d);!f&&!h&&!m||f&&!i.has(d)||ih(o,d,f==null?void 0:f.label)}),i.forEach(d=>ih(o,d)),Array.from(o.values())}function ype(e,t=[]){const n=new Map;if(t.length>0)return t.forEach(s=>ih(n,s,s)),Array.from(n.values());const r=e==null?void 0:e.config;return[...(r==null?void 0:r.detailColumns)||[],...(r==null?void 0:r.groupByColumns)||[],...(r==null?void 0:r.metricColumns)||[],...(r==null?void 0:r.pivotByColumns)||[]].forEach(s=>{ih(n,bpe(s),gpe(s))}),Array.from(n.values())}function qxt(e,t){var n;return{...e,preferences:{...e.preferences,tablePrefs:{...(n=e.preferences)==null?void 0:n.tablePrefs,conditionalFormatting:t}}}}const vpe=[{value:"gt",label:"Greater than"},{value:"gte",label:"Greater than or equal"},{value:"lt",label:"Less than"},{value:"lte",label:"Less than or equal"},{value:"eq",label:"Equals"},{value:"neq",label:"Does not equal"},{value:"between",label:"Between"},{value:"contains",label:"Contains"},{value:"blank",label:"Is blank"},{value:"notBlank",label:"Is not blank"}];function NT(e){return e===la}function y2(e){return e!=null&&String(e).trim()!==""}function EK(e){return typeof e=="number"&&Number.isFinite(e)}function Uxt(e){return e.condition.kind==="comparison"||e.condition.kind==="between"||e.condition.kind==="contains"||e.condition.kind==="blank"?"comparison":e.condition.kind}function wpe(e){return e.condition.kind==="blank"?e.condition.isBlank?"blank":"notBlank":e.condition.kind==="contains"?"contains":e.condition.kind==="between"?"between":e.condition.kind==="comparison"?e.condition.operator:"gt"}function RF(e){return e.condition.kind==="comparison"||e.condition.kind==="contains"?String(e.condition.value??""):e.condition.kind==="between"?String(e.condition.min??""):""}function Wxt(e){return e.condition.kind==="between"?String(e.condition.max??""):""}function qx(e){return typeof e=="number"&&Number.isFinite(e)?String(e):""}function Ux(e){if(!e.trim())return;const t=Number(e);return Number.isFinite(t)?t:void 0}function Kxt(e,t){const n=Number(e);return Number.isFinite(n)?n:t}function Gxt(e){var n;if(NT(e.condition.columnId))return"Select a trigger column";const t=e.condition;return t.kind==="comparison"?`${(((n=vpe.find(o=>o.value===t.operator))==null?void 0:n.label)??t.operator).toLowerCase()} ${t.value??""}`.trim():t.kind==="between"?`between ${t.min??"?"}...${t.max??"?"}`:t.kind==="contains"?`contains "${t.value??""}"`:t.kind==="blank"?t.isBlank?"is blank":"is not blank":t.kind==="topBottom"?`${t.direction} ${t.count}`:t.kind==="colorScale"?t.range==="manual"?`scale ${t.min??"auto"}...${t.max??"auto"}`:"scale (auto)":t.kind==="dataBar"?t.range==="manual"?`bar ${t.min??"auto"}...${t.max??"auto"}`:"bar (auto)":""}function Cpe(e){return NT(e.condition.columnId)?"":e.condition.columnId}function DK(e){const t=new Map;return e.forEach(n=>{const r=typeof n=="string"?{value:n,label:n}:n;!r.value||t.has(r.value)||t.set(r.value,{value:r.value,label:r.label||r.value})}),Array.from(t.values())}function Yxt(e,t){var r,o;const n=((o=(r=globalThis.crypto)==null?void 0:r.randomUUID)==null?void 0:o.call(r))??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`;return`cf-${e||"unassigned"}-${t}-${n}`}function Spe(e){return e.condition.kind==="colorScale"||e.condition.kind==="dataBar"}function Zxt(e){return e==="colorScale"||e==="dataBar"}function u0(e){if(NT(e.condition.columnId))return!1;switch(e.condition.kind){case"comparison":case"contains":return y2(e.condition.value);case"between":return y2(e.condition.min)&&y2(e.condition.max);case"blank":case"topBottom":return!0;case"colorScale":case"dataBar":return e.condition.range==="manual"?EK(e.condition.min)&&EK(e.condition.max):!0;default:return!1}}function wy(e,t){return u0(t)?e.enabled===!1&&!u0(e)&&u0(t)?{...t,enabled:!0}:t:{...t,enabled:!1}}function Xxt(e){return u0(e)?e:{...e,enabled:!1}}function t1({columnId:e,existingRule:t,index:n,kind:r="comparison",operator:o="gt",value:s="",conditionColumnId:i}){var m,g,b,x,y;const a=i??(t==null?void 0:t.condition.columnId)??e,c=NT(a),u=Zxt(r),d=c?"":u?a:e||a;if(!d&&!a)return;const f={id:(t==null?void 0:t.id)??Yxt(c?"unassigned":d||a,r),name:(t==null?void 0:t.name)??`${c?"New formatting":d||"New formatting"} rule ${n+1}`,enabled:(t==null?void 0:t.enabled)??!c,target:{level:"cell",columnIds:!u&&((m=t==null?void 0:t.target.columnIds)!=null&&m.length)?t.target.columnIds:d?[d]:void 0,applyToColumnIds:t==null?void 0:t.target.applyToColumnIds,tableParts:["body"]},style:{backgroundColor:((g=t==null?void 0:t.style)==null?void 0:g.backgroundColor)??"#fee2e2",textColor:((b=t==null?void 0:t.style)==null?void 0:b.textColor)??"#b91c1c",fontWeight:(x=t==null?void 0:t.style)==null?void 0:x.fontWeight,italic:(y=t==null?void 0:t.style)==null?void 0:y.italic}},h=w=>t?wy(t,w):Xxt(w);if(r==="topBottom"){const w=(t==null?void 0:t.condition.kind)==="topBottom"?t.condition:void 0;return h({...f,condition:{kind:"topBottom",columnId:a||la,direction:(w==null?void 0:w.direction)??"top",count:(w==null?void 0:w.count)??10}})}if(r==="colorScale"){const w=(t==null?void 0:t.condition.kind)==="colorScale"?t.condition:void 0;return h({...f,style:void 0,condition:{kind:"colorScale",columnId:a||la,range:(w==null?void 0:w.range)??"auto",min:w==null?void 0:w.min,mid:w==null?void 0:w.mid,max:w==null?void 0:w.max,colors:(w==null?void 0:w.colors)??{min:"#fee2e2",mid:"#fef3c7",max:"#dcfce7"}}})}if(r==="dataBar"){const w=(t==null?void 0:t.condition.kind)==="dataBar"?t.condition:void 0;return h({...f,style:void 0,condition:{kind:"dataBar",columnId:a||la,range:(w==null?void 0:w.range)??"auto",min:w==null?void 0:w.min,max:w==null?void 0:w.max,color:(w==null?void 0:w.color)??"#3b82f6",showValue:(w==null?void 0:w.showValue)!==!1}})}if(o==="blank"||o==="notBlank")return h({...f,condition:{kind:"blank",columnId:a||la,isBlank:o==="blank"}});if(o==="contains")return h({...f,condition:{kind:"contains",columnId:a||la,value:String(s??"")}});if(o==="between"){const w=(t==null?void 0:t.condition.kind)==="between"?t.condition:void 0;return h({...f,condition:{kind:"between",columnId:a||la,min:s,max:(w==null?void 0:w.max)??"",inclusive:(w==null?void 0:w.inclusive)!==!1}})}return h({...f,condition:{kind:"comparison",columnId:a||la,operator:o,value:s}})}const Qxt=[{value:"comparison",label:"Compare"},{value:"topBottom",label:"Top/Bot."},{value:"colorScale",label:"Scale"},{value:"dataBar",label:"Data bar"}],Jxt=[{name:"none",bg:void 0,text:void 0},{name:"red",bg:"#fee2e2",text:"#b91c1c"},{name:"amber",bg:"#fef3c7",text:"#92400e"},{name:"emerald",bg:"#dcfce7",text:"#15803d"},{name:"sky",bg:"#dbeafe",text:"#1d4ed8"},{name:"zinc",bg:"#f4f4f5",text:"#52525b"}],eyt=["#fb923c","#22c55e","#3b82f6","#a855f7","#ec4899","#71717a"],tyt={emerald:["#fee2e2","#fef3c7","#dcfce7"],sky:["#fee2e2","#fef3c7","#dbeafe"],rose:["#dcfce7","#fef3c7","#fee2e2"],zinc:["#fef2f2","#f4f4f5","#e4e4e7"]};function kp({value:e,onChange:t,options:n,ariaLabel:r}){return l.jsx("div",{role:"radiogroup","aria-label":r,className:"inline-flex h-7 w-fit max-w-full items-center rounded-[5px] border border-border/60 bg-background p-0.5",children:n.map(o=>{const s=o.value===e;return l.jsx("button",{type:"button",role:"radio","aria-checked":s,"aria-label":o.ariaLabel??String(o.label),disabled:o.disabled,onClick:()=>t(o.value),className:p.cn("inline-flex h-full items-center rounded-[4px] px-2 text-[11px] font-medium transition-colors",o.disabled?"cursor-not-allowed text-muted-foreground/40":s?"bg-foreground text-background":"text-muted-foreground hover:text-foreground"),children:o.label},o.value)})})}function nyt({value:e,onChange:t}){return l.jsx("div",{className:"flex items-center gap-1",children:Jxt.map(n=>{const r=(e??"none")===(n.bg??"none");return l.jsx("button",{type:"button",onClick:()=>t(n.bg,n.text),"aria-label":n.name,className:p.cn("flex h-6 w-6 items-center justify-center rounded-[4px] border transition-colors",r?"border-foreground":"border-border/60 hover:border-border"),style:{backgroundColor:n.bg??"transparent"},children:r&&l.jsx(p.Check,{className:"size-3",strokeWidth:3,style:{color:n.text??"currentColor"}})},n.name)})})}function ryt({value:e,onChange:t}){return l.jsx("div",{className:"flex items-center gap-1",children:Object.entries(tyt).map(([n,r])=>{const[o,s,i]=r,a=e.min===o&&e.max===i;return l.jsx("button",{type:"button","aria-label":n,onClick:()=>t({min:o,mid:s,max:i}),className:p.cn("flex h-6 w-7 items-center justify-center rounded-[4px] border transition-colors",a?"border-foreground":"border-border/60 hover:border-border"),style:{background:`linear-gradient(to right, ${o}, ${s}, ${i})`},children:a&&l.jsx(p.Check,{className:"size-3 text-foreground mix-blend-difference",strokeWidth:3,style:{color:"#fff"}})},n)})})}function oyt({value:e,onChange:t}){return l.jsx("div",{className:"flex items-center gap-1",children:eyt.map(n=>{const r=e===n;return l.jsx("button",{type:"button","aria-label":n,onClick:()=>t(n),className:p.cn("flex h-6 w-6 items-center justify-center rounded-[4px] border transition-colors",r?"border-foreground":"border-border/60 hover:border-border"),style:{backgroundColor:n},children:r&&l.jsx(p.Check,{className:"size-3 text-white",strokeWidth:3})},n)})})}function syt({rule:e}){var o,s;const t=e.condition;if(t.kind==="colorScale")return l.jsx("span",{"aria-hidden":!0,className:"inline-block h-3 w-7 shrink-0 rounded-[3px] border border-border/60",style:{background:`linear-gradient(to right, ${t.colors.min}, ${t.colors.mid??t.colors.max}, ${t.colors.max})`}});if(t.kind==="dataBar")return l.jsx("span",{"aria-hidden":!0,className:"relative inline-block h-3 w-7 shrink-0 overflow-hidden rounded-[3px] border border-border/60 bg-muted",children:l.jsx("span",{className:"absolute inset-y-0 left-0 w-3/5",style:{backgroundColor:t.color}})});const n=(o=e.style)==null?void 0:o.backgroundColor,r=(s=e.style)==null?void 0:s.textColor;return l.jsx("span",{"aria-hidden":!0,className:"inline-flex h-3 w-7 shrink-0 items-center justify-center rounded-[3px] border border-border/60 text-[8px] font-bold leading-none",style:{backgroundColor:n??"transparent",color:r??"currentColor"},children:"Aa"})}function Wx({label:e,children:t}){return l.jsxs("div",{className:"flex flex-col gap-1.5",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:e}),l.jsx("div",{className:"flex flex-col gap-1.5",children:t})]})}function Gr({label:e,htmlFor:t,children:n,align:r="center"}){return l.jsxs("div",{className:p.cn("flex gap-2",r==="start"?"items-start":"items-center"),children:[l.jsx("label",{htmlFor:t,className:p.cn("w-20 shrink-0 text-[11px] text-muted-foreground",r==="start"&&"pt-1.5"),children:e}),l.jsx("div",{className:"min-w-0 flex-1",children:n})]})}function Cl({value:e,onValueChange:t,commitDelayMs:n=250,onBlur:r,onKeyDown:o,...s}){const[i,a]=v.useState(e),c=v.useRef(e),u=v.useRef(t);v.useEffect(()=>{u.current=t},[t]),v.useEffect(()=>{c.current=e,a(e)},[e]);const d=v.useCallback(f=>{f!==c.current&&(c.current=f,v.startTransition(()=>{u.current(f)}))},[]);return v.useEffect(()=>{if(i===c.current)return;const f=window.setTimeout(()=>d(i),n);return()=>window.clearTimeout(f)},[n,d,i]),l.jsx(p.Input,{...s,value:i,onChange:f=>a(f.target.value),onBlur:f=>{d(f.currentTarget.value),r==null||r(f)},onKeyDown:f=>{f.key==="Enter"&&d(f.currentTarget.value),o==null||o(f)}})}function Npe({columnId:e,availableColumns:t=[],conditionalRules:n,onConditionalRulesChange:r,startRulesWithNoTrigger:o=!1}){const[s,i]=v.useState(()=>n.length===1?new Set([n[0].id]):new Set);if(v.useEffect(()=>{i(k=>{const T=new Set(n.map(D=>D.id));let I=!1;const E=new Set(k);for(const D of E)T.has(D)||(E.delete(D),I=!0);return I?E:k})},[n]),!r)return null;const a=k=>{i(T=>{const I=new Set(T);return I.has(k)?I.delete(k):I.add(k),I})},c=(k,T)=>{r(n.map((I,E)=>I.id===k?T(I,E):I))},u=()=>{const k=t1({columnId:e,index:n.length,kind:"comparison",conditionColumnId:o?la:void 0});k&&(i(T=>new Set(T).add(k.id)),r([...n,k]))},d=k=>{const T=n.findIndex(R=>R.id===k);if(T<0)return;const I=n[T],E={...I,id:`${I.id}-copy-${Date.now()}`,name:`${I.name??"Rule"} (copy)`},D=[...n];D.splice(T+1,0,E),i(R=>new Set(R).add(E.id)),r(D)},f=k=>{r(n.filter(T=>T.id!==k))},h=(k,T)=>{const I=n.findIndex(A=>A.id===k),E=I+T;if(I<0||E<0||E>=n.length)return;const D=[...n],[R]=D.splice(I,1);D.splice(E,0,R),r(D)},m=(k,T,I)=>{const E=t1({columnId:e,existingRule:k,index:I,kind:T});E&&r(n.map(D=>D.id===k.id?E:D))},g=(k,T,I)=>{r(n.map(E=>E.id===k.id?t1({columnId:e,existingRule:E,index:I,kind:"comparison",operator:T,value:RF(E)}):E))},b=(k,T,I)=>{r(n.map(E=>E.id===k.id?t1({columnId:e,existingRule:E,index:I,kind:"comparison",operator:wpe(E),value:T}):E))},x=(k,T)=>{c(k,I=>I.condition.kind==="between"?wy(I,{...I,condition:{...I.condition,max:T}}):I)},y=(k,T)=>{c(k,I=>({...I,style:{...I.style,...T}}))},w=(k,T)=>{c(k,I=>I.condition.kind==="topBottom"?{...I,condition:{...I.condition,...T,count:T.count!==void 0?Math.max(1,Math.floor(T.count)):I.condition.count}}:I)},C=(k,T)=>{c(k,I=>I.condition.kind==="colorScale"?wy(I,{...I,condition:{...I.condition,...T,colors:{...I.condition.colors,...T.colors}}}):I)},N=(k,T)=>{c(k,I=>I.condition.kind==="dataBar"?wy(I,{...I,condition:{...I.condition,...T}}):I)},S=(k,T)=>{c(k,I=>{const E={...I,target:I.target.level==="cell"?{...I.target,columnIds:[T]}:I.target,condition:{...I.condition,columnId:T}};return wy(I,E)})},j=(k,T)=>{c(k,I=>{var R,A,F;if(Spe(I)&&T==="row")return I;const E=Cpe(I),D=((R=I.target.columnIds)==null?void 0:R[0])||E||void 0;return{...I,target:T==="row"?{...I.target,level:"row",columnIds:void 0,applyToColumnIds:I.target.applyToColumnIds,tableParts:(A=I.target.tableParts)!=null&&A.length?I.target.tableParts:["body"]}:{...I.target,level:"cell",columnIds:D?[D]:void 0,applyToColumnIds:void 0,tableParts:(F=I.target.tableParts)!=null&&F.length?I.target.tableParts:["body"]}}})},_=n.filter(k=>k.enabled!==!1).length;return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Conditional formatting"}),n.length>0&&l.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[_," enabled · ",n.length," total"]})]}),l.jsxs(p.Button,{type:"button",variant:"ghost",size:"xs",disabled:!e,onClick:u,className:"h-6 gap-1 px-2 text-[12px]",children:[l.jsx(Tr,{className:"size-3"}),"Add rule"]})]}),n.length===0?l.jsx("p",{className:"py-6 text-center text-[12px] text-muted-foreground",children:"No conditional formatting rules for this column."}):l.jsx("ol",{className:"overflow-hidden rounded-[6px] border border-border/60",children:n.map((k,T)=>{const I=s.has(k.id);return l.jsxs("li",{className:"border-b border-border/60 bg-background last:border-b-0",children:[l.jsx(iyt,{rule:k,index:T,expanded:I,isFirst:T===0,isLast:T===n.length-1,onToggleExpand:()=>a(k.id),onToggleEnabled:E=>c(k.id,D=>E&&!u0(D)?D:{...D,enabled:E}),onMoveUp:()=>h(k.id,-1),onMoveDown:()=>h(k.id,1),onDuplicate:()=>d(k.id),onDelete:()=>f(k.id)}),I&&l.jsx(ayt,{rule:k,index:T,onUpdateName:E=>c(k.id,D=>({...D,name:E})),onUpdateRuleKind:E=>m(k,E,T),onUpdateConditionalOperator:E=>g(k,E,T),onUpdateConditionalValue:E=>b(k,E,T),onUpdateConditionalMaxValue:E=>x(k.id,E),onUpdateStyle:E=>y(k.id,E),onUpdateTopBottom:E=>w(k.id,E),onUpdateColorScale:E=>C(k.id,E),onUpdateDataBar:E=>N(k.id,E),availableColumns:t,onUpdateConditionColumn:E=>S(k.id,E),onUpdateTargetLevel:E=>j(k.id,E)})]},k.id)})})]})}function iyt({rule:e,index:t,expanded:n,isFirst:r,isLast:o,onToggleExpand:s,onToggleEnabled:i,onMoveUp:a,onMoveDown:c,onDuplicate:u,onDelete:d}){const f=Gxt(e),h=e.enabled!==!1;return l.jsxs("div",{className:p.cn("flex items-stretch gap-1 px-2 py-1.5 transition-colors",n?"bg-muted/40 shadow-[inset_2px_0_0] shadow-foreground":"hover:bg-muted/40"),children:[l.jsxs("div",{className:"flex shrink-0 flex-col items-center gap-0.5 pt-1 text-muted-foreground",children:[l.jsx("button",{type:"button","aria-label":`Move rule ${t+1} up`,disabled:r,onClick:a,className:"rounded-[3px] p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-30 disabled:hover:bg-transparent",children:l.jsx(bs,{className:"size-3"})}),l.jsx("button",{type:"button","aria-label":`Move rule ${t+1} down`,disabled:o,onClick:c,className:"rounded-[3px] p-0.5 text-muted-foreground hover:bg-foreground/10 hover:text-foreground disabled:opacity-30 disabled:hover:bg-transparent",children:l.jsx(es,{className:"size-3"})})]}),l.jsx("button",{type:"button",onClick:s,"aria-expanded":n,"aria-label":`${n?"Collapse":"Expand"} rule ${t+1}`,className:"flex min-w-0 flex-1 items-start py-0.5 text-left",children:l.jsxs("span",{className:"min-w-0 flex-1",children:[l.jsxs("span",{className:"flex items-center gap-2",children:[l.jsxs("span",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground",children:["#",t+1]}),l.jsx("span",{className:p.cn("truncate text-[12px] font-medium",h?"text-foreground":"text-muted-foreground line-through"),children:e.name??`Rule ${t+1}`})]}),l.jsxs("span",{className:"mt-0.5 flex flex-wrap items-center gap-1.5",children:[l.jsx(syt,{rule:e}),l.jsx("span",{className:"truncate text-[11px] text-muted-foreground",children:f})]})]})}),l.jsxs("div",{className:"flex shrink-0 items-start gap-1 pt-1",children:[l.jsx(p.Switch,{size:"xs","aria-label":h?`Disable rule ${t+1}`:`Enable rule ${t+1}`,checked:h,onCheckedChange:i}),l.jsxs(Uo,{children:[l.jsx(Wo,{asChild:!0,children:l.jsx("button",{type:"button","aria-label":`Rule ${t+1} actions`,className:"inline-flex h-4 w-4 items-center justify-center rounded-[4px] text-muted-foreground hover:bg-muted hover:text-foreground",children:l.jsx(Rm,{className:"size-3"})})}),l.jsxs(Do,{align:"end",className:"min-w-[140px]",children:[l.jsxs(kn,{className:"gap-2 text-[12px]",onClick:u,children:[l.jsx(Jh,{className:"size-3"}),"Duplicate"]}),l.jsxs(kn,{className:"gap-2 text-[12px] text-destructive focus:text-destructive",onClick:d,children:[l.jsx(el,{className:"size-3"}),"Delete"]})]})]})]})]})}function ayt({rule:e,index:t,availableColumns:n,onUpdateName:r,onUpdateConditionColumn:o,onUpdateTargetLevel:s,onUpdateRuleKind:i,onUpdateConditionalOperator:a,onUpdateConditionalValue:c,onUpdateConditionalMaxValue:u,onUpdateStyle:d,onUpdateTopBottom:f,onUpdateColorScale:h,onUpdateDataBar:m}){var N,S,j,_;const g=Uxt(e),b=wpe(e),x=e.id,y=Cpe(e),w=DK(n),C=!Spe(e);return l.jsxs("div",{className:"space-y-3 border-t border-border/60 bg-muted/20 px-3 py-3",children:[l.jsx(Gr,{label:"Name",htmlFor:`cf-name-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-name-${x}`,value:e.name??"",onValueChange:r,className:`w-full ${p.removeRing}`,placeholder:`Rule ${t+1}`})}),l.jsxs(Wx,{label:"Target",children:[l.jsxs(Gr,{label:"Target",children:[l.jsx(kp,{ariaLabel:"Formatting target",value:e.target.level,onChange:s,options:[{value:"cell",label:"Cell"},{value:"row",label:"Row",ariaLabel:C?"Row":"Row target is not available for this rule type",disabled:!C}]}),!C&&l.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"Color scales and data bars format cells because their values are column-specific."})]}),l.jsx(Gr,{label:"Trigger",htmlFor:`cf-trigger-${x}`,children:l.jsxs(p.Select,{value:y||"",onValueChange:o,children:[l.jsx(p.SelectTrigger,{size:"xs",id:`cf-trigger-${x}`,className:`w-full ${p.simpleRing}`,children:l.jsx(p.SelectValue,{placeholder:""})}),l.jsx(p.SelectContent,{children:(w.length?w:DK([y])).filter(k=>!!k.value).map(k=>l.jsx(p.SelectItem,{value:k.value,children:k.label},k.value))})]})})]}),l.jsxs(Wx,{label:"Condition",children:[l.jsx(kp,{ariaLabel:"Rule type",value:g,onChange:i,options:Qxt}),g==="comparison"&&l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Operator",htmlFor:`cf-operator-${x}`,children:l.jsxs(p.Select,{value:b,onValueChange:k=>a(k),children:[l.jsx(p.SelectTrigger,{size:"xs",id:`cf-operator-${x}`,className:`w-full ${p.simpleRing}`,children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:vpe.map(k=>l.jsx(p.SelectItem,{value:k.value,children:k.label},k.value))})]})}),b==="between"?l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Min",htmlFor:`cf-value-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-value-${x}`,"aria-label":"Value",value:RF(e),onValueChange:c,className:`w-full ${p.removeRing}`,placeholder:"Minimum…"})}),l.jsx(Gr,{label:"Max",htmlFor:`cf-max-value-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-max-value-${x}`,value:Wxt(e),onValueChange:u,className:`w-full ${p.removeRing}`,placeholder:"Maximum…"})})]}):b!=="blank"&&b!=="notBlank"?l.jsx(Gr,{label:"Value",htmlFor:`cf-value-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-value-${x}`,value:RF(e),onValueChange:c,className:`w-full ${p.removeRing}`,placeholder:b==="contains"?"Text to match…":"Value…"})}):null]}),e.condition.kind==="topBottom"&&l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Direction",children:l.jsx(kp,{ariaLabel:"Direction",value:e.condition.direction,onChange:k=>f({direction:k}),options:[{value:"top",label:"Top"},{value:"bottom",label:"Bottom"}]})}),l.jsx(Gr,{label:"Count",htmlFor:`cf-count-${x}`,children:l.jsx(Cl,{size:"xs",id:`cf-count-${x}`,type:"number",min:1,value:String(e.condition.count),onValueChange:k=>f({count:Kxt(k,1)}),className:`w-full ${p.removeRing}`})})]}),e.condition.kind==="colorScale"&&l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Range",children:l.jsx(kp,{ariaLabel:"Range",value:e.condition.range,onChange:k=>h({range:k}),options:[{value:"auto",label:"Auto"},{value:"manual",label:"Manual"}]})}),e.condition.range==="manual"&&l.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[l.jsx(Cl,{size:"xs",type:"number","aria-label":"Min",placeholder:"Min",value:qx(e.condition.min),onValueChange:k=>h({min:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`}),l.jsx(Cl,{size:"xs",type:"number","aria-label":"Mid",placeholder:"Mid",value:qx(e.condition.mid),onValueChange:k=>h({mid:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`}),l.jsx(Cl,{size:"xs",type:"number","aria-label":"Max",placeholder:"Max",value:qx(e.condition.max),onValueChange:k=>h({max:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`})]}),l.jsx(Gr,{label:"Palette",children:l.jsx(ryt,{value:e.condition.colors,onChange:k=>h({colors:k})})})]}),e.condition.kind==="dataBar"&&l.jsxs(l.Fragment,{children:[l.jsx(Gr,{label:"Range",children:l.jsx(kp,{ariaLabel:"Range",value:e.condition.range,onChange:k=>m({range:k}),options:[{value:"auto",label:"Auto"},{value:"manual",label:"Manual"}]})}),e.condition.range==="manual"&&l.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[l.jsx(Cl,{size:"xs",type:"number","aria-label":"Min",placeholder:"Min",value:qx(e.condition.min),onValueChange:k=>m({min:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`}),l.jsx(Cl,{size:"xs",type:"number","aria-label":"Max",placeholder:"Max",value:qx(e.condition.max),onValueChange:k=>m({max:Ux(k)}),className:`w-full text-right tabular-nums ${p.removeRing}`})]}),l.jsx(Gr,{label:"Show value",children:l.jsx(p.Switch,{size:"xs","aria-label":"Show cell value on data bar",checked:e.condition.showValue!==!1,onCheckedChange:k=>m({showValue:k})})})]})]}),(g==="comparison"||e.condition.kind==="topBottom")&&l.jsxs(Wx,{label:"Format",children:[l.jsx(Gr,{label:"Preset",children:l.jsx(nyt,{value:(N=e.style)==null?void 0:N.backgroundColor,onChange:(k,T)=>d({backgroundColor:k,textColor:T})})}),l.jsx(Gr,{label:"Fill",htmlFor:`cf-fill-${x}`,children:l.jsx(da,{id:`cf-fill-${x}`,ariaLabel:"Fill Color",value:((S=e.style)==null?void 0:S.backgroundColor)||void 0,onChange:k=>d({backgroundColor:k}),defaultValue:"#fee2e2"})}),l.jsx(Gr,{label:"Text",htmlFor:`cf-text-${x}`,children:l.jsx(da,{id:`cf-text-${x}`,ariaLabel:"Text Color",value:((j=e.style)==null?void 0:j.textColor)||void 0,onChange:k=>d({textColor:k}),defaultValue:"#b91c1c"})}),l.jsx(Gr,{label:"Weight",children:l.jsx(kp,{ariaLabel:"Font weight",value:((_=e.style)==null?void 0:_.fontWeight)??"normal",onChange:k=>d({fontWeight:k==="normal"?void 0:k}),options:[{value:"normal",label:"R",ariaLabel:"Regular"},{value:"medium",label:"M",ariaLabel:"Medium"},{value:"bold",label:"B",ariaLabel:"Bold"}]})})]}),e.condition.kind==="colorScale"&&l.jsxs(Wx,{label:"Colors",children:[l.jsx(Gr,{label:"Low",htmlFor:`cf-low-color-${x}`,children:l.jsx(da,{id:`cf-low-color-${x}`,ariaLabel:"Low color",value:e.condition.colors.min,onChange:k=>h({colors:{min:k??"#fee2e2"}}),defaultValue:"#fee2e2",allowEmpty:!1})}),l.jsx(Gr,{label:"Mid",htmlFor:`cf-mid-color-${x}`,children:l.jsx(da,{id:`cf-mid-color-${x}`,ariaLabel:"Mid color",value:e.condition.colors.mid||void 0,onChange:k=>h({colors:{mid:k}}),defaultValue:"#fef3c7"})}),l.jsx(Gr,{label:"High",htmlFor:`cf-high-color-${x}`,children:l.jsx(da,{id:`cf-high-color-${x}`,ariaLabel:"High color",value:e.condition.colors.max,onChange:k=>h({colors:{max:k??"#dcfce7"}}),defaultValue:"#dcfce7",allowEmpty:!1})})]}),e.condition.kind==="dataBar"&&l.jsxs(Wx,{label:"Bar color",children:[l.jsx(Gr,{label:"Preset",children:l.jsx(oyt,{value:e.condition.color,onChange:k=>m({color:k})})}),l.jsx(Gr,{label:"Color",htmlFor:`cf-bar-color-${x}`,children:l.jsx(da,{id:`cf-bar-color-${x}`,ariaLabel:"Bar color",value:e.condition.color,onChange:k=>m({color:k??"#3b82f6"}),defaultValue:"#3b82f6",allowEmpty:!1})})]})]})}function lyt({field:e,dataSource:t,connectionId:n,connectionType:r,filterId:o}){var f,h;const{qualifiedColumnName:s,qualifiedTableName:i}=Khe(e),a=p.getDataType(e.dataType),c=a==="date"?"between":"in",u=Kz(e),d=Gz(t,{connectionId:n,connectionType:r});return{id:o||dt.v4(),title:e.label||e.name,connectionId:n||(t==null?void 0:t.connectionId)||"",column:s,dataType:e.dataType,table:e.entityName||"",database:((h=(f=t==null?void 0:t.selectedEntities)==null?void 0:f[0])==null?void 0:h.database)||"",qualifiedTableName:i,operation:c,sql:"",fieldMeta:u,semanticContext:d,...a==="date"?{dateSelectionMode:"range"}:{type:"single"}}}function cyt(e,t){return e.kind==="filter"&&rb(e.filter,t)}function jT(e){return p.getDataType(e.dataType)==="date"?["label","start","end","range"]:["label","value"]}function jpe(e){return uyt(e)?["label","value"]:["value"]}function uyt(e){return e.type==="enum"||e.type==="multi_enum"||e.type==="field_selector"||e.type==="metric_selector"||e.type==="aggregation_selector"||e.type==="grain_selector"}function rx(e,t){return(e.inputs||[]).filter(n=>Qh(n,{sheetId:t,sheetKind:"document"}))}function kpe(e,t){const n=dyt(e,t);return(e.inputs||[]).some(r=>Qh(r,{sheetId:t,sheetKind:"document"})||r.scope.kind==="documentSections"&&r.scope.sheetId===t||r.scope.kind==="cards"&&r.scope.cardIds.some(o=>n.has(o)))}function dyt(e,t){var o,s,i;const n=new Set,r=(o=e.sheets)==null?void 0:o.find(a=>a.id===t);for(const a of((s=r==null?void 0:r.document)==null?void 0:s.sections)||[])(a.type==="table"||a.type==="chart")&&((i=a.card)!=null&&i.id)&&n.add(a.card.id);return n}function lC(e){const t={id:e.id,label:e.label,variableName:e.variableName,requiredAtExecution:!!e.requiredAtExecution,documentPlacement:"input_bar",description:e.description};return e.kind==="filter"?{...t,kind:"filter",filter:e.filter,exports:e.exports}:{...t,kind:"control",control:e.control,exports:e.exports}}function fyt({field:e,existingInputs:t,sheetId:n,dataSource:r,connectionId:o,connectionType:s,inputId:i,filterId:a}){const c=e.label||e.name,u=lyt({field:e,dataSource:r,connectionId:o,connectionType:s,filterId:a}),d=bO(c,t);return{id:i||dt.v4(),kind:"filter",label:c,variableName:d,requiredAtExecution:!1,scope:{kind:"sheets",sheetIds:[n]},runtimeScope:"perSheet",presentation:{placement:"toolbar"},filter:{...u,variableName:d},exports:jT(u)}}function hyt({control:e,existingInputs:t,sheetId:n,inputId:r}){const o=Od(e.id||e.label,t),s=e.id===o?e:{...e,id:o};return{id:r||dt.v4(),kind:"control",label:s.label,variableName:o,requiredAtExecution:s.requiredAtExecution,scope:{kind:"sheets",sheetIds:[n]},runtimeScope:"perSheet",presentation:{placement:"toolbar"},control:s,exports:jpe(s)}}function AF({input:e,allInputs:t,label:n,variableName:r}){const o=(n==null?void 0:n.trim())||e.label,s=r===void 0?e.variableName:Od(r,t.filter(a=>a.id!==e.id));if(e.kind==="filter"){const a={...e.filter,title:o,variableName:s};return{...e,label:o,variableName:s,filter:a,exports:jT(a)}}const i={...e.control,id:s,label:o};return{...e,label:o,variableName:s,requiredAtExecution:i.requiredAtExecution,control:i,exports:jpe(i)}}function PF(e,t,n){return!t||!n||t===n?e:{...e,sections:e.sections.map(r=>r.type!=="table"&&r.type!=="chart"||!r.card?r:{...r,card:myt(r.card,t,n)})}}function myt(e,t,n){var s;const r=`[[param.${t}]]`,o=`[[param.${n}]]`;return{...e,...(s=e.sql)!=null&&s.includes(r)?{sql:e.sql.split(r).join(o)}:{},...e.controls?{controls:e.controls.map(i=>i.id===t?{...i,id:n}:i)}:{},...e.controlBindings?{controlBindings:e.controlBindings.map(i=>({...i,controlId:i.controlId===t?n:i.controlId,...i.target==="sql_param"&&i.paramId===t?{paramId:n}:{}}))}:{}}}function pyt(e,t){return e.kind==="filter"&&cyt(lC(e),t)}function gyt(e){var n;const t={};for(const r of e)r.kind==="filter"&&(t[r.id]=((n=r.slot)==null?void 0:n.status)==="cleared"?void 0:r.filterValue);return t}function byt(e){var n;const t={};for(const r of e)r.kind==="control"&&((n=r.slot)==null?void 0:n.status)==="set"&&(t[r.id]=r.controlValue);return t}function xyt({dashboard:e,sheetId:t,filterValuesByInputId:n,controlValuesByInputId:r}){var i;const o=rx(e,t);let s={};for(const a of o)if(((i=a.compatibility)==null?void 0:i.source)==="documentInput"){if(a.kind==="filter"&&n&&Object.prototype.hasOwnProperty.call(n,a.id)){const c=n[a.id];s=p.setDashboardInputRuntimeSlot(s,a,{sheetId:t},c?{status:"set",value:{kind:"filter",filterValue:c}}:{status:"cleared"})}if(a.kind==="control"&&r&&Object.prototype.hasOwnProperty.call(r,a.id)){const c=r[a.id];s=p.setDashboardInputRuntimeSlot(s,a,{sheetId:t},c===void 0?{status:"cleared"}:{status:"set",value:{kind:"control",value:c}})}}return dR({dashboard:e,dashboardInputValues:s,sheetId:t})}const yyt=[],vyt={},wyt={},Cyt={};function Syt(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Nyt({sheet:e}){var sn;const n=p.useDashboardStore(Le=>{var et,at,ht;return(ht=(at=(et=Le.dashboard)==null?void 0:et.sheets)==null?void 0:at.find(Vt=>Vt.id===e.id))==null?void 0:ht.document})||e.document||p.createDefaultDocumentDefinition(),r=p.useDashboardStore(Le=>Le.dashboard),o=p.useDashboardStore(Le=>Le.dashboardInputValues),s=p.useDashboardStore(Le=>Le.filterValues),i=p.useDashboardStore(Le=>Le.controlValues),a=p.useDashboardStore(Le=>Le.inlineFilterValuesMap),c=p.useDashboardStore(Le=>Le.cardControlValuesMap),u=v.useMemo(()=>rx(r,e.id),[r,e.id]),d=u.length>0,f=v.useMemo(()=>kpe(r,e.id),[r,e.id]),h=v.useMemo(()=>d?u.map(lC):n.inputs||yyt,[n.inputs,u,d]),m=v.useMemo(()=>new Map(u.map(Le=>[Le.id,Le])),[u]),g=v.useMemo(()=>h.filter(Ql).map(Le=>Le.control),[h]),{authToken:b,tokenProps:x,documentInputValues:y,dashboardInputExecutionSnapshot:w,renderMode:C}=It(),{displayPreferences:N}=cl(),S=dl()??void 0,j=p.useDashboardStore(Le=>Le.isDashboardEditing),_=p.useDashboardStore(Le=>Le.isDownloadingPdf),k=eee({displayMode:N.mode,renderMode:C}),T=k?"print":j?"edit":"view",{updateSheetDocument:I,setSelectedDocumentSectionId:E,setDocumentInspectorTab:D,setDocumentInputFilterValues:R,setDocumentInputFilterValue:A,setDocumentInputFilterModes:F,setDocumentInputFilterMode:z,removeDocumentInputFilterValue:L,setDocumentInputControlValues:$,setDocumentInputControlValue:H,upsertDashboardInput:M,removeDashboardInput:B,setDashboardInputSlot:W,clearDashboardInputSlot:P}=p.useDashboardActions(),G=p.useDashboardStore(Le=>Le.documentInspectorTabsBySheetId[e.id]||"page"),Z=Gpt(),[X,Y]=v.useState(null),[O,q]=v.useState(null),[U,V]=v.useState("edit"),[K,Q]=v.useState({pageNumber:1,pageCount:1}),[se,oe]=v.useState({}),[me,le]=v.useState(!1),ue=Wr(),[ne,de]=v.useState(100),Ce=p.useDashboardStore(Le=>Le.documentInputRuntimeBySheetId[e.id]),ce=v.useMemo(()=>Cme(h,S),[h,S]),ie=v.useMemo(()=>Sme(h),[h]),we=y!=null&&y.sheetId&&y.sheetId!==e.id?void 0:y,fe=we==null?void 0:we.filterValuesByInputId,ae=we==null?void 0:we.controlValuesByInputId,ee=v.useMemo(()=>!w&&we?xyt({dashboard:r,sheetId:e.id,filterValuesByInputId:fe,controlValuesByInputId:ae}):void 0,[w,r,ae,we,fe,e.id]),J=v.useMemo(()=>Rpt(h),[h]),re=v.useMemo(()=>Nme(h),[h]),pe=v.useRef(re),Ee=v.useMemo(()=>Yi({dashboard:r,sheetId:e.id,sheetKind:"document",runtimeValues:{...ee?{dashboardInputValues:ee}:{dashboardInputValues:o},filterValues:s,controlValues:i,inlineFilterValuesMap:a,cardControlValuesMap:c},mode:k?"print":"interactive",timezone:S}),[r,c,i,s,a,o,S,k,ee,e.id]),Te=v.useMemo(()=>gyt(Ee.resolvedInputs),[Ee.resolvedInputs]),ze=v.useMemo(()=>byt(Ee.resolvedInputs),[Ee.resolvedInputs]),Pe=v.useMemo(()=>d?Te:we?fe||vyt:(Ce==null?void 0:Ce.filterValuesByInputId)||ce,[ce,Te,we,fe,d,Ce==null?void 0:Ce.filterValuesByInputId]),He=v.useMemo(()=>d?Uyt(h,Te):(Ce==null?void 0:Ce.filterModesByInputId)||wyt,[Te,h,d,Ce==null?void 0:Ce.filterModesByInputId]),ye=v.useMemo(()=>d?ze:we?ae||Cyt:(Ce==null?void 0:Ce.controlValuesByInputId)||ie,[ie,ze,ae,we,d,Ce==null?void 0:Ce.controlValuesByInputId]),[Ke,We]=v.useState({}),[Qe,xe]=v.useState((w==null?void 0:w.generatedAt)||(we==null?void 0:we.generatedAt)||new Date().toISOString()),Ve=v.useMemo(()=>n.sections.find(Le=>Le.type==="table")||null,[n.sections]),Ae=v.useMemo(()=>n.sections.find(Le=>Le.id===X)||null,[n.sections,X]),ke=(Ae==null?void 0:Ae.type)==="table"?Ae:Ve,Be=(ke==null?void 0:ke.id)||X||null;v.useEffect(()=>{E(e.id,Be)},[Be,E,e.id]),v.useEffect(()=>{const Le=pe.current;if(we){we.generatedAt&&xe(et=>et===we.generatedAt?et:we.generatedAt),pe.current=re;return}d||(R(e.id,Apt(Pe,h,ce,re,Le)),$(e.id,Ppt(ye,h,ie,re,Le))),pe.current=re},[ye,J,Pe,h,ce,ie,re,we,d,$,R,e.id]),v.useEffect(()=>{d||F(e.id,Opt(He,h))},[He,J,h,d,F,e.id]);const Ie=v.useCallback((Le,et)=>{const at=h.find(Xn=>Xn.id===Le),ht=at&&cc(at)?gv(at,et):et;if(!ht)return;const Vt=m.get(Le);if(Vt){W(Vt,{sheetId:e.id},{status:"set",value:{kind:"filter",filterValue:ht}});return}A(e.id,Le,ht)},[m,h,W,A,e.id]),$e=v.useCallback((Le,et)=>{const at=h.find(Xn=>Xn.id===Le),ht=m.get(Le);ht||z(e.id,Le,et);const Vt=at&&cc(at)?gv(at,Pe[Le]):Pe[Le];if(!(!Vt||!vT(Vt.operation))){if(ht){W(ht,{sheetId:e.id},{status:"set",value:{kind:"filter",filterValue:{...Vt,operation:DF(et)}}});return}A(e.id,Le,{...Vt,operation:DF(et)})}},[Pe,h,m,W,z,A,e.id]),st=v.useCallback(Le=>{const et=m.get(Le);if(et){P(et,{sheetId:e.id});return}L(e.id,Le)},[P,m,L,e.id]),ct=v.useCallback((Le,et,at)=>{const ht=m.get(Le);if((ht==null?void 0:ht.kind)==="filter"){M(AF({input:{...ht,label:et.title||ht.label,filter:et,exports:jT(et)},allInputs:r.inputs||[],label:et.title||ht.label,variableName:at==null?void 0:at.variableName}));return}I(e.id,Vt=>Hyt(Vt,Le,et,at))},[r.inputs,m,e.id,I,M]),rt=v.useCallback((Le,et)=>{const at=m.get(Le);if((at==null?void 0:at.kind)==="control"){const ht=AF({input:{...at,requiredAtExecution:et.requiredAtExecution,control:et},allInputs:r.inputs||[],label:et.label||at.label,variableName:et.id||at.variableName});M(ht),ht.kind==="control"&&at.control.id!==ht.control.id&&I(e.id,Vt=>PF(Vt,at.control.id,ht.control.id));return}I(e.id,ht=>{const Vt=(ht.inputs||[]).find(Go=>Go.id===Le&&Ql(Go)),Xn=qyt(ht,Le,et);return Vt&&Vt.control.id!==et.id?PF(Xn,Vt.control.id,et.id):Xn})},[r.inputs,m,e.id,I,M]),Ct=v.useCallback(Le=>{if(m.has(Le)){B(Le);return}I(e.id,et=>({...et,inputs:(et.inputs||[]).filter(at=>at.id!==Le)}))},[m,B,e.id,I]),Lt=v.useCallback((Le,et)=>{const at=m.get(Le);if(at){if(et===void 0){P(at,{sheetId:e.id});return}W(at,{sheetId:e.id},{status:"set",value:{kind:"control",value:et}});return}H(e.id,Le,et)},[P,m,W,H,e.id]),vt=v.useCallback((Le,et)=>{We(at=>Kyt(at[Le]||[],et)?at:{...at,[Le]:et})},[]);v.useEffect(()=>{const Le=new Set(h.filter(Ql).map(et=>et.id));We(et=>{const at=Object.fromEntries(Object.entries(et).filter(([ht])=>Le.has(ht)));return Object.keys(at).length===Object.keys(et).length?et:at})},[h]);const Tt=v.useMemo(()=>d?Ee.activeFilters:Bpt(Pe,h,re,pe.current),[Ee.activeFilters,Pe,h,re,d]),Me=v.useMemo(()=>d?Ee.controlValues:Vpt(ye,h,re,pe.current),[Ee.controlValues,ye,h,re,d]),Je=v.useMemo(()=>d?Ee.missingRequiredInputs.map(Le=>Le.label):_me(h,Pe,ye,re,pe.current),[Ee.missingRequiredInputs,h,Pe,ye,re,d]),kt=v.useMemo(()=>f?YY({dashboard:r,sheetId:e.id,sheetKind:"document",sectionIds:n.sections.map(Le=>Le.id),mode:"document",runtimeValues:{dashboardInputValues:o,filterValues:s,controlValues:i,inlineFilterValuesMap:a,cardControlValuesMap:c},timezone:S}):Je,[r,c,i,s,a,o,n.sections,S,f,Je,e.id]),mt=v.useMemo(()=>{var Le;return hpt({inputs:h,filterValuesByInputId:Pe,controlValuesByInputId:ye,controlOptionsByInputId:Ke,generatedAt:Qe,timezone:S,generatedAtFormat:(Le=n.runtime)==null?void 0:Le.generatedAtFormat})},[h,Pe,ye,Ke,Qe,S,(sn=n.runtime)==null?void 0:sn.generatedAtFormat]),_t=v.useCallback(Le=>{I(e.id,Le)},[e.id,I]),Rt=v.useCallback(Le=>D(e.id,Le),[D,e.id]),Pt=v.useCallback((Le,et,at)=>{oe(ht=>{const Vt=ht[Le];if(et.length===0){if((Vt==null?void 0:Vt.schemaSignature)===at||!Vt)return ht;const Xn={...ht};return delete Xn[Le],Xn}return(Vt==null?void 0:Vt.schemaSignature)===at&&Syt(Vt.columns,et)?ht:{...ht,[Le]:{schemaSignature:at,columns:et}}})},[]),wt=(Le,et={})=>{Y(Le),!Le&&G==="section"?Rt("page"):Le&&et.activateSectionInspector!==!1&&Rt("section"),q(null)},Et=(Le,et)=>{const at=jpt(Le);_t(ht=>({...ht,sections:[...ht.sections.slice(0,et),at,...ht.sections.slice(et)]})),Y(at.id),Rt("section"),q(null),at.type==="table"&&Z(e.id,at)},Bt=Le=>{X&&_t(et=>({...et,sections:et.sections.map(at=>at.id===X?Le(at):at)}))},un=()=>{X&&Ge(X)},Ge=Le=>{var ht;const et=Le===X,at=n.sections.filter(Vt=>Vt.id!==Le);_t(Vt=>({...Vt,sections:Vt.sections.filter(Xn=>Xn.id!==Le)})),et&&(Y(((ht=at[0])==null?void 0:ht.id)||null),Rt(at[0]?"section":"page"))},Re=(Le,et,at)=>{Le!==et&&(_t(ht=>{const Vt=ht.sections.findIndex(Qi=>Qi.id===Le),Xn=ht.sections.findIndex(Qi=>Qi.id===et);if(Vt===-1||Xn===-1)return ht;const Go=[...ht.sections],[Rs]=Go.splice(Vt,1),Lr=at==="after"?Xn+1:Xn,Co=Vt<Lr?Lr-1:Lr;return Go.splice(Math.min(Co,Go.length),0,Rs),{...ht,sections:Go}}),Y(Le))},De=Le=>{_t(et=>({...et,page:Le}))},he=v.useCallback((Le,et)=>{_t(at=>({...at,sections:at.sections.map(ht=>ht.id===Le&&ht.type==="table"?et(ht):ht)}))},[_t]),Fe=Le=>{_t(et=>({...et,header:Le(et.header)}))},ot=Le=>{_t(et=>({...et,footer:Le(et.footer)}))},Dt=v.useCallback(Le=>{Z(e.id,Le,Tt,g,Me,Je)},[g,Me,Tt,Je,Z,e.id]),nt=v.useCallback(async()=>{if(!(x!=null&&x.apiServiceUrl)||!b){lt.error("Unable to export document PDF without an active session");return}if(kt.length>0){lt.error(`Set ${kt.join(", ")} before exporting`);return}const Le=new Date().toISOString(),et=f?ZY({dashboard:r,sheetId:e.id,sheetKind:"document",sectionIds:n.sections.map(ht=>ht.id),mode:"document",runtimeValues:{dashboardInputValues:o,filterValues:s,controlValues:i,inlineFilterValuesMap:a,cardControlValuesMap:c},generatedAt:Le,timezone:S}).snapshot:void 0,at=lt.loading("Generating document PDF...");try{await Q5(x.apiServiceUrl,b,{sheetId:e.id,title:e.title||"Document",pageSize:n.page.size,orientation:n.page.orientation,timezone:S,inputSnapshot:et,...et?{}:{inputValues:{sheetId:e.id,filterValuesByInputId:Pe,controlValuesByInputId:ye,generatedAt:Le}}}),lt.dismiss(at),lt.success("Document PDF downloaded")}catch(ht){lt.dismiss(at),lt.error("Failed to export document PDF",{description:j_(ht,"Please try again or contact support."),descriptionClassName:N_,closeButton:!0,duration:1/0}),console.error("Document PDF export error:",ht)}},[b,n.page.orientation,n.page.size,n.sections,r,c,i,s,a,o,ye,Pe,S,kt,f,e.id,e.title,x==null?void 0:x.apiServiceUrl]),ge=l.jsxs("button",{type:"button",disabled:_||kt.length>0,onClick:nt,title:kt.length>0?`Set ${kt.join(", ")} before exporting`:void 0,className:p.cn(v2,"disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"),children:[_?l.jsx(p.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}):l.jsx(Su,{className:"h-3.5 w-3.5"}),"Export"]}),Se=U==="preview",Oe=l.jsx("button",{type:"button",onClick:()=>{Se?V("edit"):(V("preview"),q(null))},"aria-pressed":Se,className:p.cn(v2,Se?"bg-primary text-primary-foreground hover:bg-primary/90":"text-foreground hover:bg-muted"),children:Se?"Exit preview":"Show preview"}),Ye=v.useCallback(Le=>{Q(et=>{const at=Math.max(1,et.pageCount),ht=Math.min(at,Math.max(1,Math.round(Le)));return et.pageNumber===ht?et:{...et,pageNumber:ht}})},[]),bt=v.useCallback(Le=>{Q(et=>{const at=Math.max(et.pageCount,Le,1),ht=Math.min(et.pageNumber,at);return et.pageNumber===ht&&et.pageCount===at?et:{pageNumber:ht,pageCount:at}})},[]),St=v.useCallback(async()=>{le(!0),xe(new Date().toISOString());try{await ue.invalidateQueries({refetchType:"active",predicate:Le=>{const et=Le.queryKey;return Array.isArray(et)&&(et.includes("documentSection")||et[0]==="documentTableRows")}})}finally{le(!1)}},[ue]),on=l.jsxs(p.Button,{type:"button",variant:"ghost",size:"sm",className:p.cn(v2,"font-normal text-foreground hover:bg-muted hover:text-foreground"),onClick:St,disabled:me,"aria-label":"Refresh report",children:[l.jsx(tc,{className:p.cn("h-3.5 w-3.5",me&&"animate-spin")}),"Refresh"]});return T==="print"?l.jsxs(l.Fragment,{children:[l.jsx(d2,{inputs:h,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,onOptionsChange:vt}),l.jsx(sxt,{document:n,inputs:h,textRenderContext:mt,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,documentDashboardInputValues:ee,missingRequiredInputLabels:Je})]}):T==="view"?l.jsxs(l.Fragment,{children:[l.jsx(d2,{inputs:h,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,onOptionsChange:vt}),l.jsx(rxt,{document:n,inputs:h,textRenderContext:mt,filterValuesByInputId:Pe,filterModesByInputId:He,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,documentDashboardInputValues:ee,missingRequiredInputLabels:Je,onSetFilterValue:Ie,onSetFilterMode:$e,onRemoveFilterValue:st,controlValuesByInputId:ye,onSetControlValue:Lt,actions:l.jsxs(MK,{children:[on,l.jsx(w2,{}),ge]})})]}):l.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-muted/60 text-foreground",children:[l.jsx(d2,{inputs:h,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,onOptionsChange:vt}),l.jsx(Hgt,{sections:n.sections,inputs:h,selectedSectionId:X,onSelectSection:wt,onDeleteSection:Ge,onReorderSection:Re,onInsertSection:Le=>Et(Le,n.sections.length)}),l.jsxs("main",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[l.jsx(Ume,{inputs:h,filterValuesByInputId:Pe,filterModesByInputId:He,documentFilterValues:Tt,documentControlValues:Me,onSetFilterValue:Ie,onSetFilterMode:$e,onUpdateFilterInput:ct,onUpdateControlInput:rt,onRemoveFilterValue:st,onRemoveInput:Ct,controlValuesByInputId:ye,onSetControlValue:Lt,actions:l.jsxs(MK,{children:[on,l.jsx(w2,{}),l.jsx(Gyt,{zoom:ne,onZoomChange:de}),l.jsx(w2,{}),Oe]}),isEditing:!0}),l.jsxs("div",{className:"relative min-h-0 flex-1 overflow-auto",onClick:Le=>{Le.target===Le.currentTarget&&wt(null)},children:[l.jsx("div",{style:{zoom:ne/100},className:"flex justify-center px-6 py-8",children:l.jsx(b4,{document:n,inputs:h,textRenderContext:mt,documentFilterValues:Tt,documentControlDefinitions:g,documentControlValues:Me,documentDashboardInputValues:ee,missingRequiredInputLabels:Je,isEditing:!Se,selectedSectionId:Se?void 0:X,activeAddIndex:Se?null:O,onSelectSection:wt,onToggleAddIndex:q,onInsertSection:Et,onEditTableSection:Dt,onUpdateTableSection:he,onTableResultColumnsChange:Pt,onReorderSection:Re,pageNumber:K.pageNumber,onPageCountChange:bt,measurementScale:ne/100})}),l.jsx(Eyt,{pageNumber:K.pageNumber,pageCount:K.pageCount,onFirst:()=>Ye(1),onPrevious:()=>Ye(K.pageNumber-1),onNext:()=>Ye(K.pageNumber+1),onLast:()=>Ye(K.pageCount)})]})]}),l.jsx(jyt,{sheetId:e.id,tab:G,onTabChange:Rt,document:n,selectedSection:Ae,inputSourceSection:ke,tableResultColumnCacheBySectionId:se,onSelectSection:wt,onUpdatePage:De,onUpdateSelectedSection:Bt,onDeleteSelectedSection:un,onUpdateHeader:Fe,onUpdateFooter:ot,onEditTableSection:Dt})]})}function jyt({sheetId:e,tab:t,onTabChange:n,document:r,selectedSection:o,inputSourceSection:s,tableResultColumnCacheBySectionId:i,onSelectSection:a,onUpdatePage:c,onUpdateSelectedSection:u,onDeleteSelectedSection:d,onUpdateHeader:f,onUpdateFooter:h,onEditTableSection:m,actions:g}){const b=[{id:"page",label:"Page"},{id:"header",label:"Header"},{id:"footer",label:"Footer"},{id:"inputs",label:"Inputs"}],x=p.useDashboardStore(S=>S.dashboard),y=v.useMemo(()=>{const S=rx(x,e);return S.length>0?S.map(lC):r.inputs||[]},[x,r.inputs,e]),w=t==="section"&&o!=null,C=t==="section"?"page":t,N=v.useMemo(()=>{if((o==null?void 0:o.type)!=="table")return[];const S=i[o.id];if(!S)return[];const j=wme(o);return S.schemaSignature===j?S.columns:[]},[o,i]);return l.jsxs("aside",{className:"flex w-[360px] shrink-0 flex-col border-l bg-background",children:[w?l.jsx(kyt,{section:o,onBack:()=>a(null),actions:g}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b px-3",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(Pm,{className:"h-3.5 w-3.5 text-muted-foreground"}),l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Document"})]}),g]}),l.jsx("div",{className:"flex shrink-0 items-center gap-3 overflow-x-auto border-b px-3",children:b.map(S=>l.jsx("button",{type:"button",onClick:()=>n(S.id),className:p.cn("-mb-px border-b-2 py-2 text-[12px] transition-colors",C===S.id?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:S.label},S.id))})]}),l.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:w?l.jsx(Iyt,{section:o,inputs:y,tableResultColumns:N,onUpdateSection:u,onEditTableSection:m}):C==="page"?l.jsx(Tyt,{page:r.page,onUpdatePage:c}):C==="header"?l.jsx(Fyt,{header:r.header,inputs:y,onUpdateHeader:f}):C==="footer"?l.jsx(Oyt,{footer:r.footer,inputs:y,onUpdateFooter:h}):C==="inputs"?l.jsx(Lyt,{sheetId:e,document:r,selectedSection:s,inputCount:y.length,onSelectSection:S=>a(S,{activateSectionInspector:!1}),onEditTableSection:m}):null})]})}function kyt({section:e,onBack:t,actions:n}){const r=pv(e.type);return l.jsxs("div",{className:"flex h-10 shrink-0 items-center gap-2 border-b px-2",children:[l.jsx("button",{type:"button",onClick:t,"aria-label":"Back to document",className:"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-[4px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:l.jsx(zv,{className:"h-3.5 w-3.5"})}),l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[l.jsx(r,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),l.jsx("span",{className:"truncate text-[12px] font-medium text-foreground",children:sC[e.type]})]}),n]})}const _yt=[{value:"style",label:"Style"},{value:"columns",label:"Columns"},{value:"conditionalFormatting",label:"Conditional formatting"}];function Iyt({section:e,inputs:t,tableResultColumns:n=[],onUpdateSection:r,onEditTableSection:o}){var k,T,I,E,D,R,A,F,z;const[s,i]=v.useState("style");if(!e)return l.jsxs("div",{className:"flex flex-col items-center py-12 text-center",children:[l.jsx(Qs,{className:"mb-2 h-5 w-5 text-muted-foreground/50"}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Select a section"})]});const a=L=>{r($=>$.type!=="text"?$:{...$,style:{...$.style,...L}})},c=L=>{r($=>{var G;if($.type!=="table")return $;const H=(G=$.card.preferences)==null?void 0:G.tablePrefs,{density:M,...B}=L,W={...H==null?void 0:H.tableStyle,...B},P=M??(H==null?void 0:H.density);return{...$,card:{...$.card,preferences:{...$.card.preferences,tablePrefs:{...H,...P?{density:P}:{},tableStyle:W}}},table:{...$.table,...M?{rowHeightPx:EF(M)}:{}}}})},u=L=>{r($=>{var B;if($.type!=="table")return $;const H=(B=$.card.preferences)==null?void 0:B.tablePrefs,M=H==null?void 0:H.tableStyle;return{...$,card:{...$.card,preferences:{...$.card.preferences,tablePrefs:{...H,tableStyle:{...M,totals:{...M==null?void 0:M.totals,...L}}}}}}})},d=()=>{r(L=>{var $;return L.type==="table"?{...L,table:{...L.table,repeatHeaderOnPageBreak:!0,rowHeightPx:EF($f.density)},card:{...L.card,preferences:{...L.card.preferences,tablePrefs:{...($=L.card.preferences)==null?void 0:$.tablePrefs,density:$f.density,tableStyle:{headerStyle:$f.headerStyle,headerWrapText:$f.headerWrapText,stripedRows:$f.stripedRows,gridLines:$f.gridLines,wrapText:$f.wrapText,totals:{enabled:zf.enabled,backgroundColor:zf.backgroundColor,textColor:zf.textColor,fontWeight:zf.fontWeight,borderTop:zf.borderTop,borderTopStyle:zf.borderTopStyle,borderTopColor:zf.borderTopColor}}}}}}:L})},f=L=>{r($=>{var W;if($.type!=="table")return $;const H=(W=$.card.preferences)==null?void 0:W.tablePrefs,M=H==null?void 0:H.tableStyle;return{...$,card:{...$.card,preferences:{...$.card.preferences,tablePrefs:{...H,tableStyle:{...M,totals:{...M==null?void 0:M.totals,enabled:L}}}}},table:{...$.table,totalsRow:L}}})},h=(L,$)=>{r(H=>{var B;if(H.type!=="table")return H;const M=(B=H.card.preferences)==null?void 0:B.tablePrefs;return{...H,card:{...H.card,preferences:{...H.card.preferences,tablePrefs:{...M,columnVisibility:ooe(M==null?void 0:M.columnVisibility,L,$)}}}}})},m=()=>{r(L=>{var H;if(L.type!=="table")return L;const $=(H=L.card.preferences)==null?void 0:H.tablePrefs;return{...L,card:{...L.card,preferences:{...L.card.preferences,tablePrefs:{...$,columnVisibility:void 0}}}}})},g=e.type==="table"?A5((T=(k=e.card.preferences)==null?void 0:k.tablePrefs)==null?void 0:T.conditionalFormatting):{rules:[]},b=e.type==="table"&&ppe(e.card.type),x=b?xpe(e.card,n):[],y=e.type==="table"&&e.card.type==="table"?ype(e.card,n):[],w=b&&x.length>0,C=e.type==="table"&&e.card.type==="table",N=_yt.filter(L=>L.value==="style"||L.value==="columns"&&C||L.value==="conditionalFormatting"&&w),S=N.some(L=>L.value===s)?s:"style",j=((I=x[0])==null?void 0:I.value)??la,_=L=>{r($=>$.type==="table"?{...$,card:qxt($.card,{version:1,rules:L})}:$)};return l.jsxs("div",{className:"space-y-4",children:[e.type==="text"&&l.jsxs(l.Fragment,{children:[l.jsx(Oo,{label:"Content",children:l.jsx(xv,{content:e.content,inputs:t,multiline:!0,onChange:L=>r($=>$.type==="text"?{...$,content:L}:$)})}),l.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[l.jsx(Oo,{label:"Size",children:l.jsxs(p.Select,{value:String(((E=e.style)==null?void 0:E.fontSize)||13),onValueChange:L=>a({fontSize:Number(L)}),children:[l.jsx(p.SelectTrigger,{size:"sm","aria-label":"Text size",children:l.jsx(p.SelectValue,{})}),l.jsx(p.SelectContent,{children:[11,12,13,14,16,18,20,24].map(L=>l.jsxs(p.SelectItem,{value:String(L),children:[L,"px"]},L))})]})}),l.jsx(Oo,{label:"Weight",children:l.jsxs(p.Select,{value:((D=e.style)==null?void 0:D.fontWeight)||"normal",onValueChange:L=>a({fontWeight:L}),children:[l.jsx(p.SelectTrigger,{size:"sm","aria-label":"Text weight",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"normal",children:"Regular"}),l.jsx(p.SelectItem,{value:"medium",children:"Medium"}),l.jsx(p.SelectItem,{value:"semibold",children:"Semibold"}),l.jsx(p.SelectItem,{value:"bold",children:"Bold"})]})]})})]}),l.jsx(Oo,{label:"Alignment",children:l.jsx("div",{className:"inline-flex h-8 items-center rounded-md border bg-background p-0.5",children:["left","center","right"].map(L=>{var M;const $=L==="left"?fve:L==="center"?dve:hve,H=((M=e.style)==null?void 0:M.align)||"left";return l.jsx(p.Button,{type:"button",variant:H===L?"secondary":"ghost",size:"icon",className:"h-6 w-7","aria-label":`Align ${L}`,onClick:()=>a({align:L}),children:l.jsx($,{className:"h-3.5 w-3.5"})},L)})})}),l.jsx(Oo,{label:"Color",children:l.jsx(Ayt,{value:((R=e.style)==null?void 0:R.color)||"#27272a","aria-label":"Text color",onValueChange:L=>a({color:L})})})]}),e.type==="table"&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"inline-flex h-8 items-center rounded-md border bg-background p-0.5",children:N.map(L=>l.jsx(p.Button,{type:"button",variant:S===L.value?"secondary":"ghost",size:"xs",className:"h-6 px-2 text-[11px]",onClick:()=>i(L.value),children:L.label},L.value))}),S==="style"?l.jsxs(l.Fragment,{children:[l.jsx(Oo,{label:"Title",children:l.jsx(p.Input,{size:"xs",value:e.title||e.card.title,onChange:L=>r($=>$.type==="table"?{...$,title:L.target.value,card:{...$.card,title:L.target.value}}:$)})}),l.jsx(mpe,{style:d4(e),onDensityChange:L=>c({density:L}),onStyleChange:c,showFullStyle:e.card.type==="table",totals:e.card.type==="table"&&!((A=e.card.sql)!=null&&A.trim())?{enabled:e.table.totalsRow===!0,onEnabledChange:f,onStyleChange:u}:void 0,onReset:e.card.type==="table"?d:void 0})]}):S==="columns"?l.jsx(fpe,{columns:y,columnVisibility:(z=(F=e.card.preferences)==null?void 0:F.tablePrefs)==null?void 0:z.columnVisibility,onColumnVisibilityChange:h,onShowAllColumns:m,emptyMessage:"Run the table query or add fields before hiding output columns."}):l.jsx(l.Fragment,{children:l.jsx(Npe,{columnId:j,availableColumns:x,conditionalRules:g.rules,onConditionalRulesChange:_,startRulesWithNoTrigger:!0})}),l.jsx("div",{className:"flex flex-col gap-1.5 pt-1",children:l.jsxs(p.Button,{type:"button",variant:"secondary",size:"xs",className:"w-full gap-1.5",onClick:()=>o(e),children:[l.jsx(p.Table2,{className:"h-3 w-3"}),"Edit table"]})})]}),e.type==="spacer"&&l.jsx(Oo,{label:"Height",children:l.jsx(y4,{"aria-label":"Spacer height",min:8,max:240,value:e.heightPx,onValueChange:L=>r($=>$.type==="spacer"?{...$,heightPx:L}:$)})})]})}function Tyt({page:e,onUpdatePage:t}){const n=(r,o)=>{t({...e,margins:{...e.margins,[r]:o}})};return l.jsxs("div",{className:"space-y-5",children:[l.jsx(Oo,{label:"Page size",children:l.jsxs(p.Select,{value:e.size,onValueChange:r=>t({...e,size:r}),children:[l.jsx(p.SelectTrigger,{"aria-label":"Page size",size:"sm",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"letter",children:"Letter"}),l.jsx(p.SelectItem,{value:"a4",children:"A4"})]})]})}),l.jsx(Oo,{label:"Orientation",children:l.jsxs(p.Select,{value:e.orientation,onValueChange:r=>t({...e,orientation:r}),children:[l.jsx(p.SelectTrigger,{"aria-label":"Orientation",size:"sm",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"portrait",children:"Portrait"}),l.jsx(p.SelectItem,{value:"landscape",children:"Landscape"})]})]})}),l.jsx(Oo,{label:"Margins",children:l.jsx("div",{className:"grid grid-cols-2 gap-2",children:["top","bottom","left","right"].map(r=>l.jsxs("label",{className:"block",children:[l.jsx("span",{className:"mb-1 block text-[10px] capitalize text-muted-foreground",children:r}),l.jsx(y4,{"aria-label":`${r} margin`,min:0,step:.125,value:e.margins[r],onValueChange:o=>n(r,o)})]},r))})})]})}function y4({value:e,onValueChange:t,min:n=0,max:r,step:o,disabled:s,"aria-label":i}){const[a,c]=v.useState(()=>String(e)),[u,d]=v.useState(!1);v.useEffect(()=>{u||c(String(e))},[u,e]);const f=v.useCallback((h,m=!1)=>{if(h.trim()===""){m&&c(String(e));return}const g=Number(h);if(!Number.isFinite(g)){m&&c(String(e));return}const b=m?Math.min(r??g,Math.max(n,g)):g;b<n||r!==void 0&&b>r||(t(b),m&&c(String(b)))},[r,n,t,e]);return l.jsx(p.Input,{"aria-label":i,size:"sm",type:"number",min:n,max:r,step:o,value:a,disabled:s,onFocus:()=>d(!0),onChange:h=>{c(h.target.value),f(h.target.value)},onBlur:()=>{d(!1),f(a,!0)}})}function Eyt({pageNumber:e,pageCount:t,onFirst:n,onPrevious:r,onNext:o,onLast:s}){return t<=1?null:l.jsxs("div",{className:"sticky bottom-4 z-20 mx-auto mt-[-44px] flex w-max items-center gap-1.5 rounded-full border border-zinc-200 bg-white/95 px-2.5 py-1 text-[13px] text-zinc-700 shadow-[0_8px_24px_rgba(0,0,0,0.14)] backdrop-blur",children:[l.jsx("button",{type:"button","aria-label":"First document page",disabled:e<=1,className:"inline-flex h-5 w-5 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-zinc-500",onClick:n,children:l.jsx(pZ,{className:"h-3.5 w-3.5"})}),l.jsx("button",{type:"button","aria-label":"Previous document page",disabled:e<=1,className:"inline-flex h-5 w-5 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-zinc-500",onClick:r,children:l.jsx(Mm,{className:"h-3.5 w-3.5"})}),l.jsxs("span",{className:"min-w-[44px] text-center text-[12px] tabular-nums",children:[e," / ",t]}),l.jsx("button",{type:"button","aria-label":"Next document page",disabled:e>=t,className:"inline-flex h-5 w-5 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-zinc-500",onClick:o,children:l.jsx(Ft.ChevronRight,{className:"h-3.5 w-3.5"})}),l.jsx("button",{type:"button","aria-label":"Last document page",disabled:e>=t,className:"inline-flex h-5 w-5 items-center justify-center rounded-full text-zinc-500 transition-colors hover:bg-zinc-100 hover:text-zinc-900 disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-transparent disabled:hover:text-zinc-500",onClick:s,children:l.jsx(gZ,{className:"h-3.5 w-3.5"})})]})}const Dyt=["#ffffff","#fafafa","#f4f4f5","#e4e4e7","#a1a1aa","#52525b","#27272a","#0f172a","#eff6ff","#eef2ff","#ecfdf5","#fefce8"];function Myt(e){return e.startsWith("#")?e.toLowerCase():`#${e.toLowerCase()}`}function Ryt(e){return/^#[0-9a-fA-F]{6}$/.test(e)}function Ayt({value:e,onValueChange:t,"aria-label":n}){const[r,o]=v.useState(!1),[s,i]=v.useState(e.toUpperCase());v.useEffect(()=>{i(e.toUpperCase())},[e]);const a=v.useCallback(u=>{const d=Myt(u.trim());if(!Ryt(d)){i(e.toUpperCase());return}if(d===e.toLowerCase()){i(d.toUpperCase());return}t(d)},[t,e]),c=e.toLowerCase();return l.jsxs(p.Popover,{open:r,onOpenChange:o,children:[l.jsx(p.PopoverTrigger,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":n,className:"flex h-7 w-full items-center gap-2 rounded-[5px] border border-input bg-background px-1.5 text-[12px] text-foreground transition-colors hover:bg-muted/40 focus-visible:border-ring focus-visible:outline-none",children:[l.jsx("span",{"aria-hidden":"true",className:"h-4 w-4 shrink-0 rounded-[3px] border border-border/60",style:{backgroundColor:e}}),l.jsx("span",{className:"font-mono text-[11px] uppercase tracking-wide text-foreground",children:e.toUpperCase()}),l.jsx(Mm,{"aria-hidden":"true",className:"ml-auto h-3 w-3 shrink-0 -rotate-90 text-muted-foreground/60"})]})}),l.jsxs(p.PopoverContent,{align:"start",sideOffset:4,className:"w-[224px] space-y-2 p-2",onMouseDown:u=>u.stopPropagation(),children:[l.jsx("div",{role:"radiogroup","aria-label":"Color presets",className:"grid grid-cols-6 gap-1",children:Dyt.map(u=>{const d=u.toLowerCase()===c;return l.jsx("button",{type:"button",role:"radio","aria-checked":d,"aria-label":u,title:u.toUpperCase(),onClick:()=>{t(u),o(!1)},className:p.cn("relative flex h-7 w-7 items-center justify-center rounded-[4px] border border-border/60 transition-shadow",d&&"ring-1 ring-foreground ring-offset-1"),style:{backgroundColor:u},children:d&&l.jsx(p.Check,{"aria-hidden":"true",className:p.cn("h-3 w-3",Pyt(u)?"text-zinc-900":"text-white"),strokeWidth:3})},u)})}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("span",{"aria-hidden":"true",className:"text-[11px] font-medium uppercase tracking-[0.06em] text-muted-foreground",children:"Hex"}),l.jsx(p.Input,{size:"xs",value:s,onChange:u=>i(u.target.value.toUpperCase()),onBlur:u=>a(u.currentTarget.value),onKeyDown:u=>{u.key==="Enter"?u.currentTarget.blur():u.key==="Escape"&&(i(e.toUpperCase()),u.currentTarget.blur())},className:"font-mono text-[11px]"}),l.jsxs("label",{className:"relative inline-flex h-7 w-7 shrink-0 cursor-pointer items-center justify-center rounded-[4px] border border-border/60 bg-background hover:bg-muted/60",title:"Custom color",children:[l.jsx("span",{"aria-hidden":"true",className:"absolute inset-1 rounded-[3px]",style:{backgroundImage:"conic-gradient(from 0deg, #ef4444, #f59e0b, #84cc16, #06b6d4, #6366f1, #ec4899, #ef4444)"}}),l.jsx("input",{"aria-label":`${n??"Color"} (custom)`,type:"color",value:e,onChange:u=>t(u.target.value),className:"absolute inset-0 h-full w-full cursor-pointer opacity-0"})]})]})]})]})}function Pyt(e){const t=e.replace("#","");if(t.length!==6)return!0;const n=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),o=parseInt(t.slice(4,6),16);return .2126*n+.7152*r+.0722*o>150}function Fyt({header:e,inputs:t,onUpdateHeader:n}){const r=e?p.getRegionImageBlock(e.blocks,"logo"):void 0,o=e?p.getRegionTextBlock(e.blocks,"title"):void 0,s=e?p.getRegionTextBlock(e.blocks,"metadata"):void 0,i=(r==null?void 0:r.area)==="center"||(r==null?void 0:r.area)==="right"?r.area:"left",a=(u,d,f)=>{n(h=>{const m=h||p.createHeaderRegion();return{...m,enabled:!0,blocks:p.upsertTextRegionBlock(m.blocks,{id:`header_${u}`,role:u,area:d,content:f})}})},c=u=>{n(d=>{const f=d||p.createHeaderRegion(),h=p.getRegionImageBlock(f.blocks,"logo");return{...f,enabled:!0,blocks:p.upsertImageRegionBlock(f.blocks,{id:"header_logo",type:"image",role:"logo",area:"left",src:"",alt:"Logo",widthPx:120,...h,...u})}})};return e?l.jsxs("div",{className:"space-y-4",children:[l.jsx(dpe,{label:"Enabled",enabled:!!(e!=null&&e.enabled),onToggle:u=>n(d=>Ipe(d,p.createHeaderRegion,u))}),l.jsx(Oo,{label:"Logo URL",children:l.jsx(p.Input,{"aria-label":"Logo URL",size:"sm",value:(r==null?void 0:r.src)||"",disabled:!(e!=null&&e.enabled),onChange:u=>c({src:u.target.value})})}),l.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_5rem] gap-2",children:[l.jsx(Oo,{label:"Logo placement",children:l.jsxs(p.Select,{value:i,disabled:!(e!=null&&e.enabled),onValueChange:u=>c({area:u}),children:[l.jsx(p.SelectTrigger,{"aria-label":"Logo placement",size:"sm",children:l.jsx(p.SelectValue,{})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"left",children:"Left"}),l.jsx(p.SelectItem,{value:"center",children:"Center"}),l.jsx(p.SelectItem,{value:"right",children:"Right"})]})]})}),l.jsx(Oo,{label:"Width",children:l.jsx(y4,{"aria-label":"Logo width",min:24,max:320,step:4,value:(r==null?void 0:r.widthPx)||120,disabled:!(e!=null&&e.enabled),onValueChange:u=>c({widthPx:u})})})]}),l.jsx(Oo,{label:"Logo alt text",children:l.jsx(p.Input,{"aria-label":"Logo alt text",size:"sm",value:(r==null?void 0:r.alt)||"",disabled:!(e!=null&&e.enabled),onChange:u=>c({alt:u.target.value})})}),l.jsx(Oo,{label:"Title",children:l.jsx(xv,{content:o==null?void 0:o.content,inputs:t,disabled:!(e!=null&&e.enabled),onChange:u=>a("title","title",u)})}),l.jsx(Oo,{label:"Metadata",children:l.jsx(xv,{content:s==null?void 0:s.content,inputs:t,disabled:!(e!=null&&e.enabled),onChange:u=>a("metadata","metadata",u)})})]}):l.jsx(_pe,{title:"No header",description:"Logo, title, and metadata.",actionLabel:"Add header",onAdd:()=>n(()=>p.createHeaderRegion())})}function Oyt({footer:e,inputs:t,onUpdateFooter:n}){const r=e?p.getRegionTextBlock(e.blocks,"note"):void 0,o=e?p.getRegionTextBlock(e.blocks,"pageInfo"):void 0,s=(i,a,c)=>{n(u=>{const d=u||p.createFooterRegion();return{...d,enabled:!0,blocks:p.upsertTextRegionBlock(d.blocks,{id:`footer_${i}`,role:i,area:a,content:c})}})};return e?l.jsxs("div",{className:"space-y-4",children:[l.jsx(dpe,{label:"Enabled",enabled:!!(e!=null&&e.enabled),onToggle:i=>n(a=>Ipe(a,p.createFooterRegion,i))}),l.jsx(Oo,{label:"Note",children:l.jsx(xv,{content:r==null?void 0:r.content,inputs:t,disabled:!(e!=null&&e.enabled),onChange:i=>s("note","note",i)})}),l.jsx(Oo,{label:"Page info",children:l.jsx(xv,{content:o==null?void 0:o.content,inputs:t,disabled:!(e!=null&&e.enabled),onChange:i=>s("pageInfo","pageInfo",i)})})]}):l.jsx(_pe,{title:"No footer",description:"Note and page info.",actionLabel:"Add footer",onAdd:()=>n(()=>Wyt())})}function _pe({title:e,description:t,actionLabel:n,onAdd:r}){return l.jsxs("div",{className:"rounded border border-dashed border-border bg-muted/20 p-4",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx("p",{className:"text-[13px] font-medium text-foreground",children:e}),l.jsx("p",{className:"text-[12px] leading-4 text-muted-foreground",children:t})]}),l.jsx(p.Button,{type:"button",size:"sm",variant:"outline",className:"mt-4 h-8 w-full justify-center text-[12px]",onClick:r,children:n})]})}function Lyt({sheetId:e,document:t,selectedSection:n,inputCount:r,onSelectSection:o,onEditTableSection:s}){const i=p.useDashboardStore(w=>w.dashboard),{upsertDashboardInput:a,removeDashboardInput:c,updateSheetDocument:u}=p.useDashboardActions(),d=(n==null?void 0:n.type)==="table"?n:null,f=v.useMemo(()=>rx(i,e),[i,e]),h=v.useMemo(()=>f.map(lC),[f]),m=t.sections.filter(w=>w.type==="table"),g=v.useCallback(w=>{var S,j;const C=d==null?void 0:d.card;if(!C||f.some(_=>pyt(_,w)))return;const N=fyt({field:w,existingInputs:i.inputs||[],sheetId:e,dataSource:C.dataSource,connectionId:((S=C.dataSource)==null?void 0:S.connectionId)||C.connectionId,connectionType:(j=C.dataSource)==null?void 0:j.connectionType});a(N)},[i.inputs,f,d==null?void 0:d.card,e,a]),b=v.useCallback(w=>{c(w)},[c]),x=v.useCallback((w,C)=>{const N=f.find(S=>S.id===w);N&&a({...N,requiredAtExecution:C,...N.kind==="control"?{control:{...N.control,requiredAtExecution:C}}:{}})},[f,a]),y=v.useCallback((w,C)=>{const N=f.find(j=>j.id===w);if(!N)return;const S=AF({input:N,allInputs:i.inputs||[],...C});a(S),N.kind==="control"&&S.kind==="control"&&N.control.id!==S.control.id&&u(e,j=>PF(j,N.control.id,S.control.id))},[i.inputs,f,e,u,a]);return l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("h3",{className:"text-[12px] font-medium text-foreground",children:"Document inputs"}),l.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground",children:r})]}),l.jsx("p",{className:"text-[11px] leading-4 text-muted-foreground",children:"Add document-wide filter inputs from the selected table fields."})]}),l.jsx($yt,{selectedTableSection:d,tableSections:m,inputs:h,onSelectTable:o,onEditTableSection:s,onAddField:g}),l.jsx(Byt,{inputs:h,onUpdateMetadata:y,onRemove:b,onSetRequired:x})]})}function $yt({selectedTableSection:e,tableSections:t,inputs:n,onSelectTable:r,onEditTableSection:o,onAddField:s}){return t.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border bg-muted/20 px-4 py-6 text-center",children:[l.jsx(Qs,{className:"mb-2 h-5 w-5 text-muted-foreground/50"}),l.jsx("h3",{className:"mb-1 text-[12px] font-medium text-foreground",children:"No table sections"}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Add a document table before creating filter inputs."})]}):e?e.card?l.jsx(zyt,{section:e,inputs:n,onAddField:s}):l.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/20 p-3 text-[12px] text-muted-foreground",children:[l.jsxs("div",{className:"flex items-center gap-2 text-foreground",children:[l.jsx(ss,{className:"h-3.5 w-3.5"}),l.jsx("span",{className:"font-medium",children:"Configure this table"})]}),l.jsx("p",{children:"Choose a data source before adding document inputs."}),l.jsxs(p.Button,{type:"button",variant:"secondary",size:"sm",className:"h-8 w-full gap-2",onClick:()=>o(e),children:[l.jsx(p.Table2,{className:"h-3.5 w-3.5"}),"Configure table"]})]}):l.jsxs("div",{className:"rounded-md border bg-background",children:[l.jsx("div",{className:"border-b px-2.5 py-2 text-[11px] font-medium text-muted-foreground",children:"Choose a table section"}),l.jsx("div",{className:"space-y-1 p-1.5",children:t.map(i=>{var a;return l.jsxs(p.Button,{type:"button",variant:"ghost",size:"sm",className:"h-8 w-full justify-start gap-2 px-2 text-xs",onClick:()=>r(i.id),children:[l.jsx(p.Table2,{className:"h-3.5 w-3.5"}),i.title||((a=i.card)==null?void 0:a.title)||"Table"]},i.id)})})]})}function zyt({section:e,inputs:t,onAddField:n}){var i,a;const r=p.useEditorStore(c=>{var u;return(u=c.card)==null?void 0:u.id}),{setCard:o}=p.useEditorActions(),s=v.useMemo(()=>t.filter(cc).map(c=>({id:c.filter.id,column:c.filter.column,title:c.filter.title,dataType:c.filter.dataType,table:c.filter.table||"",database:c.filter.database||"",qualifiedTableName:c.filter.qualifiedTableName,connectionId:c.filter.connectionId,operation:c.filter.operation,sql:c.filter.sql,fieldMeta:c.filter.fieldMeta,semanticContext:c.filter.semanticContext})),[t]);return v.useEffect(()=>{e.card&&o(e.card)},[e.card,o]),r!==((i=e.card)==null?void 0:i.id)?l.jsx("div",{className:"rounded border border-dashed p-4 text-[12px] text-muted-foreground",children:"Loading fields..."}):l.jsxs("div",{className:"flex flex-col overflow-hidden rounded-md border bg-background",children:[l.jsxs("div",{className:"border-b px-2.5 py-2 text-[12px] text-muted-foreground",children:["Fields from"," ",l.jsx("span",{className:"font-medium text-foreground",children:e.title||((a=e.card)==null?void 0:a.title)||"this table"})]}),l.jsx(mme,{className:"h-[300px]",context:"document-filter",inlineFilters:s,onFieldSelect:n})]})}function Byt({inputs:e,onUpdateMetadata:t,onRemove:n,onSetRequired:r}){return l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:"Active inputs"}),e.length>0?l.jsx("span",{className:"rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground",children:e.length}):null]}),e.length===0?l.jsx("div",{className:"rounded-md border bg-muted/20 px-3 py-2 text-[11px] text-muted-foreground",children:"No document inputs yet."}):l.jsx("div",{className:"space-y-1",children:e.map(o=>l.jsx(Vyt,{input:o,onUpdateMetadata:s=>t(o.id,s),onRemove:()=>n(o.id),onSetRequired:s=>r(o.id,s)},o.id))})]})}function Vyt({input:e,onUpdateMetadata:t,onSetRequired:n,onRemove:r}){const[o,s]=v.useState(e.label);v.useEffect(()=>{s(e.label)},[e.id,e.label]);const i=v.useCallback(()=>{const c=o.trim();if(!c){s(e.label);return}c!==e.label&&t({label:c})},[e.label,o,t]),a=c=>{c.key==="Enter"&&(c.preventDefault(),c.currentTarget.blur())};return l.jsxs("div",{className:"rounded-md border bg-background px-2.5 py-2",children:[l.jsxs("div",{className:"flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[l.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[l.jsx(p.Input,{size:"xs",className:"h-6 min-w-0 border-0 bg-transparent px-0 py-0 text-[12px] font-medium shadow-none focus-visible:ring-0",value:o,onChange:c=>s(c.target.value),onBlur:i,onKeyDown:a,"aria-label":`${e.label} input label`}),l.jsx("span",{className:"shrink-0 rounded bg-muted px-1.5 py-0.5 text-[9px] font-medium uppercase text-muted-foreground",children:e.kind==="control"?"Control":"Filter"})]}),l.jsx(p.Input,{size:"xs",className:"h-6 min-w-0 rounded border bg-muted/20 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground shadow-none focus-visible:ring-0",value:`{{${e.variableName}}}`,readOnly:!0,"aria-label":`${e.label} input token`})]}),l.jsx("div",{className:"flex shrink-0 items-center gap-1",children:l.jsx(p.Button,{variant:"ghost",size:"icon",className:"h-5 w-5 hover:bg-destructive/10 hover:text-destructive",onClick:r,"aria-label":`Remove ${e.label} document input`,children:l.jsx(el,{className:"h-3 w-3"})})})]}),l.jsxs("label",{className:"mt-2 flex items-center justify-between gap-2 border-t pt-1.5 text-[11px] text-muted-foreground",children:[l.jsx("span",{children:"Required"}),l.jsx(p.Switch,{size:"xs",checked:e.requiredAtExecution,onCheckedChange:n,"aria-label":`Required ${e.label}`})]})]})}function Hyt(e,t,n,r){return{...e,inputs:(e.inputs||[]).map(o=>{if(o.id!==t||!cc(o))return o;const s={...o.filter,...n};return{...o,label:s.title||o.label,variableName:(r==null?void 0:r.variableName)||o.variableName,filter:s,exports:jT(s)}})}}function qyt(e,t,n){return{...e,inputs:(e.inputs||[]).map(r=>r.id!==t||!Ql(r)?r:{...r,label:n.label||r.label,requiredAtExecution:n.requiredAtExecution,control:n})}}function Uyt(e,t){return e.reduce((n,r)=>{if(!cc(r))return n;const o=t[r.id];return o&&vT(o.operation)&&(n[r.id]=kme(o.operation)),n},{})}function Ipe(e,t,n){return e?{...e,enabled:n}:n?t():void 0}function Wyt(){const e=p.createFooterRegion();return{...e,blocks:p.upsertTextRegionBlock(e.blocks,{id:"footer_pageInfo",role:"pageInfo",area:"pageInfo",content:[{type:"text",value:"Page "},{type:"variable",ref:{source:"documentMeta",key:"pageNumber"}},{type:"text",value:" of "},{type:"variable",ref:{source:"documentMeta",key:"pageCount"}}]})}}function Kyt(e,t){return e.length!==t.length?!1:e.every((n,r)=>{var o,s;return n.value===((o=t[r])==null?void 0:o.value)&&n.label===((s=t[r])==null?void 0:s.label)})}const Vf=[50,75,100,125,150],v2="inline-flex h-full items-center gap-1.5 rounded-none border-0 bg-transparent px-2 text-[12px] transition-colors";function MK({children:e}){return l.jsx("div",{className:"inline-flex h-7 shrink-0 items-center overflow-hidden rounded-[5px] border border-border bg-background text-foreground",children:e})}function w2(){return l.jsx("span",{"aria-hidden":"true",className:"h-full w-px bg-border"})}function Gyt({zoom:e,onZoomChange:t}){const n=Vf.indexOf(e),r=n>0,o=n>=0&&n<Vf.length-1;return l.jsxs("div",{className:"inline-flex h-full items-center gap-0.5 bg-transparent px-1",children:[l.jsx("button",{type:"button",disabled:!r,onClick:()=>{const s=Vf.indexOf(e);s>0&&t(Vf[s-1])},"aria-label":"Zoom out",className:"inline-flex h-5 w-5 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-muted-foreground",children:l.jsx($c,{className:"h-3 w-3"})}),l.jsxs("span",{className:"min-w-[34px] px-1 text-center text-[11px] tabular-nums text-foreground",children:[e,"%"]}),l.jsx("button",{type:"button",disabled:!o,onClick:()=>{const s=Vf.indexOf(e);s>=0&&s<Vf.length-1&&t(Vf[s+1])},"aria-label":"Zoom in",className:"inline-flex h-5 w-5 items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-30 disabled:hover:bg-transparent disabled:hover:text-muted-foreground",children:l.jsx(Tr,{className:"h-3 w-3"})})]})}const Yyt=f6.WidthProvider(f6.Responsive),Zyt=["input","textarea","select","button","a",'[role="button"]','[role="menuitem"]','[contenteditable="true"]',"[data-rgl-drag-cancel]",".data-table-scroll-container"].join(", ");function C2(e){if(!e)return null;let t=!1;const n={};for(const[r,o]of Object.entries(e))n[r]=o.map(s=>{const i=Number(s.w),a=Number(s.h);if(i===1&&a===1)return s;const c=s.minH!==void 0&&s.minH!==null,u=Number(s.minH),d=c&&Number.isFinite(u)?Math.max(1,u):void 0,f=Number.isFinite(a)?Math.max(1,a):1,h=d!==void 0?Math.max(d,f):f;if((h!==s.h||d!==s.minH)&&(t=!0),d===void 0){const{minH:m,...g}=s;return{...g,h}}return{...s,h,minH:d}});return t?n:null}function Xyt(){const{open:e}=K5();return e?l.jsx(pht,{}):null}function RK({sheet:e}){return e.kind==="document"?l.jsx(Nyt,{sheet:e}):l.jsx(Qyt,{sheet:e})}function Qyt({sheet:e}){var A,F;const t=p.useDashboardStore(z=>z.isDashboardEditing),n=p.useDashboardStore(z=>z.currentBreakpoint),r=p.useDashboardStore(z=>z.themeStyle),o=Ru(),s=v.useRef(0),i=v.useRef(!1),a=v.useRef(null),c=p.useDashboardStore(z=>z.selectedSheetId),u=e.layouts,d=v.useMemo(()=>C2(u),[u]),f=d||u,[h,m]=v.useState(f),g=v.useRef(f),b=e.frames,{setSheetLayouts:x,setCurrentBreakpoint:y}=p.useDashboardStore(z=>z.actions);v.useEffect(()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)},[e.id]),v.useEffect(()=>{i.current||jF(g.current,f)&&(g.current=f,m(f))},[f]),v.useEffect(()=>()=>{a.current!==null&&window.clearTimeout(a.current)},[]);function w(z){y(z)}const C=z=>{g.current=z,m(z)},N=z=>{a.current!==null&&window.clearTimeout(a.current),a.current=window.setTimeout(()=>{a.current=null,v.startTransition(()=>{x(e.id,z)})},0)};function S(z,L){if(!i.current){C2(L);const $=ght(u,d);c===e.id&&$&&(C($),N($));return}}const j=()=>{i.current=!0},_=z=>{if(z&&c===e.id){const L={...g.current||f||{},[n]:z},H=C2(L)||L;C(H),jF(u,H)&&N(H)}i.current=!1};if(!c)return null;const k=(z,L)=>l.jsx(Tpe,{className:"after:content-none",ref:L,handleAxis:z});function T(){return b==null?void 0:b.map(z=>l.jsx("div",{role:"dashboard-frame-container",className:p.cn("group isolate overflow-hidden",r==null?void 0:r.dashboardCardContainer),children:l.jsx(Si,{FallbackComponent:({error:L,resetErrorBoundary:$})=>l.jsx(ZJe,{error:L,resetErrorBoundary:$,frame:z}),children:l.jsx(iut,{frame:z})})},z.id))}const I=((A=r==null?void 0:r.gridLayout)==null?void 0:A.margin)??[10,10],E=o.gridMargin??I,D=o.gridContainerPadding??(o.gridMargin?I:void 0),R={...(r==null?void 0:r.cardBorderRadius)!==void 0?{"--placeholder-border-radius":`${r.cardBorderRadius}px`}:{},...o.gridStyle};return!b||b.length===0?l.jsx(fut,{sheetId:e.id}):l.jsxs(ATe,{children:[l.jsx(Yyt,{margin:E,containerPadding:D,isDraggable:t,draggableCancel:t?Zyt:void 0,resizeHandles:t?["s","w","e","n","sw","nw","se","ne"]:[],className:p.cn((F=r==null?void 0:r.gridLayout)==null?void 0:F.className),style:R,layouts:h,cols:{lg:48,md:36,sm:24,xs:12,xxs:6},rowHeight:1,onBreakpointChange:w,onLayoutChange:S,onDragStart:j,onDragStop:z=>_(z),onResizeStart:j,onResize:(z,L,$,H,M,B)=>{const W=Date.now();W-s.current>100&&(B.scrollIntoView({behavior:"auto",block:"nearest"}),s.current=W)},onResizeStop:(z,L,$,H,M,B)=>{B.scrollIntoView({behavior:"smooth",block:"nearest"}),_(z)},resizeHandle:k,children:T()}),l.jsx(Xyt,{})]})}const Tpe=v.forwardRef(({className:e,handleAxis:t,...n},r)=>{const o=p.useDashboardStore(s=>s.themeStyle);return o!=null&&o.cardBorderRadius,l.jsx("div",{ref:r,className:p.cn(`react-resizable-handle z-20 react-resizable-handle-${t} absolute border-foreground/40`,{"z-30 h-4 w-4":["sw","nw","se","ne"].includes(t),"bottom-0 left-0 cursor-sw-resize":t==="sw","left-0 top-0 cursor-nw-resize":t==="nw","bottom-0 right-0 cursor-se-resize":t==="se","right-0 top-0 cursor-ne-resize":t==="ne","!bottom-0 !left-0 !right-0 !h-2 !w-full cursor-ns-resize":t==="s","!left-0 !right-0 !top-0 !h-2 !w-full cursor-ns-resize":t==="n","!bottom-0 !right-0 !top-0 !h-full !w-2 cursor-ew-resize":t==="e","!bottom-0 !left-0 !top-0 !h-full !w-2 cursor-ew-resize":t==="w"},e),...n})});Tpe.displayName="ResizeHandle";const kT=v.createContext(null);kT.displayName="PanelGroupContext";const Jr={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},v4=10,Yh=v.useLayoutEffect,AK=te.useId,Jyt=typeof AK=="function"?AK:()=>null;let e0t=0;function w4(e=null){const t=Jyt(),n=v.useRef(e||t||null);return n.current===null&&(n.current=""+e0t++),e??n.current}function Epe({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:o,forwardedRef:s,id:i,maxSize:a,minSize:c,onCollapse:u,onExpand:d,onResize:f,order:h,style:m,tagName:g="div",...b}){const x=v.useContext(kT);if(x===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:y,expandPanel:w,getPanelSize:C,getPanelStyle:N,groupId:S,isPanelCollapsed:j,reevaluatePanelConstraints:_,registerPanel:k,resizePanel:T,unregisterPanel:I}=x,E=w4(i),D=v.useRef({callbacks:{onCollapse:u,onExpand:d,onResize:f},constraints:{collapsedSize:n,collapsible:r,defaultSize:o,maxSize:a,minSize:c},id:E,idIsFromProps:i!==void 0,order:h});v.useRef({didLogMissingDefaultSizeWarning:!1}),Yh(()=>{const{callbacks:A,constraints:F}=D.current,z={...F};D.current.id=E,D.current.idIsFromProps=i!==void 0,D.current.order=h,A.onCollapse=u,A.onExpand=d,A.onResize=f,F.collapsedSize=n,F.collapsible=r,F.defaultSize=o,F.maxSize=a,F.minSize=c,(z.collapsedSize!==F.collapsedSize||z.collapsible!==F.collapsible||z.maxSize!==F.maxSize||z.minSize!==F.minSize)&&_(D.current,z)}),Yh(()=>{const A=D.current;return k(A),()=>{I(A)}},[h,E,k,I]),v.useImperativeHandle(s,()=>({collapse:()=>{y(D.current)},expand:A=>{w(D.current,A)},getId(){return E},getSize(){return C(D.current)},isCollapsed(){return j(D.current)},isExpanded(){return!j(D.current)},resize:A=>{T(D.current,A)}}),[y,w,C,j,E,T]);const R=N(D.current,o);return v.createElement(g,{...b,children:e,className:t,id:E,style:{...R,...m},[Jr.groupId]:S,[Jr.panel]:"",[Jr.panelCollapsible]:r||void 0,[Jr.panelId]:E,[Jr.panelSize]:parseFloat(""+R.flexGrow).toFixed(1)})}const Dpe=v.forwardRef((e,t)=>v.createElement(Epe,{...e,forwardedRef:t}));Epe.displayName="Panel";Dpe.displayName="forwardRef(Panel)";let FF=null,eN=-1,sd=null;function t0t(e,t){if(t){const n=(t&Fpe)!==0,r=(t&Ope)!==0,o=(t&Lpe)!==0,s=(t&$pe)!==0;if(n)return o?"se-resize":s?"ne-resize":"e-resize";if(r)return o?"sw-resize":s?"nw-resize":"w-resize";if(o)return"s-resize";if(s)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function n0t(){sd!==null&&(document.head.removeChild(sd),FF=null,sd=null,eN=-1)}function S2(e,t){var n,r;const o=t0t(e,t);if(FF!==o){if(FF=o,sd===null&&(sd=document.createElement("style"),document.head.appendChild(sd)),eN>=0){var s;(s=sd.sheet)===null||s===void 0||s.removeRule(eN)}eN=(n=(r=sd.sheet)===null||r===void 0?void 0:r.insertRule(`*{cursor: ${o} !important;}`))!==null&&n!==void 0?n:-1}}function Mpe(e){return e.type==="keydown"}function Rpe(e){return e.type.startsWith("pointer")}function Ape(e){return e.type.startsWith("mouse")}function _T(e){if(Rpe(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(Ape(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function r0t(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function o0t(e,t,n){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function s0t(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:OK(e),b:OK(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;Nn(r,"Stacking order can only be calculated for elements with a common ancestor");const o={a:FK(PK(n.a)),b:FK(PK(n.b))};if(o.a===o.b){const s=r.childNodes,i={a:n.a.at(-1),b:n.b.at(-1)};let a=s.length;for(;a--;){const c=s[a];if(c===i.a)return 1;if(c===i.b)return-1}}return Math.sign(o.a-o.b)}const i0t=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function a0t(e){var t;const n=getComputedStyle((t=Ppe(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function l0t(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||a0t(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||i0t.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function PK(e){let t=e.length;for(;t--;){const n=e[t];if(Nn(n,"Missing node"),l0t(n))return n}return null}function FK(e){return e&&Number(getComputedStyle(e).zIndex)||0}function OK(e){const t=[];for(;e;)t.push(e),e=Ppe(e);return t}function Ppe(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const Fpe=1,Ope=2,Lpe=4,$pe=8,c0t=r0t()==="coarse";let Ja=[],fg=!1,ah=new Map,IT=new Map;const yv=new Set;function u0t(e,t,n,r,o){var s;const{ownerDocument:i}=t,a={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:o},c=(s=ah.get(i))!==null&&s!==void 0?s:0;return ah.set(i,c+1),yv.add(a),hk(),function(){var d;IT.delete(e),yv.delete(a);const f=(d=ah.get(i))!==null&&d!==void 0?d:1;if(ah.set(i,f-1),hk(),f===1&&ah.delete(i),Ja.includes(a)){const h=Ja.indexOf(a);h>=0&&Ja.splice(h,1),S4(),o("up",!0,null)}}}function d0t(e){const{target:t}=e,{x:n,y:r}=_T(e);fg=!0,C4({target:t,x:n,y:r}),hk(),Ja.length>0&&(mk("down",e),e.preventDefault(),zpe(t)||e.stopImmediatePropagation())}function N2(e){const{x:t,y:n}=_T(e);if(fg&&e.buttons===0&&(fg=!1,mk("up",e)),!fg){const{target:r}=e;C4({target:r,x:t,y:n})}mk("move",e),S4(),Ja.length>0&&e.preventDefault()}function j2(e){const{target:t}=e,{x:n,y:r}=_T(e);IT.clear(),fg=!1,Ja.length>0&&(e.preventDefault(),zpe(t)||e.stopImmediatePropagation()),mk("up",e),C4({target:t,x:n,y:r}),S4(),hk()}function zpe(e){let t=e;for(;t;){if(t.hasAttribute(Jr.resizeHandle))return!0;t=t.parentElement}return!1}function C4({target:e,x:t,y:n}){Ja.splice(0);let r=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(r=e),yv.forEach(o=>{const{element:s,hitAreaMargins:i}=o,a=s.getBoundingClientRect(),{bottom:c,left:u,right:d,top:f}=a,h=c0t?i.coarse:i.fine;if(t>=u-h&&t<=d+h&&n>=f-h&&n<=c+h){if(r!==null&&document.contains(r)&&s!==r&&!s.contains(r)&&!r.contains(s)&&s0t(r,s)>0){let g=r,b=!1;for(;g&&!g.contains(s);){if(o0t(g.getBoundingClientRect(),a)){b=!0;break}g=g.parentElement}if(b)return}Ja.push(o)}})}function k2(e,t){IT.set(e,t)}function S4(){let e=!1,t=!1;Ja.forEach(r=>{const{direction:o}=r;o==="horizontal"?e=!0:t=!0});let n=0;IT.forEach(r=>{n|=r}),e&&t?S2("intersection",n):e?S2("horizontal",n):t?S2("vertical",n):n0t()}let _2=new AbortController;function hk(){_2.abort(),_2=new AbortController;const e={capture:!0,signal:_2.signal};yv.size&&(fg?(Ja.length>0&&ah.forEach((t,n)=>{const{body:r}=n;t>0&&(r.addEventListener("contextmenu",j2,e),r.addEventListener("pointerleave",N2,e),r.addEventListener("pointermove",N2,e))}),window.addEventListener("pointerup",j2,e),window.addEventListener("pointercancel",j2,e)):ah.forEach((t,n)=>{const{body:r}=n;t>0&&(r.addEventListener("pointerdown",d0t,e),r.addEventListener("pointermove",N2,e))}))}function mk(e,t){yv.forEach(n=>{const{setResizeHandlerState:r}=n,o=Ja.includes(n);r(e,o,t)})}function f0t(){const[e,t]=v.useState(0);return v.useCallback(()=>t(n=>n+1),[])}function Nn(e,t){if(!e)throw console.error(t),Error(t)}function Tm(e,t,n=v4){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function Hc(e,t,n=v4){return Tm(e,t,n)===0}function Pi(e,t,n){return Tm(e,t,n)===0}function h0t(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){const o=e[r],s=t[r];if(!Pi(o,s,n))return!1}return!0}function Jp({panelConstraints:e,panelIndex:t,size:n}){const r=e[t];Nn(r!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:o=0,collapsible:s,maxSize:i=100,minSize:a=0}=r;if(Tm(n,a)<0)if(s){const c=(o+a)/2;Tm(n,c)<0?n=o:n=a}else n=a;return n=Math.min(i,n),n=parseFloat(n.toFixed(v4)),n}function Cy({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:o,trigger:s}){if(Pi(e,0))return t;const i=[...t],[a,c]=r;Nn(a!=null,"Invalid first pivot index"),Nn(c!=null,"Invalid second pivot index");let u=0;if(s==="keyboard"){{const f=e<0?c:a,h=n[f];Nn(h,`Panel constraints not found for index ${f}`);const{collapsedSize:m=0,collapsible:g,minSize:b=0}=h;if(g){const x=t[f];if(Nn(x!=null,`Previous layout not found for panel index ${f}`),Pi(x,m)){const y=b-x;Tm(y,Math.abs(e))>0&&(e=e<0?0-y:y)}}}{const f=e<0?a:c,h=n[f];Nn(h,`No panel constraints found for index ${f}`);const{collapsedSize:m=0,collapsible:g,minSize:b=0}=h;if(g){const x=t[f];if(Nn(x!=null,`Previous layout not found for panel index ${f}`),Pi(x,b)){const y=x-m;Tm(y,Math.abs(e))>0&&(e=e<0?0-y:y)}}}}{const f=e<0?1:-1;let h=e<0?c:a,m=0;for(;;){const b=t[h];Nn(b!=null,`Previous layout not found for panel index ${h}`);const y=Jp({panelConstraints:n,panelIndex:h,size:100})-b;if(m+=y,h+=f,h<0||h>=n.length)break}const g=Math.min(Math.abs(e),Math.abs(m));e=e<0?0-g:g}{let h=e<0?a:c;for(;h>=0&&h<n.length;){const m=Math.abs(e)-Math.abs(u),g=t[h];Nn(g!=null,`Previous layout not found for panel index ${h}`);const b=g-m,x=Jp({panelConstraints:n,panelIndex:h,size:b});if(!Pi(g,x)&&(u+=g-x,i[h]=x,u.toPrecision(3).localeCompare(Math.abs(e).toPrecision(3),void 0,{numeric:!0})>=0))break;e<0?h--:h++}}if(h0t(o,i))return o;{const f=e<0?c:a,h=t[f];Nn(h!=null,`Previous layout not found for panel index ${f}`);const m=h+u,g=Jp({panelConstraints:n,panelIndex:f,size:m});if(i[f]=g,!Pi(g,m)){let b=m-g,y=e<0?c:a;for(;y>=0&&y<n.length;){const w=i[y];Nn(w!=null,`Previous layout not found for panel index ${y}`);const C=w+b,N=Jp({panelConstraints:n,panelIndex:y,size:C});if(Pi(w,N)||(b-=N-w,i[y]=N),Pi(b,0))break;e>0?y--:y++}}}const d=i.reduce((f,h)=>h+f,0);return Pi(d,100)?i:o}function m0t({layout:e,panelsArray:t,pivotIndices:n}){let r=0,o=100,s=0,i=0;const a=n[0];Nn(a!=null,"No pivot index found"),t.forEach((f,h)=>{const{constraints:m}=f,{maxSize:g=100,minSize:b=0}=m;h===a?(r=b,o=g):(s+=b,i+=g)});const c=Math.min(o,100-s),u=Math.max(r,100-i),d=e[a];return{valueMax:c,valueMin:u,valueNow:d}}function vv(e,t=document){return Array.from(t.querySelectorAll(`[${Jr.resizeHandleId}][data-panel-group-id="${e}"]`))}function Bpe(e,t,n=document){const o=vv(e,n).findIndex(s=>s.getAttribute(Jr.resizeHandleId)===t);return o??null}function Vpe(e,t,n){const r=Bpe(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function Hpe(e,t=document){var n;if(t instanceof HTMLElement&&(t==null||(n=t.dataset)===null||n===void 0?void 0:n.panelGroupId)==e)return t;const r=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return r||null}function TT(e,t=document){const n=t.querySelector(`[${Jr.resizeHandleId}="${e}"]`);return n||null}function p0t(e,t,n,r=document){var o,s,i,a;const c=TT(t,r),u=vv(e,r),d=c?u.indexOf(c):-1,f=(o=(s=n[d])===null||s===void 0?void 0:s.id)!==null&&o!==void 0?o:null,h=(i=(a=n[d+1])===null||a===void 0?void 0:a.id)!==null&&i!==void 0?i:null;return[f,h]}function g0t({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:o,panelGroupElement:s,setLayout:i}){v.useRef({didWarnAboutMissingResizeHandle:!1}),Yh(()=>{if(!s)return;const a=vv(n,s);for(let c=0;c<o.length-1;c++){const{valueMax:u,valueMin:d,valueNow:f}=m0t({layout:r,panelsArray:o,pivotIndices:[c,c+1]}),h=a[c];if(h!=null){const m=o[c];Nn(m,`No panel data found for index "${c}"`),h.setAttribute("aria-controls",m.id),h.setAttribute("aria-valuemax",""+Math.round(u)),h.setAttribute("aria-valuemin",""+Math.round(d)),h.setAttribute("aria-valuenow",f!=null?""+Math.round(f):"")}}return()=>{a.forEach((c,u)=>{c.removeAttribute("aria-controls"),c.removeAttribute("aria-valuemax"),c.removeAttribute("aria-valuemin"),c.removeAttribute("aria-valuenow")})}},[n,r,o,s]),v.useEffect(()=>{if(!s)return;const a=t.current;Nn(a,"Eager values not found");const{panelDataArray:c}=a,u=Hpe(n,s);Nn(u!=null,`No group found for id "${n}"`);const d=vv(n,s);Nn(d,`No resize handles found for group id "${n}"`);const f=d.map(h=>{const m=h.getAttribute(Jr.resizeHandleId);Nn(m,"Resize handle element has no handle id attribute");const[g,b]=p0t(n,m,c,s);if(g==null||b==null)return()=>{};const x=y=>{if(!y.defaultPrevented)switch(y.key){case"Enter":{y.preventDefault();const w=c.findIndex(C=>C.id===g);if(w>=0){const C=c[w];Nn(C,`No panel data found for index ${w}`);const N=r[w],{collapsedSize:S=0,collapsible:j,minSize:_=0}=C.constraints;if(N!=null&&j){const k=Cy({delta:Pi(N,S)?_-S:S-N,initialLayout:r,panelConstraints:c.map(T=>T.constraints),pivotIndices:Vpe(n,m,s),prevLayout:r,trigger:"keyboard"});r!==k&&i(k)}}break}}};return h.addEventListener("keydown",x),()=>{h.removeEventListener("keydown",x)}});return()=>{f.forEach(h=>h())}},[s,e,t,n,r,o,i])}function LK(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function qpe(e,t){const n=e==="horizontal",{x:r,y:o}=_T(t);return n?r:o}function b0t(e,t,n,r,o){const s=n==="horizontal",i=TT(t,o);Nn(i,`No resize handle element found for id "${t}"`);const a=i.getAttribute(Jr.groupId);Nn(a,"Resize handle element has no group id attribute");let{initialCursorPosition:c}=r;const u=qpe(n,e),d=Hpe(a,o);Nn(d,`No group element found for id "${a}"`);const f=d.getBoundingClientRect(),h=s?f.width:f.height;return(u-c)/h*100}function x0t(e,t,n,r,o,s){if(Mpe(e)){const i=n==="horizontal";let a=0;e.shiftKey?a=100:o!=null?a=o:a=10;let c=0;switch(e.key){case"ArrowDown":c=i?0:a;break;case"ArrowLeft":c=i?-a:0;break;case"ArrowRight":c=i?a:0;break;case"ArrowUp":c=i?0:-a;break;case"End":c=100;break;case"Home":c=-100;break}return c}else return r==null?0:b0t(e,t,n,r,s)}function y0t({panelDataArray:e}){const t=Array(e.length),n=e.map(s=>s.constraints);let r=0,o=100;for(let s=0;s<e.length;s++){const i=n[s];Nn(i,`Panel constraints not found for index ${s}`);const{defaultSize:a}=i;a!=null&&(r++,t[s]=a,o-=a)}for(let s=0;s<e.length;s++){const i=n[s];Nn(i,`Panel constraints not found for index ${s}`);const{defaultSize:a}=i;if(a!=null)continue;const c=e.length-r,u=o/c;r++,t[s]=u,o-=u}return t}function _p(e,t,n){t.forEach((r,o)=>{const s=e[o];Nn(s,`Panel data not found for index ${o}`);const{callbacks:i,constraints:a,id:c}=s,{collapsedSize:u=0,collapsible:d}=a,f=n[c];if(f==null||r!==f){n[c]=r;const{onCollapse:h,onExpand:m,onResize:g}=i;g&&g(r,f),d&&(h||m)&&(m&&(f==null||Hc(f,u))&&!Hc(r,u)&&m(),h&&(f==null||!Hc(f,u))&&Hc(r,u)&&h())}})}function n1(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function v0t({defaultSize:e,dragState:t,layout:n,panelData:r,panelIndex:o,precision:s=3}){const i=n[o];let a;return i==null?a=e!=null?e.toPrecision(s):"1":r.length===1?a="1":a=i.toPrecision(s),{flexBasis:0,flexGrow:a,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function w0t(e,t=10){let n=null;return(...o)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...o)},t)}}function $K(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function Upe(e){return`react-resizable-panels:${e}`}function Wpe(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:o,order:s}=t;return o?r:s?`${s}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function Kpe(e,t){try{const n=Upe(e),r=t.getItem(n);if(r){const o=JSON.parse(r);if(typeof o=="object"&&o!=null)return o}}catch{}return null}function C0t(e,t,n){var r,o;const s=(r=Kpe(e,n))!==null&&r!==void 0?r:{},i=Wpe(t);return(o=s[i])!==null&&o!==void 0?o:null}function S0t(e,t,n,r,o){var s;const i=Upe(e),a=Wpe(t),c=(s=Kpe(e,o))!==null&&s!==void 0?s:{};c[a]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{o.setItem(i,JSON.stringify(c))}catch(u){console.error(u)}}function zK({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((s,i)=>s+i,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(s=>`${s}%`).join(", ")}`);if(!Pi(r,100)&&n.length>0)for(let s=0;s<t.length;s++){const i=n[s];Nn(i!=null,`No layout data found for index ${s}`);const a=100/r*i;n[s]=a}let o=0;for(let s=0;s<t.length;s++){const i=n[s];Nn(i!=null,`No layout data found for index ${s}`);const a=Jp({panelConstraints:t,panelIndex:s,size:i});i!=a&&(o+=i-a,n[s]=a)}if(!Pi(o,0))for(let s=0;s<t.length;s++){const i=n[s];Nn(i!=null,`No layout data found for index ${s}`);const a=i+o,c=Jp({panelConstraints:t,panelIndex:s,size:a});if(i!==c&&(o-=c-i,n[s]=c,Pi(o,0)))break}return n}const N0t=100,Sy={getItem:e=>($K(Sy),Sy.getItem(e)),setItem:(e,t)=>{$K(Sy),Sy.setItem(e,t)}},BK={};function Gpe({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:o,id:s=null,onLayout:i=null,keyboardResizeBy:a=null,storage:c=Sy,style:u,tagName:d="div",...f}){const h=w4(s),m=v.useRef(null),[g,b]=v.useState(null),[x,y]=v.useState([]),w=f0t(),C=v.useRef({}),N=v.useRef(new Map),S=v.useRef(0),j=v.useRef({autoSaveId:e,direction:r,dragState:g,id:h,keyboardResizeBy:a,onLayout:i,storage:c}),_=v.useRef({layout:x,panelDataArray:[],panelDataArrayChanged:!1});v.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),v.useImperativeHandle(o,()=>({getId:()=>j.current.id,getLayout:()=>{const{layout:P}=_.current;return P},setLayout:P=>{const{onLayout:G}=j.current,{layout:Z,panelDataArray:X}=_.current,Y=zK({layout:P,panelConstraints:X.map(O=>O.constraints)});LK(Z,Y)||(y(Y),_.current.layout=Y,G&&G(Y),_p(X,Y,C.current))}}),[]),Yh(()=>{j.current.autoSaveId=e,j.current.direction=r,j.current.dragState=g,j.current.id=h,j.current.onLayout=i,j.current.storage=c}),g0t({committedValuesRef:j,eagerValuesRef:_,groupId:h,layout:x,panelDataArray:_.current.panelDataArray,setLayout:y,panelGroupElement:m.current}),v.useEffect(()=>{const{panelDataArray:P}=_.current;if(e){if(x.length===0||x.length!==P.length)return;let G=BK[e];G==null&&(G=w0t(S0t,N0t),BK[e]=G);const Z=[...P],X=new Map(N.current);G(e,Z,X,x,c)}},[e,x,c]),v.useEffect(()=>{});const k=v.useCallback(P=>{const{onLayout:G}=j.current,{layout:Z,panelDataArray:X}=_.current;if(P.constraints.collapsible){const Y=X.map(V=>V.constraints),{collapsedSize:O=0,panelSize:q,pivotIndices:U}=Hf(X,P,Z);if(Nn(q!=null,`Panel size not found for panel "${P.id}"`),!Hc(q,O)){N.current.set(P.id,q);const K=zp(X,P)===X.length-1?q-O:O-q,Q=Cy({delta:K,initialLayout:Z,panelConstraints:Y,pivotIndices:U,prevLayout:Z,trigger:"imperative-api"});n1(Z,Q)||(y(Q),_.current.layout=Q,G&&G(Q),_p(X,Q,C.current))}}},[]),T=v.useCallback((P,G)=>{const{onLayout:Z}=j.current,{layout:X,panelDataArray:Y}=_.current;if(P.constraints.collapsible){const O=Y.map(se=>se.constraints),{collapsedSize:q=0,panelSize:U=0,minSize:V=0,pivotIndices:K}=Hf(Y,P,X),Q=G??V;if(Hc(U,q)){const se=N.current.get(P.id),oe=se!=null&&se>=Q?se:Q,le=zp(Y,P)===Y.length-1?U-oe:oe-U,ue=Cy({delta:le,initialLayout:X,panelConstraints:O,pivotIndices:K,prevLayout:X,trigger:"imperative-api"});n1(X,ue)||(y(ue),_.current.layout=ue,Z&&Z(ue),_p(Y,ue,C.current))}}},[]),I=v.useCallback(P=>{const{layout:G,panelDataArray:Z}=_.current,{panelSize:X}=Hf(Z,P,G);return Nn(X!=null,`Panel size not found for panel "${P.id}"`),X},[]),E=v.useCallback((P,G)=>{const{panelDataArray:Z}=_.current,X=zp(Z,P);return v0t({defaultSize:G,dragState:g,layout:x,panelData:Z,panelIndex:X})},[g,x]),D=v.useCallback(P=>{const{layout:G,panelDataArray:Z}=_.current,{collapsedSize:X=0,collapsible:Y,panelSize:O}=Hf(Z,P,G);return Nn(O!=null,`Panel size not found for panel "${P.id}"`),Y===!0&&Hc(O,X)},[]),R=v.useCallback(P=>{const{layout:G,panelDataArray:Z}=_.current,{collapsedSize:X=0,collapsible:Y,panelSize:O}=Hf(Z,P,G);return Nn(O!=null,`Panel size not found for panel "${P.id}"`),!Y||Tm(O,X)>0},[]),A=v.useCallback(P=>{const{panelDataArray:G}=_.current;G.push(P),G.sort((Z,X)=>{const Y=Z.order,O=X.order;return Y==null&&O==null?0:Y==null?-1:O==null?1:Y-O}),_.current.panelDataArrayChanged=!0,w()},[w]);Yh(()=>{if(_.current.panelDataArrayChanged){_.current.panelDataArrayChanged=!1;const{autoSaveId:P,onLayout:G,storage:Z}=j.current,{layout:X,panelDataArray:Y}=_.current;let O=null;if(P){const U=C0t(P,Y,Z);U&&(N.current=new Map(Object.entries(U.expandToSizes)),O=U.layout)}O==null&&(O=y0t({panelDataArray:Y}));const q=zK({layout:O,panelConstraints:Y.map(U=>U.constraints)});LK(X,q)||(y(q),_.current.layout=q,G&&G(q),_p(Y,q,C.current))}}),Yh(()=>{const P=_.current;return()=>{P.layout=[]}},[]);const F=v.useCallback(P=>{let G=!1;const Z=m.current;return Z&&window.getComputedStyle(Z,null).getPropertyValue("direction")==="rtl"&&(G=!0),function(Y){Y.preventDefault();const O=m.current;if(!O)return()=>null;const{direction:q,dragState:U,id:V,keyboardResizeBy:K,onLayout:Q}=j.current,{layout:se,panelDataArray:oe}=_.current,{initialLayout:me}=U??{},le=Vpe(V,P,O);let ue=x0t(Y,P,q,U,K,O);const ne=q==="horizontal";ne&&G&&(ue=-ue);const de=oe.map(ie=>ie.constraints),Ce=Cy({delta:ue,initialLayout:me??se,panelConstraints:de,pivotIndices:le,prevLayout:se,trigger:Mpe(Y)?"keyboard":"mouse-or-touch"}),ce=!n1(se,Ce);(Rpe(Y)||Ape(Y))&&S.current!=ue&&(S.current=ue,!ce&&ue!==0?ne?k2(P,ue<0?Fpe:Ope):k2(P,ue<0?Lpe:$pe):k2(P,0)),ce&&(y(Ce),_.current.layout=Ce,Q&&Q(Ce),_p(oe,Ce,C.current))}},[]),z=v.useCallback((P,G)=>{const{onLayout:Z}=j.current,{layout:X,panelDataArray:Y}=_.current,O=Y.map(se=>se.constraints),{panelSize:q,pivotIndices:U}=Hf(Y,P,X);Nn(q!=null,`Panel size not found for panel "${P.id}"`);const K=zp(Y,P)===Y.length-1?q-G:G-q,Q=Cy({delta:K,initialLayout:X,panelConstraints:O,pivotIndices:U,prevLayout:X,trigger:"imperative-api"});n1(X,Q)||(y(Q),_.current.layout=Q,Z&&Z(Q),_p(Y,Q,C.current))},[]),L=v.useCallback((P,G)=>{const{layout:Z,panelDataArray:X}=_.current,{collapsedSize:Y=0,collapsible:O}=G,{collapsedSize:q=0,collapsible:U,maxSize:V=100,minSize:K=0}=P.constraints,{panelSize:Q}=Hf(X,P,Z);Q!=null&&(O&&U&&Hc(Q,Y)?Hc(Y,q)||z(P,q):Q<K?z(P,K):Q>V&&z(P,V))},[z]),$=v.useCallback((P,G)=>{const{direction:Z}=j.current,{layout:X}=_.current;if(!m.current)return;const Y=TT(P,m.current);Nn(Y,`Drag handle element not found for id "${P}"`);const O=qpe(Z,G);b({dragHandleId:P,dragHandleRect:Y.getBoundingClientRect(),initialCursorPosition:O,initialLayout:X})},[]),H=v.useCallback(()=>{b(null)},[]),M=v.useCallback(P=>{const{panelDataArray:G}=_.current,Z=zp(G,P);Z>=0&&(G.splice(Z,1),delete C.current[P.id],_.current.panelDataArrayChanged=!0,w())},[w]),B=v.useMemo(()=>({collapsePanel:k,direction:r,dragState:g,expandPanel:T,getPanelSize:I,getPanelStyle:E,groupId:h,isPanelCollapsed:D,isPanelExpanded:R,reevaluatePanelConstraints:L,registerPanel:A,registerResizeHandle:F,resizePanel:z,startDragging:$,stopDragging:H,unregisterPanel:M,panelGroupElement:m.current}),[k,g,r,T,I,E,h,D,R,L,A,F,z,$,H,M]),W={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return v.createElement(kT.Provider,{value:B},v.createElement(d,{...f,children:t,className:n,id:s,ref:m,style:{...W,...u},[Jr.group]:"",[Jr.groupDirection]:r,[Jr.groupId]:h}))}const Ype=v.forwardRef((e,t)=>v.createElement(Gpe,{...e,forwardedRef:t}));Gpe.displayName="PanelGroup";Ype.displayName="forwardRef(PanelGroup)";function zp(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function Hf(e,t,n){const r=zp(e,t),s=r===e.length-1?[r-1,r]:[r,r+1],i=n[r];return{...t.constraints,panelSize:i,pivotIndices:s}}function j0t({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){v.useEffect(()=>{if(e||n==null||r==null)return;const o=TT(t,r);if(o==null)return;const s=i=>{if(!i.defaultPrevented)switch(i.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{i.preventDefault(),n(i);break}case"F6":{i.preventDefault();const a=o.getAttribute(Jr.groupId);Nn(a,`No group element found for id "${a}"`);const c=vv(a,r),u=Bpe(a,t,r);Nn(u!==null,`No resize element found for id "${t}"`);const d=i.shiftKey?u>0?u-1:c.length-1:u+1<c.length?u+1:0;c[d].focus();break}}};return o.addEventListener("keydown",s),()=>{o.removeEventListener("keydown",s)}},[r,e,t,n])}function ET({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:o,onBlur:s,onClick:i,onDragging:a,onFocus:c,onPointerDown:u,onPointerUp:d,style:f={},tabIndex:h=0,tagName:m="div",...g}){var b,x;const y=v.useRef(null),w=v.useRef({onClick:i,onDragging:a,onPointerDown:u,onPointerUp:d});v.useEffect(()=>{w.current.onClick=i,w.current.onDragging=a,w.current.onPointerDown=u,w.current.onPointerUp=d});const C=v.useContext(kT);if(C===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:N,groupId:S,registerResizeHandle:j,startDragging:_,stopDragging:k,panelGroupElement:T}=C,I=w4(o),[E,D]=v.useState("inactive"),[R,A]=v.useState(!1),[F,z]=v.useState(null),L=v.useRef({state:E});Yh(()=>{L.current.state=E}),v.useEffect(()=>{if(n)z(null);else{const B=j(I);z(()=>B)}},[n,I,j]);const $=(b=r==null?void 0:r.coarse)!==null&&b!==void 0?b:15,H=(x=r==null?void 0:r.fine)!==null&&x!==void 0?x:5;v.useEffect(()=>{if(n||F==null)return;const B=y.current;Nn(B,"Element ref not attached");let W=!1;return u0t(I,B,N,{coarse:$,fine:H},(G,Z,X)=>{if(!Z){D("inactive");return}switch(G){case"down":{D("drag"),W=!1,Nn(X,'Expected event to be defined for "down" action'),_(I,X);const{onDragging:Y,onPointerDown:O}=w.current;Y==null||Y(!0),O==null||O();break}case"move":{const{state:Y}=L.current;W=!0,Y!=="drag"&&D("hover"),Nn(X,'Expected event to be defined for "move" action'),F(X);break}case"up":{D("hover"),k();const{onClick:Y,onDragging:O,onPointerUp:q}=w.current;O==null||O(!1),q==null||q(),W||Y==null||Y();break}}})},[$,N,n,H,j,I,F,_,k]),j0t({disabled:n,handleId:I,resizeHandler:F,panelGroupElement:T});const M={touchAction:"none",userSelect:"none"};return v.createElement(m,{...g,children:e,className:t,id:o,onBlur:()=>{A(!1),s==null||s()},onFocus:()=>{A(!0),c==null||c()},ref:y,role:"separator",style:{...M,...f},tabIndex:h,[Jr.groupDirection]:N,[Jr.groupId]:S,[Jr.resizeHandle]:"",[Jr.resizeHandleActive]:E==="drag"?"pointer":R?"keyboard":void 0,[Jr.resizeHandleEnabled]:!n,[Jr.resizeHandleId]:I,[Jr.resizeHandleState]:E})}ET.displayName="PanelResizeHandle";const Zpe=({className:e,...t})=>l.jsx(Ype,{className:p.cn("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t}),OF=Dpe,k0t=({withHandle:e,className:t,...n})=>l.jsx(ET,{className:p.cn("relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&l.jsx("div",{className:"z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border",children:l.jsx(Nu,{className:"h-2.5 w-2.5"})})}),_0t=({withHandle:e,className:t,onTabClick:n,open:r,...o})=>l.jsx(ET,{className:p.cn("relative flex w-px items-start justify-end bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",{"justify-start":r},t),...o,children:e&&!1});function I0t(e={}){const{initialPosition:t="bottom-right"}=e,[n,r]=v.useState(t),[o,s]=v.useState(!1),[i,a]=v.useState(null),c=v.useRef(null),u=v.useRef(!1),d=v.useRef(null);v.useEffect(()=>()=>{d.current&&(d.current(),d.current=null)},[]);const f=v.useCallback(g=>{const b="touches"in g?g.touches[0].clientX:g.clientX,x="touches"in g?g.touches[0].clientY:g.clientY;c.current={x:b,y:x},u.current=!1,a({x:b,y:x});const y=(_,k,T)=>{if(!c.current)return;const I=Math.abs(_-c.current.x),E=Math.abs(k-c.current.y);(I>10||E>10)&&(u.current?T.cancelable&&T.preventDefault():(T.cancelable&&T.preventDefault(),u.current=!0,s(!0))),a({x:_,y:k})},w={passive:!1},C=_=>{y(_.clientX,_.clientY,_)},N=_=>{if(_.touches.length===0)return;const k=_.touches[0];y(k.clientX,k.clientY,_)},S=()=>{document.removeEventListener("mousemove",C),document.removeEventListener("mouseup",j),document.removeEventListener("touchmove",N),document.removeEventListener("touchend",j),d.current=null},j=()=>{a(_=>{if(u.current&&_){const k=window.innerWidth,T=window.innerHeight,I=_.x<k/2,E=_.y<T/2;r(E&&I?"top-left":E&&!I?"top-right":!E&&I?"bottom-left":"bottom-right")}return null}),c.current=null,setTimeout(()=>{u.current=!1,s(!1)},100),S()};document.addEventListener("mousemove",C),document.addEventListener("mouseup",j),document.addEventListener("touchmove",N,w),document.addEventListener("touchend",j),d.current=S},[]),h=v.useCallback(()=>{if(o&&i)return{position:"fixed",left:0,top:0,right:"auto",bottom:"auto",transform:`translate(${i.x-24}px, ${i.y-24}px)`,transition:"none",willChange:"transform"}},[o,i]),m=v.useCallback(()=>({horizontal:n.includes("left")?"left-6":"right-6",vertical:n.includes("top")?"top-6":"bottom-6"}),[n]);return{position:n,isDragging:o,dragPosition:i,handleDragStart:f,isDraggingRef:u,getStyle:h,getPositionClasses:m}}function T0t({open:e,setOpen:t}){const n=p.useDashboardStore(s=>s.selectedSheetId),{deleteSheet:r}=p.useDashboardActions();function o(){n&&(r(n),t(!1))}return l.jsx(ff,{open:e,onOpenChange:t,children:l.jsxs(ku,{children:[l.jsxs(_u,{children:[l.jsx(Tu,{children:"Delete Sheet"}),l.jsx(Eu,{children:"Are you sure you want to delete this sheet along with all its cards? This action cannot be undone."})]}),l.jsxs(Iu,{children:[l.jsx(Mu,{children:"Cancel"}),l.jsx(Du,{className:"bg-destructive hover:bg-destructive/90",onClick:o,children:"Delete"})]})]})})}function Xpe({placeholders:e,onClick:t}){return l.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:e==null?void 0:e.map(n=>l.jsxs("button",{type:"button",onClick:()=>t(n),className:"flex cursor-pointer flex-col items-start gap-1 rounded-control border border-border/60 bg-muted/30 px-2.5 py-2 text-left transition-colors hover:border-border hover:bg-muted/50",children:[l.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:n.title}),l.jsx("span",{className:"text-[12px] leading-[1.45] text-foreground/80",children:n.subtitle})]},n.title))})}var Qpe="vercel.ai.error",E0t=Symbol.for(Qpe),Jpe,D0t=class ege extends Error{constructor({name:t,message:n,cause:r}){super(n),this[Jpe]=!0,this.name=t,this.cause=r}static isInstance(t){return ege.hasMarker(t,Qpe)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}};Jpe=E0t;var of=D0t;function tge(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var nge="AI_InvalidArgumentError",rge=`vercel.ai.error.${nge}`,M0t=Symbol.for(rge),oge,R0t=class extends of{constructor({message:e,cause:t,argument:n}){super({name:nge,message:e,cause:t}),this[oge]=!0,this.argument=n}static isInstance(e){return of.hasMarker(e,rge)}};oge=M0t;var sge="AI_JSONParseError",ige=`vercel.ai.error.${sge}`,A0t=Symbol.for(ige),age,VK=class extends of{constructor({text:e,cause:t}){super({name:sge,message:`JSON parsing failed: Text: ${e}.
|
|
1341
1341
|
Error message: ${tge(t)}`,cause:t}),this[age]=!0,this.text=e}static isInstance(e){return of.hasMarker(e,ige)}};age=A0t;var lge="AI_TypeValidationError",cge=`vercel.ai.error.${lge}`,P0t=Symbol.for(cge),uge,F0t=class LF extends of{constructor({value:t,cause:n}){super({name:lge,message:`Type validation failed: Value: ${JSON.stringify(t)}.
|
|
1342
1342
|
Error message: ${tge(n)}`,cause:n}),this[uge]=!0,this.value=t}static isInstance(t){return of.hasMarker(t,cge)}static wrap({value:t,cause:n}){return LF.isInstance(n)&&n.value===t?n:new LF({value:t,cause:n})}};uge=P0t;var pk=F0t;class HK extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function I2(e){}function O0t(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=I2,onError:n=I2,onRetry:r=I2,onComment:o}=e;let s="",i=!0,a,c="",u="";function d(b){const x=i?b.replace(/^\xEF\xBB\xBF/,""):b,[y,w]=L0t(`${s}${x}`);for(const C of y)f(C);s=w,i=!1}function f(b){if(b===""){m();return}if(b.startsWith(":")){o&&o(b.slice(b.startsWith(": ")?2:1));return}const x=b.indexOf(":");if(x!==-1){const y=b.slice(0,x),w=b[x+1]===" "?2:1,C=b.slice(x+w);h(y,C,b);return}h(b,"",b)}function h(b,x,y){switch(b){case"event":u=x;break;case"data":c=`${c}${x}
|
|
1343
1343
|
`;break;case"id":a=x.includes("\0")?void 0:x;break;case"retry":/^\d+$/.test(x)?r(parseInt(x,10)):n(new HK(`Invalid \`retry\` value: "${x}"`,{type:"invalid-retry",value:x,line:y}));break;default:n(new HK(`Unknown field "${b.length>20?`${b.slice(0,20)}…`:b}"`,{type:"unknown-field",field:b,value:x,line:y}));break}}function m(){c.length>0&&t({id:a,event:u||void 0,data:c.endsWith(`
|
|
@@ -1389,4 +1389,4 @@ Defaulting to \`null\`.`}var Dbe=_be,sjt=Tbe;const L4=te.forwardRef(({className:
|
|
|
1389
1389
|
More info: ${o.docs}`:"",a=typeof o.message=="string"&&o.message.trim()?o.message.trim():typeof o.error=="string"&&o.error.trim()?o.error.trim():null;if(a){const c=s?` (code: ${s})`:"",u=s==="insufficient_quota"||a.toLowerCase().includes("quota")?`
|
|
1390
1390
|
|
|
1391
1391
|
Semaphor supports bring-your-own OpenAI API keys. Add yours in Settings or drop a note to support@semaphor.cloud and we’ll help you get set up.`:"";return`${a}${c}${i}${u}`}return null};if(typeof e=="string"){const r=e.trim();if(!r)return"Something went wrong.";try{const o=JSON.parse(r),s=t(o);if(s)return s}catch{}return r}const n=t(e);if(n)return n;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function q4({errorMessage:e}){return l.jsxs("div",{className:"flex items-start gap-2 rounded-control border border-red-300 bg-red-50/60 p-2 text-[12px] text-red-700 dark:border-red-900/60 dark:bg-red-950/20 dark:text-red-300",children:[l.jsx(Zs,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),l.jsx("span",{className:"whitespace-pre-wrap break-words leading-[1.55]",children:Ckt(e)})]})}function Skt({error:e,resetErrorBoundary:t}){return l.jsxs("div",{className:"my-3 space-y-2 rounded-control border border-border/60 bg-muted/20 p-2.5",children:[l.jsx(q4,{errorMessage:e==null?void 0:e.message}),l.jsx("button",{type:"button",className:"text-[11px] font-medium text-muted-foreground underline underline-offset-2 hover:text-foreground",onClick:t,children:"Try again"})]})}function Nkt({text:e,files:t}){return l.jsxs(exe,{who:"You",children:[e&&l.jsx("div",{className:"whitespace-pre-line text-[13px] leading-[1.55] text-foreground",children:e}),t&&t.length>0&&l.jsx("div",{className:"flex flex-wrap gap-2 pt-0.5",children:t.map(n=>l.jsx(ajt,{file:n},n.id))})]})}function jkt({text:e}){const t=e.split("|"),n=t[0],r=t[1]||"{}",o=JSON.parse(r);return l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"font-bold",children:"System Message:"})," ",n]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx("span",{className:"font-mono text-xs",children:"Scope:"}),l.jsx(_jt,{children:JSON.stringify(o,null,2)})]})]})}function txe(e,t){return!e||e.role!=="assistant"?!1:(e.parts??[]).some(r=>{if(!r)return!1;switch(r.type){case"text":return typeof r.text=="string"&&r.text.trim().length>0;case"reasoning":return typeof r.text=="string"&&r.text.trim().length>0||r.state==="streaming";case"error":return!0;default:return typeof r.type=="string"&&(r.type.startsWith("tool-")||r.type==="dynamic-tool")?H4(r,t):!1}})}function FG(){return l.jsx("span",{className:"relative grid h-2 w-2 shrink-0 place-items-center",children:l.jsx("span",{className:"absolute inset-0 animate-pulse rounded-full bg-muted-foreground/70"})})}function kkt({status:e,errorMessage:t,activeToolText:n}){return n?l.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-muted-foreground",children:[l.jsx(FG,{}),l.jsx("span",{children:n})]}):e==="submitted"||e==="streaming"?l.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-muted-foreground",children:[l.jsx(FG,{}),l.jsx("span",{children:e==="submitted"?"Thinking":"Generating"})]}):e==="error"?l.jsx(q4,{errorMessage:t}):null}function _kt(e){var t;return e?(t=[...e].reverse().find(n=>{var r;return n.role==="assistant"&&((r=n.parts)==null?void 0:r.some(o=>o.type==="text"&&typeof o.text=="string"&&o.text.trim().length>0))}))==null?void 0:t.id:void 0}function Ikt({message:e,messageIndex:t,messages:n,showTools:r=!1,onAddToDashboard:o,showSystemMessage:s=!1,handleRun:i,onQuickReply:a,disableQuickReplies:c=!1}){var y,w,C,N;const u=_kt(n),d=e.id===u;if(e.role==="user"){const S=((y=e.parts)==null?void 0:y.filter(T=>T.type==="text"))||[],j=((w=e.parts)==null?void 0:w.filter(T=>T.type==="file"))||[],_=S.map(T=>T.text).join(`
|
|
1392
|
-
`).trim(),k=j.map((T,I)=>{var R,A;let E="",D;if((R=T.url)!=null&&R.startsWith("data:")){const F=T.url.match(/data:[^;]+;base64,(.+)/);F&&(E=F[1],(A=T.mediaType)!=null&&A.startsWith("image/")&&(D=T.url))}return{id:`${e.id||t}-file-${I}`,name:T.filename||`File ${I+1}`,size:0,type:T.mediaType||"application/octet-stream",data:E,preview:D}});return l.jsx(Nkt,{text:_||void 0,files:k.length>0?k:void 0})}const f=((C=e.parts)==null?void 0:C.filter(S=>S.type==="reasoning"))||[],h=f.length>0,m=f.some(S=>S.state==="streaming"),g=f.filter(S=>S.text&&S.text.trim().length>0),b=h&&(g.length>0||m)?l.jsxs(vu,{className:"space-y-2",defaultOpen:!1,children:[l.jsx(wu,{asChild:!0,children:l.jsxs("button",{type:"button",className:"group inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:[l.jsx(Ft.ChevronRight,{className:"h-3 w-3 transition-transform duration-200 group-data-[state=open]:rotate-90"}),l.jsx("span",{className:m?"animate-pulse":"",children:m?"Reasoning":"Show reasoning"}),g.length>1&&l.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["(",g.length," steps)"]})]})}),l.jsx(Cu,{children:l.jsx("ol",{className:"space-y-2 border-l border-border/60 pl-3",children:g.map((S,j)=>l.jsxs("li",{className:"relative",children:[l.jsx("span",{className:"absolute -left-[15px] top-[3px] grid h-4 w-4 place-items-center rounded-full bg-muted font-mono text-[9px] text-muted-foreground",children:j+1}),l.jsx(IG,{className:"text-[12px] leading-[1.55] text-muted-foreground",text:S.text})]},`${e.id||t}-reasoning-${j}`))})})]},`${e.id||t}-reasoning`):null,x=(N=e.parts)==null?void 0:N.map((S,j)=>{var k;const _=`${e.id||t}-${j}`;switch(S.type){case"text":{const T=typeof S.text=="string"?S.text:JSON.stringify(S.text??"",null,2);if(e.role==="assistant"){const{cleanedText:I,quickReplies:E}=vkt(T),D=I.trim().length>0;return l.jsxs("div",{className:"space-y-2.5",children:[D&&l.jsx(IG,{text:I,handleRun:i,onAddToDashboard:o,messageId:e.id,messages:n}),E.length>0&&a&&d&&l.jsxs("div",{className:"space-y-1.5",children:[E.length>=3&&l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Suggested next steps"}),l.jsx("div",{className:"flex flex-wrap gap-1",children:E.map(({label:R,value:A},F)=>l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Button,{size:"sm",variant:"outline",className:"h-6 max-w-[220px] rounded-control border-border/60 bg-background px-2 text-[11px] font-normal text-foreground/85 transition-colors hover:border-border hover:bg-muted/40 hover:text-foreground disabled:opacity-50",disabled:c,onClick:()=>a(A),children:l.jsx("span",{className:"truncate",children:R})})}),l.jsx(p.TooltipContent,{side:"top",align:"center",children:l.jsx("p",{className:"max-w-xs text-xs",children:A})})]},`${_}-qr-${F}`))})]})]},_)}return e.role==="system"&&s?l.jsx(jkt,{text:T},_):null}case"error":{const T=S,I=T.errorText??T.error??T.message;return l.jsx("div",{className:"my-4",children:l.jsx(q4,{errorMessage:I})},_)}case"reasoning":return null;default:return((k=S.type)!=null&&k.startsWith("tool-")||S.type==="dynamic-tool")&&H4(S,r)?l.jsx(Si,{FallbackComponent:({error:T,resetErrorBoundary:I})=>l.jsx(Skt,{error:T,resetErrorBoundary:I}),children:l.jsx(pkt,{part:S,idx:_,messageId:e.id,showTools:r,onAddToDashboard:o,messages:n})},_):null}});return e.role==="assistant"?txe(e,r)?l.jsxs(exe,{who:"Assistant",className:"space-y-2",children:[b,x]}):null:l.jsxs("div",{className:"space-y-2",children:[b,x]})}const Tkt=8,Ekt=24,Dkt=20;function Mkt(e,t,n,r){return e==="error"&&t?!0:r?!1:!!(n||e==="submitted"||e==="streaming")}function nxe({messages:e,showTools:t=!1,showSystemMessage:n=!1,handleRun:r,onAddToDashboard:o,onQuickReply:s,disableQuickReplies:i=!1,status:a,errorMessage:c,activeToolText:u,className:d,rowContentClassName:f,statusClassName:h,latestButtonClassName:m,scrollToEndSignal:g=0}){const b=v.useRef(null),x=v.useRef(null),y=v.useRef(e.length),w=v.useRef(!1),C=v.useRef(null),N=v.useRef(!1),S=v.useRef(g),[j,_]=v.useState(!0),[k,T]=v.useState(0),[I,E]=v.useState(Ekt);S.current!==g&&(S.current=g,N.current=!0);const D=e[e.length-1],R=txe(D,t),A=Mkt(a,c,u,R),F=uI({count:e.length,getScrollElement:()=>b.current,estimateSize:H=>{const M=e[H];return(M==null?void 0:M.role)==="user"?88:180},getItemKey:H=>{const M=e[H];return(M==null?void 0:M.id)||`message-${H}`},anchorTo:"end",followOnAppend:!0,scrollEndThreshold:Tkt,overscan:6,gap:20,paddingEnd:A?I+Dkt:0,useAnimationFrameWithResizeObserver:!0,onChange:H=>{const M=H.isAtEnd();_(B=>B===M?B:M),M&&T(0)}}),z=v.useCallback((H="smooth")=>{C.current!==null&&cancelAnimationFrame(C.current),C.current=requestAnimationFrame(()=>{C.current=null,F.scrollToEnd({behavior:H})}),T(0),_(!0)},[F]);v.useLayoutEffect(()=>{w.current||(w.current=!0,z("auto"))},[z]),v.useLayoutEffect(()=>{N.current&&(N.current=!1,z("auto"))},[e.length,g,z]),v.useEffect(()=>{const H=y.current;y.current=e.length,e.length>H&&!F.isAtEnd()&&T(M=>M+e.length-H),e.length===0&&(T(0),_(!0),w.current=!1,N.current=!1)},[e.length,F]);const L=F.getVirtualItems(),$=F.getTotalSize();return v.useEffect(()=>()=>{C.current!==null&&cancelAnimationFrame(C.current)},[]),v.useLayoutEffect(()=>{const H=x.current;if(!H||!A)return;const M=()=>{const W=Math.ceil(H.getBoundingClientRect().height);W>0&&E(P=>P===W?P:W)};if(M(),typeof ResizeObserver>"u")return;const B=new ResizeObserver(M);return B.observe(H),()=>B.disconnect()},[A,a,c,u]),l.jsxs(l.Fragment,{children:[l.jsx(hl,{"data-role":"assistant-virtualized-scroll-area",ref:b,className:p.cn("min-h-0 min-w-0 flex-1 basis-0",d),children:l.jsxs("div",{className:"relative w-full",style:{height:$},children:[L.map(H=>{const M=e[H.index];return M?l.jsx("div",{ref:F.measureElement,"data-index":H.index,className:"absolute left-0 top-0 w-full",style:{transform:`translateY(${H.start}px)`},children:l.jsx("div",{className:p.cn("min-w-0",f),children:l.jsx(Ikt,{message:M,messageIndex:H.index,messages:e,showTools:t,showSystemMessage:n,handleRun:r,onAddToDashboard:o,onQuickReply:s,disableQuickReplies:i})})},H.key):null}),A&&l.jsx("div",{ref:x,className:p.cn("absolute left-0 top-0 w-full",h),style:{transform:`translateY(${Math.max($-I,0)}px)`},children:l.jsx("div",{className:p.cn("min-w-0",f),children:l.jsx(kkt,{status:a,errorMessage:c,activeToolText:u})})})]})}),!j&&l.jsxs("button",{type:"button",onClick:()=>z("smooth"),"aria-label":"Scroll to latest",className:p.cn("absolute right-4 z-10 inline-flex h-7 items-center gap-1.5 rounded-full border border-border bg-background px-2.5 text-[11px] text-foreground shadow-[0_1px_2px_rgba(0,0,0,0.08)] transition-colors hover:bg-muted/40",m),children:[l.jsx(es,{className:"h-3 w-3"}),"Latest",k>0&&l.jsx("span",{className:"grid h-4 min-w-[16px] place-items-center rounded-full bg-foreground px-1 font-mono text-[9px] tabular-nums text-background",children:k>9?"9+":k})]})]})}function Rkt(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return"";const t=e;return(typeof t.userSql=="string"?t.userSql:"")||(typeof t.sourceSql=="string"?t.sourceSql:"")||(typeof t.sql=="string"?t.sql:"")}const Akt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Pkt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:o}){const[s,i]=v.useState(!1),[a,c]=v.useState(dt.isDevEnv),[u,d]=v.useState(!1),[f,h]=v.useState("auto"),[m,g]=v.useState(!1),[b,x]=v.useState(!1),[y,w]=v.useState(0),C=n??b,{isLocalDev:N,isConsoleMode:S}=Lm(),j=N||S||a,_=v.useRef(null);p.useDashboardStore(re=>re.dashboard.aiScopeTables),p.useDashboardStore(re=>re.isDashboardEditing);const k=p.useDashboardStore(re=>re.selectedSheetId),{setDataSource:T}=p.useEditorActions(),{setSelectedFrameId:I,setIsDashboardEditing:E}=p.useDashboardActions(),D=Q$(),{clearAssistantMessageContexts:R}=p.useAIActions(),{clearQueue:A}=p.useQueueActions(),{clearFileAttachments:F,getFileAttachments:z}=p.useFileActions(),L=p.useFileAttachments("dashboard"),$=p.useEditorStore(re=>re.card.dataSource),{assistantProfile:H}=vbe(),M=p.useDashboardStore(re=>re.handleOpenAssistantProfile),{selectedEntities:B,applyDashboardDefaultEntities:W}=eT("dashboard"),{sendMessage:P,isLoading:G,messages:Z,setMessages:X,status:Y,stop:O,errorMessage:q,clearError:U}=zNt({dynamicVisualMode:f}),V=v.useCallback(()=>{w(re=>re+1)},[]),K=v.useCallback(re=>{r==null||r(re),n===void 0&&x(re)},[n,r]),Q=v.useCallback(()=>{K(!C)},[C,K]);v.useEffect(()=>{if(!C)return;function re(pe){pe.key==="Escape"&&K(!1)}return window.addEventListener("keydown",re),()=>{window.removeEventListener("keydown",re)}},[C,K]);const[se,oe]=v.useState(""),me=re=>{oe(re.target.value)};async function le({sql:re,cardTitle:pe,connectionId:Ee,cardType:Te,python:ze,cardConfig:Pe,dataSource:He,customVisualPreferences:ye,visualizationMode:Ke,dynamicCardPreferences:We}){if(!k)return;const Qe=Ke==="dynamic",xe=dt.hasValidCardConfig(Pe),Ve=Ee||(He==null?void 0:He.connectionId)||"",Ae=He?{...He,connectionId:Ve||He.connectionId,connectionType:He.connectionType||"",mode:He.mode||"database",selectedEntities:He.selectedEntities||[]}:Ve?{connectionId:Ve,connectionType:"",mode:"database",selectedEntities:[]}:sb,Be=!(xe&&(!Qe||(We==null?void 0:We.provenance)==="card-config"||(We==null?void 0:We.provenance)==="query_spec")),Ie=Be?Rkt(re):"",$e=Be?ze:"",st={id:dt.v4(),title:pe||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Te==="horizontalBar"?"y":"x"},...Qe&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:Te,sql:Ie,python:$e,dataSource:Ae,config:Pe,connectionId:Ve,visualizationMode:Ke,dynamicCardPreferences:We,customCardPreferences:ye?{url:ye.url,componentName:ye.componentName,pluginChartType:ye.pluginChartType,settings:ye.settings,type:"component"}:void 0},ct={id:dt.v4(),cards:[st],activeCardId:st.id};try{await D(k,ct,"end"),E(!0),I(ct.id)}catch(rt){console.error("Failed to add assistant visual to dashboard:",rt),lt.error(rt instanceof Error?rt.message:"Failed to prepare semantic metadata for the new visual")}}const ue=re=>{re.preventDefault();const pe=se.trim();if(!pe&&L.length===0)return;const Ee=[];pe&&Ee.push({type:"text",text:pe}),L.forEach(Te=>{Te.data&&Ee.push({type:"file",mediaType:Te.type,filename:Te.name,url:`data:${Te.type};base64,${Te.data}`})}),P({role:"user",parts:Ee}),oe(""),F("dashboard"),V()};v.useEffect(()=>{var re;e&&((re=_.current)==null||re.focus())},[e]),Obe({assistantType:"dashboard",status:Y,isLoading:G,sendMessage:P});const{hasActiveTools:ne,activeToolText:de}=Lbe(Z);function Ce(re){const pe={role:"user",parts:[{type:"text",text:re.title+" "+re.subtitle}]};P(pe),V()}function ce(re){P({role:"user",parts:[{type:"text",text:re}]}),V()}function ie(re){P({role:"user",parts:[{type:"text",text:re}]}),V()}const we=v.useCallback(async()=>{const re=JSON.stringify(Z??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(re),lt.success("Conversation copied")}catch(pe){console.error("Failed to copy conversation",pe),lt.error("Unable to copy conversation")}},[Z]),fe=(se==null?void 0:se.length)===0&&(Z==null?void 0:Z.filter(re=>re.role==="user").length)===0;function ae(){return l.jsx("div",{"data-role":"header",className:"flex items-center gap-2",children:l.jsx("span",{className:"text-[13px] font-medium text-foreground",children:"Assistant"})})}function ee(){return l.jsxs(Uo,{children:[l.jsx(Wo,{asChild:!0,children:l.jsx(nu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(Rm,{className:"size-3.5"})})}),l.jsxs(Do,{align:"end",children:[l.jsx(qa,{children:"Options"}),l.jsx(Sa,{}),l.jsx(nd,{checked:s,onCheckedChange:i,children:"Token Usage"}),l.jsx(nd,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(nd,{checked:u,onCheckedChange:d,children:"System Message"}),(N||S)&&l.jsxs(l.Fragment,{children:[l.jsx(Sa,{}),l.jsx(qa,{children:"Dynamic Visuals"}),l.jsx(nd,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(nd,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(nd,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const J=l.jsxs("div",{"data-role":"dashboard-assistant",className:p.cn("relative flex h-full grow flex-col break-words bg-background",C&&"rounded-card border border-border/60 shadow-xl"),children:[l.jsxs("header",{"data-role":"header-section",className:"flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3",children:[ae(),M&&l.jsxs("button",{type:"button",onClick:M,className:"inline-flex h-6 items-center gap-1 rounded-[4px] border border-border/60 bg-muted/40 px-1.5 text-[11px] text-muted-foreground transition-colors hover:border-border hover:text-foreground",title:"Edit assistant profile",children:[l.jsx("span",{className:"h-1 w-1 rounded-full bg-muted-foreground/60"}),l.jsx("span",{className:"max-w-[180px] truncate",children:(H==null?void 0:H.name)||"Default profile"})]}),l.jsxs("div",{"data-role":"header-actions",className:"ml-auto flex items-center gap-0.5",children:[S&&ee(),j&&l.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-6 px-1.5 text-[11px] text-muted-foreground hover:text-foreground",onClick:we,children:"Copy Conversation"}),l.jsx(nu,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:C?"Exit fullscreen":"Expand",onClick:Q,children:C?l.jsx(Ft.Minimize2,{className:"h-3.5 w-3.5"}):l.jsx(Ft.Maximize2,{className:"h-3.5 w-3.5"})}),l.jsx(nu,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:"New chat",onClick:()=>{const re=Z.filter(pe=>pe.role==="assistant").map(pe=>pe.id).filter(pe=>!!pe);X([]),A("dashboard"),U(),R(re)},children:l.jsx(DO,{className:"h-3.5 w-3.5"})}),l.jsx(nu,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:"Close",onClick:()=>{t(!1)},children:l.jsx(je.X,{className:"h-3.5 w-3.5"})})]})]}),l.jsx(nxe,{messages:Z,showTools:a,showSystemMessage:u,onAddToDashboard:le,onQuickReply:ie,disableQuickReplies:G,status:Y,errorMessage:q,activeToolText:G&&ne?de:void 0,className:p.cn(C?"px-6 py-5":"px-3 py-3"),rowContentClassName:p.cn(C&&"mx-auto w-full max-w-[680px]"),latestButtonClassName:e?"bottom-[148px]":"hidden",scrollToEndSignal:y}),l.jsxs("div",{className:"shrink-0 space-y-2 border-t border-border/60 px-3 pb-3 pt-2",children:[!H&&fe&&l.jsx(Xpe,{onClick:Ce,placeholders:Akt}),fe&&H&&l.jsx(wbe,{seedQuestions:H.seedQuestions||[],handleSeedQuestionClick:ce}),l.jsx(Fbe,{assistantType:"dashboard"}),l.jsx(V4,{ref:_,setInput:oe,stop:O,input:se,handleInputChange:me,handleSubmit:re=>{ue(re)},isLoading:G,status:Y,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(B4,{incomingSelectedEntities:B,open:m,onOpenChange:g,dataSource:$||sb,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:re=>W()})]});return C&&o?br.createPortal(l.jsx(Kb,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background/95 px-4 pb-4 pt-[calc(var(--app-header-height,15px)+0.5rem)] backdrop-blur-sm",children:l.jsx("div",{className:"flex h-full w-full",children:J})}),o):J}function Fkt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=p.useDashboardActions(),o=_ue(),s=p.useDashboardStore(d=>d.dashboard.sheets),a=p.useDashboardStore(d=>d.selectedSheetId)??(s==null?void 0:s[0].id),c=p.useDashboardStore(d=>d.isDashboardEditing),u=p.useDashboardStore(d=>d.isVisualEditing);v.useEffect(()=>{if(!c||u)return;async function d(m){if(Okt(m.target))return;const g=m.ctrlKey||m.metaKey;g&&m.key==="c"?(await f(),lt.success("Card copied to clipboard"),m.preventDefault()):g&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText(),g=Lkt(m);if(g!=null&&g.id){const b=Nue(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await o(a,b),r(b.id),lt.success("Card pasted from clipboard")}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[o,n,r,a,c,u,t])}function Okt(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.closest("[contenteditable]");return t&&t.getAttribute("contenteditable")!=="false"?!0:!!e.closest('input, textarea, select, [role="textbox"]')}function Lkt(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.id=="string"&&Array.isArray(t.cards)?t:null}catch{return null}}function $kt(e,t){switch(e.interactionMode){case"drillToDetail":zkt(e,t);break;case"drillThrough":Bkt(e,t);break;case"drillToURL":Vkt(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 zkt(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:o,filterGroups:s}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=s.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=s.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}o==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function Bkt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:o,sourceCardId:s}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=o.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Vkt(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 Hkt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:o,contextMode:s,cardTitle:i,cardDescription:a}){return l.jsx(Mo,{open:e,onOpenChange:t,children:l.jsxs(go,{className:"flex max-h-[90vh] max-w-[90vw] flex-col gap-0 overflow-hidden p-0",children:[l.jsxs(Is,{className:"space-y-1 border-b border-border px-5 pb-3.5 pt-4 text-left",children:[l.jsx(bo,{className:"text-[15px] font-semibold tracking-tight",children:i||"Insight detail"}),l.jsx(Ro,{className:"text-[12px] leading-[1.5] text-muted-foreground",children:a||"View detailed insight data with applied filters"})]}),l.jsx(Mue,{filters:r,filterDefinitions:o,contextMode:s}),l.jsx("div",{className:"h-[400px] min-h-0 flex-1 overflow-auto px-5 py-4",children:n?l.jsx(Bfe,{insightId:n,filters:r,contextMode:s}):l.jsx("div",{className:"flex items-center justify-center p-12 text-[13px] text-muted-foreground",children:"No insight selected"})})]})})}function qkt(){const e=p.useInteractionStore(N=>N.interactionStates),t=p.useInteractionStore(N=>N.setInteractionState),n=p.useInteractionStore(N=>N.clearLastInteractionEvent),r=p.useInteractionStore(N=>N.replaceCardWithInsight),o=p.useInteractionStore(N=>N.setPendingDrillThrough),s=p.useInteractionStore(N=>N.pendingDrillThrough),i=p.useInteractionStore(N=>N.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=p.useDashboardActions(),{selectDashboard:u}=Dm(),d=p.useDashboardStore(N=>N.dashboard),f=p.useDashboardStore(N=>N.filterValues),{data:h,isLoading:m}=UX((s==null?void 0:s.targetDashboardId)||"",{enabled:!!(s!=null&&s.targetDashboardId)}),[g,b]=v.useState({open:!1,insightId:""}),x=Vfe(g.insightId,{enabled:g.open&&!!g.insightId}),y=v.useRef(new Set),w=v.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:N,filters:S,contextMode:j})=>{b({open:!0,insightId:N,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:j})},replaceCardContent:({cardId:N,insightId:S,filters:j,contextMode:_})=>{r(N,S,j,_)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:o,setGlobalDrillContext:({filters:N,contextMode:S,sourceDashboardId:j,sourceDashboardTitle:_,targetDashboardId:k})=>{const T={filters:N},I={sourceCardId:p.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[T]},E={...p.createInitialInteractionState(),appliedClickFilters:[I],contextMode:S,sourceDashboardId:j,sourceDashboardTitle:_,targetDashboardId:k};t(p.DRILL_CONTEXT_CARD_ID,E)}}),[a,r,f,c,d,o,t]);v.useEffect(()=>{Object.entries(e).forEach(([N,S])=>{if(S!=null&&S.lastInteractionEvent){const j=S.lastInteractionEvent,_=`${N}-${j.interactionMode}-${j.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{$kt(j,w)}catch(k){console.error("Error executing interaction event:",k)}finally{n(N),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,w]),v.useEffect(()=>{if(!(!s||!h||m))try{u(h),c(s.targetDashboardId,s.sourceDashboardId,s.sourceDashboardTitle,s.filters,s.contextMode),i()}catch(N){console.error("[DrillThrough] Error during automatic navigation:",N),i()}},[s,h,m,u,c,i]);const C=()=>{b({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Hkt,{open:g.open,onOpenChange:C,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),s&&m&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[l.jsx(p.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Ukt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,o=Wkt(ez(t));return r==="="?`${n} = ${o}`:`${n} ${r} ${o}`}).join(", ")}function Wkt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function Kkt(e){return e?`Back to ${e}`:"Back"}function Gkt(){var y,w,C,N,S;const e=p.useInteractionStore(j=>j.interactionStates[p.DRILL_CONTEXT_CARD_ID]),t=p.useDashboardStore(j=>j.actions.goBackFromDrill),n=p.useDashboardStore(j=>j.actions.clearDrillContext),{selectDashboard:r}=Dm(),[o,s]=v.useState({x:16,y:16}),[i,a]=v.useState(!1),c=v.useRef({x:0,y:0});v.useEffect(()=>{if(!i)return;const j=k=>{s({x:k.clientX-c.current.x,y:k.clientY-c.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",j),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((N=(C=(w=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:w.filterGroups)==null?void 0:C[0])==null?void 0:N.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 m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(j){console.error("[DrillBack] Error during back navigation:",j)}},g=()=>{n()},b=j=>{j.target.closest("button")||(a(!0),c.current={x:j.clientX-o.x,y:j.clientY-o.y})};Ukt(f);const x=Kkt(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${o.x}px, ${o.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:b,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((j,_)=>{const k=j.field.label||j.field.name,T=String(j.value);return l.jsxs(mi,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",T]},_)})})]}),l.jsx(p.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(je.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(p.Button,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(zv,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Ykt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Zkt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:o,filterQueryContext:s,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:m,transition:g,isDragging:b}=tx({id:`filter:${e.id}`,disabled:n||!t}),x={transform:Ki.Translate.toString(m),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return l.jsx("div",{ref:h,style:x,...d,children:l.jsx(P$,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:o,filterQueryContext:s,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u})})}const OG="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Xkt=[];function rxe({open:e,onOpenChange:t}){const[n,r]=v.useState(!1),[o,s]=v.useState(!1),[i,a]=v.useState({sheetSelection:"current",protectPdf:!1,password:""}),c=p.useDashboardStore(X=>{var Y;return(Y=X.dashboard)==null?void 0:Y.sheets}),u=p.useDashboardStore(X=>X.dashboard),d=p.useDashboardStore(X=>X.dashboardInputValues),f=p.useDashboardStore(X=>X.filterValues),h=p.useDashboardStore(X=>X.controlValues),m=p.useDashboardStore(X=>X.inlineFilterValuesMap),g=p.useDashboardStore(X=>X.cardControlValuesMap),b=p.useDashboardStore(X=>X.selectedSheetId),x=p.useDashboardStore(X=>X.selectedSheetId?X.documentInputRuntimeBySheetId[X.selectedSheetId]:void 0),y=p.useDashboardStore(X=>X.isDownloadingPdf),w=p.useDashboardStore(X=>X.reportContext),{authToken:C,tokenProps:N}=It(),S=c==null?void 0:c.find(X=>X.id===b),j=v.useMemo(()=>p.getDashboardExportSheets(c),[c]),_=p.isDocumentSheet(S),k=_&&S?S.document:void 0,T=v.useMemo(()=>_&&S?rx(u,S.id):[],[S,_,u]),I=T.length>0,E=v.useMemo(()=>_&&S?kpe(u,S.id):!1,[S,_,u]),D=v.useMemo(()=>I?T.map(lC):(k==null?void 0:k.inputs)||Xkt,[k,T,I]),R=w==null?void 0:w.calendar.tz,A=v.useMemo(()=>Nme(D),[D]),F=v.useMemo(()=>Cme(D,R),[D,R]),z=v.useMemo(()=>Sme(D),[D]),L=x?x.filterValuesByInputId:F,$=x?x.controlValuesByInputId:z,H=v.useMemo(()=>_?E&&S&&k?YY({dashboard:u,sheetId:S.id,sheetKind:"document",sectionIds:k.sections.map(X=>X.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},timezone:R}):_me(D,L,$,A,A):[],[k,D,S,_,u,g,h,f,m,d,$,L,A,R,E]),M=!!S,B=j.length>0,W=((c==null?void 0:c.length)||0)>1||_,P=i.sheetSelection==="current"&&(!M||_&&H.length>0)||i.sheetSelection==="all"&&!B;v.useEffect(()=>{e&&i.sheetSelection==="all"&&!B&&a(X=>({...X,sheetSelection:"current"}))},[B,e,i.sheetSelection]);const G=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function Z(){if(y){lt.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){lt.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!M){lt.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!B){lt.error("No dashboard sheets are available to export");return}s(!0);const X=i.sheetSelection==="current"&&_,Y=X?i.protectPdf?"Generating protected document PDF... may take up to 60 seconds":"Generating document PDF... may take up to 60 seconds":i.sheetSelection==="all"?"Generating PDF for all dashboard sheets... This may take a while.":i.protectPdf?"Generating protected PDF... may take up to 60 seconds":"Generating PDF... may take up to 60 seconds",O=lt.loading(Y);try{if(X){if(!k||!S)throw new Error("Selected document sheet is missing document data");if(H.length>0){lt.dismiss(O),lt.error(`Set ${H.join(", ")} before exporting`);return}const U=new Date().toISOString(),V=E?ZY({dashboard:u,sheetId:S.id,sheetKind:"document",sectionIds:k.sections.map(K=>K.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},generatedAt:U,timezone:R}).snapshot:void 0;await Q5(N.apiServiceUrl,C,{sheetId:S.id,title:S.title||"Document",pageSize:k.page.size,orientation:k.page.orientation,timezone:R,password:i.protectPdf?i.password:void 0,inputSnapshot:V,...V?{}:{inputValues:{sheetId:S.id,filterValuesByInputId:L,controlValuesByInputId:$,generatedAt:U}}})}else{const U=eoe();await Uee(N.apiServiceUrl,C,i.protectPdf?i.password:void 0,i.sheetSelection,U)}lt.dismiss(O);const q=X?i.protectPdf?"Protected document PDF downloaded successfully!":"Document PDF downloaded successfully!":i.sheetSelection==="all"?"Dashboard sheets PDF downloaded successfully!":i.protectPdf?"Protected PDF downloaded successfully!":"PDF downloaded successfully!";lt.success(q,{duration:2e3}),G()}catch(q){lt.dismiss(O),lt.error("Failed to download PDF",{description:j_(q,"Please try again or contact support."),descriptionClassName:N_,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",q)}finally{s(!1)}}return l.jsx(Mo,{open:e,onOpenChange:X=>{if(!X){G();return}t(!0)},children:l.jsxs(go,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[l.jsxs(Is,{children:[l.jsx(bo,{className:"text-[15px]",children:_?"Export document":"Export dashboard"}),l.jsx(Ro,{className:"text-[13px] leading-5",children:_?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),l.jsxs("div",{className:"space-y-4 py-1",children:[W&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(p.Label,{className:OG,children:"Export scope"}),l.jsxs(rl,{value:i.sheetSelection,onValueChange:X=>a({...i,sheetSelection:X}),className:"gap-1.5",children:[l.jsxs(p.Label,{htmlFor:"scope-current",className:p.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!M&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(vs,{value:"current",id:"scope-current",disabled:!M}),_?"This document":"This sheet"," (",(S==null?void 0:S.title)||"Current",")"]}),l.jsxs(p.Label,{htmlFor:"scope-all",className:p.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!B&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(vs,{value:"all",id:"scope-all",disabled:!B}),"Dashboard sheets (",j.length," ",j.length===1?"sheet":"sheets",")"]})]}),_&&l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:H.length>0?`Set ${H.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),l.jsx(p.Separator,{className:"bg-border/60"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs(p.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[l.jsx(Tn,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:X=>{a({...i,protectPdf:X,password:X?i.password:""}),X||r(!1)}}),l.jsx(Vv,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&l.jsxs("div",{className:"ml-6 space-y-1.5",children:[l.jsx(p.Label,{htmlFor:"pdf-password",className:OG,children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(p.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:X=>a({...i,password:X.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:X=>{X.key==="Enter"&&i.password&&Z()}}),l.jsx("button",{type:"button",className:"absolute right-1 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>r(!n),"aria-label":n?"Hide password":"Show password",children:n?l.jsx(Ak,{className:"h-3.5 w-3.5"}):l.jsx(Ft.Eye,{className:"h-3.5 w-3.5"})})]}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),l.jsxs(tl,{children:[l.jsx(p.Button,{variant:"outline",size:"xs",onClick:G,disabled:o,children:"Cancel"}),l.jsx(p.Button,{size:"xs",onClick:Z,disabled:o||y||P,children:o?l.jsxs(l.Fragment,{children:[l.jsx(p.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):l.jsxs(l.Fragment,{children:[l.jsx(Su,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function oxe({iconClassName:e,open:t,onOpenChange:n}){const[r,o]=v.useState(!1),s=t!==void 0,i=s?t:r,a=u=>{s||o(u),n==null||n(u)},c=p.useDashboardStore(u=>u.isDownloadingPdf);return l.jsxs(l.Fragment,{children:[s?null:l.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:c,onClick:()=>a(!0),children:l.jsx(Su,{className:p.cn("size-4",e)})}),l.jsx(rxe,{open:i,onOpenChange:a})]})}function LG(e,t,n){const r=new Set(t),o=[...n];return e.map(s=>r.has(s.id)?o.shift()??s.id:s.id)}function Qkt({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:o,listeners:s,setNodeRef:i,transform:a,transition:c,isDragging:u}=tx({id:`control:${e.id}`,disabled:!n}),d={transform:Ki.Translate.toString(a),transition:c,opacity:u?.5:1,zIndex:u?10:void 0};return l.jsx("div",{ref:i,style:d,...o,children:l.jsx(qme,{control:e,value:t,isEditing:n,dragListeners:n?s:void 0,onChange:r})})}function $G(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function zG(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function Jkt(e,t,n){const r=new Set([...t.map(a=>`filter:${a.id}`),...n.map(a=>`control:${a.id}`)]);if(!(e!=null&&e.length))return zG(t,n);const o=e.filter(a=>r.has(a)),s=new Set(o),i=zG(t,n).filter(a=>!s.has(a));return[...o,...i]}function e_t(e,t){return p.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function t_t(e){return Qh(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>Qh(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function F2(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function n_t(e){return sxe(e).filter(t=>{var n,r;return t.filter.hide||t.filter.location==="frame"?!1:((n=t.compatibility)==null?void 0:n.source)==="dashboardFilter"?!0:(((r=t.presentation)==null?void 0:r.placement)||"toolbar")==="toolbar"})}function sxe(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=e_t(e.dashboard,t);return Rk(ab({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!t_t({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function r_t(e,t){return"toolbar"}function o_t(){const e=dc("interactive"),t=p.useDashboardStore(q=>q.selectedSheetId),n=p.useDashboardStore(q=>q.dashboard.filters),r=p.useDashboardStore(q=>q.dashboard.filterLayout),o=p.useDashboardStore(q=>q.isDashboardEditing),s=p.useDashboardStore(q=>q.controlValues),i=p.useDashboardStore(q=>q.filterValues);p.useDashboardStore(q=>q.filteringCards);const a=p.useDashboardStore(q=>q.inlineFilterValuesMap),c=p.useDashboardStore(q=>q.dashboardInputValues),u=p.useInteractionStore(q=>q.clearAllClickFilters),d=p.useInteractionStore(q=>Object.entries(q.interactionStates).reduce((U,[V,K])=>{var Q;return V===p.DRILL_CONTEXT_CARD_ID?U:U+(((Q=K.appliedClickFilters)==null?void 0:Q.length)??0)},0)),f=p.useDashboardStore(q=>q.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:m,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:w,setFilteringCards:C,upsertDashboardInput:N}=p.useDashboardActions(),S=oT(nb(Jb,{activationConstraint:{distance:5}})),j=p.useDashboardStore(q=>q.dashboard),_=n_t({dashboard:j,selectedSheetId:t}).filter(q=>r_t(q.filter)==="toolbar"),k=sxe({dashboard:j,selectedSheetId:t}),T=_.map(q=>q.filter),I=new Map(_.map(q=>[`filter:${q.filter.id}`,q])),E=stt(j),D=E.filter(q=>!q.hidden&&nv(q)==="toolbar"),R=E.filter(q=>!q.hidden&&nv(q)==="advanced"),A=Jkt(r==null?void 0:r.toolbarItemOrder,T,D),F=new Map(T.map(q=>[`filter:${q.id}`,q])),z=new Map(D.map(q=>[`control:${q.id}`,q]));function L(q){const{active:U,over:V}=q;if(!V||U.id===V.id)return;const K=String(U.id),Q=String(V.id),se=A.findIndex(ce=>ce===K),oe=A.findIndex(ce=>ce===Q);if(se===-1||oe===-1)return;const me=ex(A,se,oe);y({toolbarItemOrder:me});const le=new Set((n||[]).map(ce=>ce.id)),ue=A.filter(ce=>ce.startsWith("filter:")).map(ce=>ce.replace("filter:","")).filter(ce=>le.has(ce)),ne=me.filter(ce=>ce.startsWith("filter:")).map(ce=>ce.replace("filter:","")).filter(ce=>le.has(ce)),de=A.filter(ce=>ce.startsWith("control:")).map(ce=>ce.replace("control:","")),Ce=me.filter(ce=>ce.startsWith("control:")).map(ce=>ce.replace("control:",""));h(LG(n||[],ue,ne)),g(LG(j.controls||[],de,Ce))}const $=(r==null?void 0:r.toolbarWrap)??!1,H=(r==null?void 0:r.showDownloadButton)??!1,M=k.filter(F2),B=k.filter(q=>{if(F2(q))return!1;const U=p.getDashboardInputRuntimeSlot(c,q,{sheetId:t});return(U==null?void 0:U.status)==="set"||(U==null?void 0:U.status)==="cleared"}),W=new Set([...M,...B].map(q=>q.filter.id)),P=(i==null?void 0:i.filter(q=>!W.has(q.filterId)&&$G(q)).length)??0,G=[...M,...B],Z=G.filter(q=>{const U=p.hydrateAuthoredDashboardInputSlot({dashboard:j,input:q,runtimeValues:c,target:{sheetId:t}});return(U==null?void 0:U.status)==="set"&&U.value.kind==="filter"&&$G(U.value.filterValue)}).length,X=a?Object.values(a).reduce((q,U)=>q+((U==null?void 0:U.length)??0),0):0,Y=P+Z+X+d,O=()=>{w([]),G.forEach(q=>{m(q,{sheetId:t})}),C([]),u(),a&&Object.entries(a).forEach(([q,U])=>{U==null||U.forEach(V=>{f(q,V.filterId)})})};return!T.length&&!D.length&&!R.length&&!H&&Y===0?null:l.jsx("div",{className:"z-20 border-b border-border/60 bg-background/95 px-3 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/85",style:e.containerStyle,role:"toolbar","aria-label":"Dashboard filters and controls",children:l.jsx(nC,{sensors:S,collisionDetection:Jw,onDragEnd:L,children:l.jsxs("div",{className:p.cn("flex items-center",$?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[l.jsx(rC,{items:A,strategy:Oz,children:l.jsx(MF,{className:"gap-3 pr-0",wrap:$,children:A.map(q=>{const U=F.get(q);if(U){const K=I.get(q),Q=K&&F2(K);return l.jsx(Zkt,{filter:U,isEditing:o,storageOptions:Q?{storageTarget:"dashboardInput",dashboardInput:K,sheetId:t??void 0}:void 0,inputVariableName:Q?K.variableName:void 0,onUpdateFilter:Q?(se,oe)=>{N({...K,variableName:(oe==null?void 0:oe.variableName)||K.variableName,filter:se})}:void 0,onRemoveFilter:Q?()=>{w((i||[]).filter(se=>se.filterId!==U.id)),b(K.id)}:void 0},q)}const V=z.get(q);return V?l.jsx(Qkt,{control:V,value:s==null?void 0:s[V.id],isEditing:o,onChange:K=>x(V.id,K)},q):null})})}),R.length>0&&l.jsx(zue,{title:"",controls:R,values:s,onChange:(q,U)=>x(q.id,U),immediatePlacement:"toolbar",advancedLabel:"More controls"}),Y>0&&l.jsxs("button",{type:"button",onClick:O,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(je.X,{className:"h-3 w-3"}),"Clear all",l.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:Y})]}),H&&l.jsx("div",{className:p.cn(Y>0?"ml-1.5":"ml-auto"),children:l.jsx(oxe,{})})]})})})}function ixe(){var ie,we;const{showAssistant:e,tokenProps:t,renderMode:n}=It(),r=Ykt((ie=t.config)==null?void 0:ie.showDashboardAssistant,e),{preferences:o}=Lm(),s=(we=o==null?void 0:o.cardDisplay)==null?void 0:we.mode,i=mf(s),a=eee({displayMode:s,renderMode:n}),c=v.useRef(null),u=v.useRef(null),[d,f]=v.useState(!1),{handleDragStart:h,isDraggingRef:m,getStyle:g,getPositionClasses:b}=I0t({initialPosition:"bottom-right"}),x=Mh(fe=>fe.setFullscreen),y=Mh(fe=>fe.setPanelOpen),w=Mh(fe=>fe.setContainer),C=GQ("dashboard"),N=YQ(),S=ZQ("dashboard"),j=C.isOpen,_=N==="dashboard",k=p.useDashboardStore(fe=>fe.isVisualEditing),T=p.useDashboardStore(fe=>fe.themeStyle),I=Ru(),E=p.useDashboardStore(fe=>{var ae;return(ae=fe.dashboard)==null?void 0:ae.sheets}),D=p.useDashboardStore(fe=>fe.showFilters),R=p.useDashboardStore(fe=>fe.isDashboardEditing),A=p.useDashboardStore(fe=>fe.selectedSheetId),F=E==null?void 0:E.find(fe=>fe.id===A),z=p.useDashboardStore(fe=>{var ae,ee,J;return(J=(ee=(ae=fe.dashboard)==null?void 0:ae.sheets)==null?void 0:ee.find(re=>re.id===fe.selectedSheetId))==null?void 0:J.kind}),L=p.useDashboardStore(fe=>{var ae,ee;return((ee=(ae=fe.dashboard)==null?void 0:ae.summary)==null?void 0:ee.position)||"top"}),$=z==="document",H=p.useDashboardStore(fe=>{var ae;return(ae=fe.dashboard)==null?void 0:ae.id}),{getDefaultSheetId:M,setDefaultSheetId:B,clearDefaultSheetId:W}=_Y(H),[P,G]=v.useState(null),{setSelectedSheetId:Z,setSheetTitle:X,addSheet:Y,setSheets:O}=p.useDashboardActions();Fkt(u);const{setActiveAssistantType:q}=p.useAIActions();v.useEffect(()=>{if(H){const fe=M();G(fe)}},[H,M]),v.useEffect(()=>{j?q("dashboard"):N==="dashboard"&&x(null)},[j,q,N,x]),v.useEffect(()=>{var fe;j||(fe=c.current)==null||fe.resize(0)},[j]);function U(fe){var ae,ee;fe?((ae=c.current)==null||ae.resize(40),y("dashboard",!0),x("dashboard"),q("dashboard")):(y("dashboard",!1),x(null),(ee=c.current)==null||ee.resize(0),q(null))}function V(fe="dashboard"){const ae={id:dt.v4(),title:fe==="document"?"New Document":"New Sheet",...fe==="document"?{kind:fe,document:p.createDefaultDocumentDefinition()}:{}};Y(ae),Z(ae.id)}function K(fe,ae){if(!H)return;P===fe?(W(),G(null),lt.success("Default sheet cleared")):(B(fe),G(fe),lt.success(`"${ae}" set as default sheet`))}function Q(fe){var ae;fe<1?(y("dashboard",!1),x(null),q(null),(ae=c.current)==null||ae.resize(0)):(j||y("dashboard",!0),q("dashboard"))}function se(){return(T==null?void 0:T.canvasTheme)==="muted"||!(T!=null&&T.canvasTheme)?"hsl(var(--semaphor-muted))":(T==null?void 0:T.canvasTheme)==="clear"?"":T==null?void 0:T.canvasTheme}const oe=(fe,ae)=>{fe.dataTransfer.setData("tabIndex",ae.toString())},me=fe=>{fe.preventDefault()},le=(fe,ae)=>{const ee=fe.dataTransfer.getData("tabIndex");if(ee===ae.toString())return;const J=Array.from(E||[]),[re]=J.splice(parseInt(ee),1);J.splice(ae,0,re),O(J)},ue=r===!0&&!i&&!j&&!k&&!D;function ne(){if(E&&E.length>1||R)return l.jsx("div",{className:"relative flex w-full items-stretch border-b border-border",children:l.jsxs("div",{className:"relative min-w-0 flex-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-4 bg-gradient-to-r from-background to-transparent"}),l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-4 bg-gradient-to-l from-background to-transparent"}),l.jsxs(p.TabsList,{role:"tab-list",className:"flex w-0 min-w-full items-stretch justify-start overflow-x-auto rounded-none bg-transparent p-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[E==null?void 0:E.map((fe,ae)=>{const ee=A===fe.id,J=P===fe.id;return l.jsxs(p.TabsTrigger,{draggable:!0,onDragStart:re=>oe(re,ae),onDragOver:me,onDrop:re=>le(re,ae),onClick:()=>Z(fe.id),className:p.cn("group relative inline-flex h-9 shrink-0 items-center gap-1.5 rounded-none bg-transparent px-3 py-0 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-transparent hover:text-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none","after:pointer-events-none after:absolute after:inset-x-2 after:-bottom-px after:h-0.5 after:bg-transparent data-[state=active]:after:bg-foreground"),value:fe.id,children:[fe.kind==="document"&&l.jsx(Qs,{className:"h-3 w-3 text-muted-foreground"}),l.jsx(Pj,{enabled:R&&ee,text:fe.title,onSave:re=>X(fe.id,re),children:fe.title},fe.id),l.jsx("span",{role:"button",tabIndex:0,"aria-label":J?"Clear default sheet":"Set as default sheet",title:J?"Clear default sheet":"Set as default sheet",onClick:re=>{re.stopPropagation(),K(fe.id,fe.title||"Sheet")},onKeyDown:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),re.stopPropagation(),K(fe.id,fe.title||"Sheet"))},className:p.cn("inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] transition-opacity hover:bg-muted focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",ee||J?"opacity-100":"opacity-0 group-hover:opacity-100"),children:l.jsx(FZ,{className:p.cn("h-3 w-3 transition-colors",J?"fill-current text-amber-500":"text-muted-foreground")})}),R&&ee&&E.length>1&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Delete sheet",className:"inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",onClick:re=>{re.stopPropagation(),f(!0)},onKeyDown:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),re.stopPropagation(),f(!0))},children:l.jsx(je.X,{className:"h-3 w-3"})})]},fe.id)}),R&&l.jsxs(Uo,{children:[l.jsx(Wo,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add sheet",className:"ml-1 inline-flex h-9 shrink-0 items-center gap-1 px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(Tr,{className:"h-3 w-3"}),"Sheet"]})}),l.jsxs(Do,{align:"start",className:"w-48",children:[l.jsxs(kn,{onSelect:()=>V("dashboard"),children:[l.jsx(em,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),l.jsxs(kn,{onSelect:()=>V("document"),children:[l.jsx(Qs,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})})}function de(){return l.jsx("div",{ref:u,style:{},className:"h-full min-h-0 grow",children:E==null?void 0:E.map(fe=>l.jsx(p.TabsContent,{style:{backgroundColor:se(),...I.dashboardCanvasStyle},className:p.cn("mt-0 h-full min-h-0",{}),value:fe.id,children:l.jsx(RK,{sheet:fe})},fe.id))})}function Ce(){return l.jsxs(p.Tabs,{"data-role":"dashboard-tabs-container",className:p.cn("relative flex h-full flex-col",T==null?void 0:T.dashboardTabsContainer),onValueChange:fe=>{Z(fe)},value:A||void 0,children:[ne(),L==="top"&&!$&&l.jsx(GP,{}),A&&!$&&l.jsx(o_t,{}),$?l.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:de()}):l.jsx(hl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:de()}),L==="bottom"&&!$&&l.jsx(GP,{}),l.jsx(T0t,{open:d,setOpen:f})]})}const ce=v.useCallback(fe=>{w("dashboard",fe)},[w]);return E?a&&A&&!$?l.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',A,'" was not found or is not a document sheet in the loaded dashboard.']}):a&&$&&F?l.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:l.jsx(RK,{sheet:F})}):l.jsxs(l.Fragment,{children:[l.jsx(qkt,{}),l.jsx(Gkt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(Zpe,{className:p.cn("flex-1 basis-0 overflow-y-auto transition-opacity",_&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(OF,{children:Ce()}),r===!0&&l.jsxs(l.Fragment,{children:[l.jsx(_0t,{open:j,onTabClick:U,withHandle:!0,disabled:!j}),l.jsx(OF,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:Q,defaultSize:j?40:0,ref:c,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Pkt,{open:j,setOpen:U,isFullscreen:_,onFullscreenChange:fe=>x(fe?"dashboard":null),fullscreenContainer:S})})})]})]}),l.jsx("div",{ref:ce,className:p.cn("absolute inset-0",!_&&"pointer-events-none")}),ue&&l.jsx("div",{className:p.cn("absolute z-50 transition-all duration-300 ease-in-out",b().horizontal,b().vertical),style:g(),children:l.jsx(p.Button,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{m.current||U(!0)},onMouseDown:h,onTouchStart:h,title:"Open Assistant (drag to move)",children:l.jsx(_ve,{className:"h-5 w-5"})})})]})]}):null}const axe=v.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:o,children:s,className:i,style:a,...c},u)=>{const d=v.useId(),f=v.useMemo(()=>s_t(d),[d]),{theme:h}=oO(),m=i_t(h),g=v.useMemo(()=>o??cf.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,o,n]),b=v.useMemo(()=>p.compileAppearance({spec:g,systemMode:m}),[g,m]),x=v.useMemo(()=>p.createAppearanceContextValue(f,b),[b,f]);return l.jsx(p.AppearanceContext.Provider,{value:x,children:l.jsx(Kb,{...c,ref:u,className:i,style:a,children:s})})});axe.displayName="AppearanceProvider";function s_t(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function i_t(e){const t=iN(e),[n,r]=v.useState(()=>a_t());return v.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const o=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!o)return;const s=()=>{r(o.matches?"dark":"light")};return s(),typeof o.addEventListener=="function"?(o.addEventListener("change",s),()=>o.removeEventListener("change",s)):((a=o.addListener)==null||a.call(o,s),()=>{var c;return(c=o.removeListener)==null?void 0:c.call(o,s)})},[t]),t==="system"?n:t}function a_t(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const lxe=v.createContext({openBrandStudioPreview:()=>{}}),l_t=lxe.Provider;function c_t(){return v.useContext(lxe)}function u_t({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const o=iN(t),[s,i]=v.useState(()=>d_t(n)||o),a=v.useCallback(u=>{const d=iN(u);f_t(n,d),i(d)},[n]),c=v.useMemo(()=>({theme:s,setTheme:a}),[s,a]);return l.jsx(sY.Provider,{...r,value:c,children:e})}function d_t(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=iN(t,"system");return n===t?n:null}catch{return null}}function f_t(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const h_t=v.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function U4({appearance:e,children:t}){var E,D;const{authToken:n,id:r,tokenProps:o}=It(),s=Pv(),i=(E=s.data)==null?void 0:E.organizationAppearance,a=(D=o.config)==null?void 0:D.appearance,[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,m]=v.useState(null),[g,b]=v.useState(null),[x,y]=v.useState(null),w=`${o.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,C=Un({queryKey:zX({resourceType:lo.DASHBOARD,apiServiceUrl:o.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>p.getRequest(`${o.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:R=>(R==null?void 0:R.organizationAppearance)??null,enabled:!s.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});v.useEffect(()=>{i!==void 0&&y({scopeKey:w,appearance:i})},[i,w]),v.useEffect(()=>{C.data!==void 0&&y({scopeKey:w,appearance:C.data})},[C.data,w]);const N=(x==null?void 0:x.scopeKey)===w?x.appearance:null,S=i!==void 0?i:C.data!==void 0?C.data:N,j=v.useMemo(()=>cf.resolveAppearance({organizationAppearance:S,tokenAppearance:a,reactAppearance:e}),[e,S,a]),_=v.useCallback(()=>{f(g??h??j),u(!0)},[g,h,j]),k=v.useCallback(()=>{u(!1)},[]);v.useEffect(()=>{f(null),m(null),b(null),u(!1)},[r]);const T=v.useMemo(()=>({openBrandStudioPreview:_}),[_]),I=g??h??e;return l.jsx(u_t,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(l_t,{value:T,children:l.jsx(axe,{organizationAppearance:S,tokenAppearance:a,reactAppearance:I,style:{height:"100%",width:"100%"},children:l.jsxs(p.TooltipProvider,{delayDuration:0,children:[t,c&&l.jsx("aside",{"aria-label":"Brand Studio","aria-modal":"false",role:"dialog",className:"fixed bottom-0 right-0 top-0 z-50 flex w-[min(520px,100vw)] flex-col border-l border-border bg-background text-foreground shadow-sm",children:l.jsx(v.Suspense,{fallback:l.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:l.jsx(h_t,{appearance:d,onDraftChange:b,onSave:R=>{m(R),b(R),f(R)},onCancel:k})})})]})})})})}function cxe({children:e,preferences:t}){const{currentUser:n}=ti(),r=v.useMemo(()=>{var o,s;return{preferences:t||{},isLocalDev:((o=t==null?void 0:t.uiMode)==null?void 0:o.developer)||!1,isConsoleMode:((s=t==null?void 0:t.uiMode)==null?void 0:s.console)||!1}},[t]);return l.jsx(OX.Provider,{value:r,children:l.jsx(HI,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function m_t(e=2e3,t=500){const n=Jye(),[r,o]=v.useState(!1),[s,i]=v.useState(!1),a=v.useRef(null);return v.useEffect(()=>{const c=setTimeout(()=>o(!0),e);return()=>clearTimeout(c)},[e]),v.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),s}function W4({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const o=m_t(e,t);return v.useEffect(()=>(o&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[o,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:o?"ready":""})}function uxe(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Si,{FallbackComponent:BI,children:l.jsx(uO,{dashboardProps:e,children:l.jsxs(JI,{children:[l.jsx(W4,{componentType:"dashboard",componentId:e.id}),l.jsx(U4,{appearance:e.appearance,children:l.jsx(cxe,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(JO,{...e,type:"dashboard",children:l.jsx(ixe,{})})})})})]})})})}function p_t(e=[]){const t=v.useRef(null),n=v.useRef(null),r=v.useRef(null),[o,s]=v.useState(),i=v.useCallback(()=>{var m,g,b;const a=((m=t.current)==null?void 0:m.clientWidth)??0,c=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);s(x=>x===h?x:h)},[]);return v.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:o,updateAvailableWidth:i}}function g_t({filter:e}){var g;const t=p.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=Lm(),r=mf((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),o=p.useDashboardStore(b=>b.filterValues),s=o==null?void 0:o.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=p.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:m}=p_t([t,s,r]);return v.useEffect(()=>{m()},[e.title,m]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(p.Label,{className:"my-1 block w-full text-sm",children:l.jsx(xi,{value:e.title||e.column,onSave:b=>c({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(A$,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(je.X,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function b_t(){const e=p.useDashboardStore(r=>r.dashboard.filters),t=p.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:p.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(g_t,{filter:r}),l.jsx(FI,{filter:r})]},r.id))}):null}function x_t(){var s;const e=p.useDashboardStore(i=>i.dashboard),t=p.useDashboardStore(i=>i.selectedSheetId),n=p.useDashboardStore(i=>i.isDashboardEditing),r=(s=e.sheets)==null?void 0:s.find(i=>i.id===t),o=p.isDocumentSheet(r);return l.jsx("div",{role:"dashboard-plus-main",className:"flex min-h-0 grow basis-0 overflow-hidden",children:l.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[n&&!o&&l.jsx(b_t,{}),l.jsx(ixe,{})]})})}const y_t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-BLNG_zHC.cjs"))),v_t=v.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-CR832BJc.cjs"))),w_t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BJ_Z9EaL.cjs")));function C_t({showControls:e=!1,showFooter:t=!0,...n}){const r=p.useDashboardStore(a=>a.isVisualEditing),o=p.useDashboardStore(a=>a.showDashboardJSON),{appearance:s,preferences:i}=n;return l.jsx(Si,{FallbackComponent:BI,children:l.jsx(uO,{dashboardProps:n,children:l.jsxs(JI,{children:[l.jsx(W4,{componentType:"surfboard",componentId:n.id}),l.jsxs(U4,{appearance:s,children:[l.jsx(RCe,{toastOptions:{classNames:{toast:"max-w-[calc(100vw-2rem)] overflow-x-hidden !items-start [--toast-close-button-end:0.5rem] [--toast-close-button-start:auto] [--toast-close-button-transform:translate(0,0)] sm:max-w-[44rem]",content:"min-w-0 flex-1",icon:"mt-0.5 shrink-0",title:"max-w-full break-words pr-8",description:"max-w-full break-words",closeButton:"!top-2 h-6 w-6 rounded-md border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"}}}),l.jsxs(cxe,{preferences:i,children:[o&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(w_t,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(y_t,{})}),l.jsx("div",{className:"flex grow overflow-hidden",children:l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(JO,{...n,type:"dashboard",children:[r&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(v_t,{})}),l.jsx(v.Activity,{mode:r?"hidden":"visible",children:l.jsx(x_t,{})})]})})})]})]})]})]})})})}const XF=[{value:"en-US",label:"English (United States)"},{value:"en-GB",label:"English (United Kingdom)"},{value:"de-DE",label:"German (Germany)"},{value:"fr-FR",label:"French (France)"},{value:"es-ES",label:"Spanish (Spain)"},{value:"it-IT",label:"Italian (Italy)"},{value:"nl-NL",label:"Dutch (Netherlands)"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"ja-JP",label:"Japanese (Japan)"},{value:"en-IN",label:"English (India)"},{value:"en-NZ",label:"English (New Zealand)"},{value:"mi-NZ",label:"Māori (New Zealand)"}],dxe=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","INR","BRL","KWD"]),S_t=Li.getSupportedCurrencyCodes(),N_t=S_t.filter(e=>!dxe.has(e)),fxe=[{value:"short",label:"Short"},{value:"medium",label:"Medium"},{value:"long",label:"Long"}],BG="2026-07-31",O2="2026-07-31T14:30:45";function QF(e){switch(e){case"viewer_user":return"user";case"viewer_tenant_user":return"tenant user";case"viewer_tenant":return"tenant";case"viewer_organization":return"organization";case"session_initial":return"embedded session";case"system_default":return"system";default:return"another preference level"}}function L2(e){var t;return((t=fxe.find(n=>n.value===e))==null?void 0:t.label)??e}function j_t(e){const t=XF.find(n=>n.value===e);return t?`${t.label} — ${t.value}`:e}function $2(e){return{short:e("short"),medium:e("medium"),long:e("long")}}function z2({id:e,label:t,value:n,inherited:r,inheritedSource:o,examples:s,disabled:i,onValueChange:a}){const c=n===void 0?`Inherited · ${L2(r)}`:L2(n);return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{htmlFor:e,className:"text-[11px] text-muted-foreground",children:t}),l.jsxs(p.Select,{value:n??"inherit",disabled:i,onValueChange:a,children:[l.jsx(p.SelectTrigger,{id:e,size:"xs",children:l.jsx(p.SelectValue,{children:c})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"inherit",className:"[&>span:last-child]:w-full",children:l.jsxs("span",{className:"flex w-full min-w-0 items-center justify-between gap-4",children:[l.jsxs("span",{children:["Inherited from ",QF(o)," ·"," ",L2(r)]}),l.jsx("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:s[r]})]})}),fxe.map(u=>l.jsx(p.SelectItem,{value:u.value,className:"[&>span:last-child]:w-full",children:l.jsxs("span",{className:"flex w-full min-w-0 items-center justify-between gap-4",children:[l.jsx("span",{children:u.label}),l.jsx("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:s[u.value]})]})},u.value))]})]})]})}function k_t({value:e,inherited:t,inheritedSources:n,onChange:r,disabled:o}){var j,_,k,T;const s=v.useId(),i=v.useId(),a=v.useId(),c=v.useId(),u=v.useId(),f=(e.locale===void 0?void 0:Li.canonicalizeSupportedLocale(e.locale))??t.locale,h=e.defaultCurrency??t.defaultCurrency,m={locale:f,dateStyle:e.dateStyle??t.dateStyle,dateTime:{dateStyle:((j=e.dateTime)==null?void 0:j.dateStyle)??t.dateTime.dateStyle,timeStyle:((_=e.dateTime)==null?void 0:_.timeStyle)??t.dateTime.timeStyle},defaultCurrency:h},g=new Intl.NumberFormat(f,{style:"currency",currency:h}).format(1e3),b=$t.resolveRawTemporalFormat({preferences:m,calendar:{tz:"UTC"}}),x=$t.formatRawTemporalValue({value:BG,metadata:{kind:"raw_temporal",valueKind:"date"},format:b}).text,y=$t.formatRawTemporalValue({value:O2,metadata:{kind:"raw_temporal",valueKind:"wall_datetime"},format:b}).text,w=$2(I=>$t.formatRawTemporalValue({value:BG,metadata:{kind:"raw_temporal",valueKind:"date"},format:$t.resolveRawTemporalFormat({preferences:{...m,dateStyle:I},calendar:{tz:"UTC"}})}).text),C=$2(I=>$t.formatRawTemporalValue({value:O2,metadata:{kind:"raw_temporal",valueKind:"wall_datetime"},format:$t.resolveRawTemporalFormat({preferences:{...m,dateTime:{...m.dateTime,dateStyle:I}},calendar:{tz:"UTC"}})}).text),N=$2(I=>$t.formatRawTemporalValue({value:O2,metadata:{kind:"raw_temporal",valueKind:"wall_datetime"},format:$t.resolveRawTemporalFormat({preferences:{...m,dateTime:{...m.dateTime,timeStyle:I}},calendar:{tz:"UTC"}})}).text),S=(I,E)=>{const D={...e.dateTime,[I]:E==="inherit"?void 0:E};r({...e,dateTime:D.dateStyle===void 0&&D.timeStyle===void 0?void 0:D})};return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{htmlFor:s,className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Locale"}),l.jsxs(p.Select,{value:e.locale??"inherit",disabled:o,onValueChange:I=>r({...e,locale:I==="inherit"?void 0:I}),children:[l.jsx(p.SelectTrigger,{id:s,size:"xs",children:l.jsx(p.SelectValue,{children:e.locale===void 0?`Inherited · ${t.locale}`:j_t(e.locale)})}),l.jsxs(p.SelectContent,{children:[l.jsxs(p.SelectItem,{value:"inherit",children:["Inherited from ",QF(n.locale)," ·"," ",t.locale]}),e.locale&&!XF.some(I=>I.value===e.locale)&&l.jsx(p.SelectItem,{value:e.locale,children:e.locale}),XF.map(I=>l.jsxs(p.SelectItem,{value:I.value,children:[I.label," — ",I.value]},I.value))]})]})]}),l.jsxs("fieldset",{className:"space-y-2",children:[l.jsx("legend",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Date values"}),l.jsx(z2,{id:a,label:"Format",value:e.dateStyle,inherited:t.dateStyle,inheritedSource:n.dateStyle,examples:w,disabled:o,onValueChange:I=>r({...e,dateStyle:I==="inherit"?void 0:I})})]}),l.jsxs("fieldset",{className:"space-y-2",children:[l.jsx("legend",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Date & time values"}),l.jsx(z2,{id:c,label:"Date",value:(k=e.dateTime)==null?void 0:k.dateStyle,inherited:t.dateTime.dateStyle,inheritedSource:n.dateTime.dateStyle,examples:C,disabled:o,onValueChange:I=>S("dateStyle",I)}),l.jsx(z2,{id:u,label:"Time",value:(T=e.dateTime)==null?void 0:T.timeStyle,inherited:t.dateTime.timeStyle,inheritedSource:n.dateTime.timeStyle,examples:N,disabled:o,onValueChange:I=>S("timeStyle",I)})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{htmlFor:i,className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default currency"}),l.jsxs(p.Select,{value:e.defaultCurrency??"inherit",disabled:o,onValueChange:I=>r({...e,defaultCurrency:I==="inherit"?void 0:I}),children:[l.jsx(p.SelectTrigger,{id:i,size:"xs",children:l.jsx(p.SelectValue,{children:e.defaultCurrency===void 0?`Inherited · ${t.defaultCurrency}`:e.defaultCurrency})}),l.jsxs(p.SelectContent,{children:[l.jsxs(p.SelectItem,{value:"inherit",children:["Inherited from ",QF(n.defaultCurrency)," ·"," ",t.defaultCurrency]}),[...dxe].map(I=>l.jsx(p.SelectItem,{value:I,children:I},I)),N_t.map(I=>l.jsx(p.SelectItem,{value:I,children:I},I))]})]})]}),l.jsxs("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2",children:[l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Preview"}),l.jsxs("dl",{className:"mt-1.5 space-y-1 text-[12px]",children:[l.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Date"}),l.jsx("dd",{className:"text-right font-medium text-foreground",children:x})]}),l.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Date & time"}),l.jsx("dd",{className:"text-right font-medium text-foreground",children:y})]}),l.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Currency"}),l.jsx("dd",{className:"text-right font-medium text-foreground",children:g})]})]})]}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Currency values are not converted. Date examples use a fixed reference value and the Gregorian calendar."})]})}const JF=new Set;function hxe(e){return JF.add(e),()=>{JF.delete(e)}}function K4(){JF.forEach(e=>{e()})}var __t=Object.defineProperty,I_t=(e,t,n)=>t in e?__t(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,l1=(e,t,n)=>I_t(e,typeof t!="symbol"?t+"":t,n);const T_t={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},E_t={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}},D_t={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function M_t(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function mxe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const R_t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const o=mxe(t);if(typeof n<"u"&&o in n.container)return n.container[o]})();return typeof r=="function"?r.bind(n):void 0}},A_t={stringify:e=>`${e}`,parse:e=>parseFloat(e)},P_t={stringify:e=>e,parse:e=>e},B2={string:P_t,number:A_t,boolean:T_t,function:E_t,method:R_t,json:D_t},Zx=Symbol.for("r2wc.render"),c1=Symbol.for("r2wc.connected"),qf=Symbol.for("r2wc.context"),Ii=Symbol.for("r2wc.props");function F_t(e,t,n){var r,o,s;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const g=M_t(m);d[m]=g,f[g]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),l1(this,s,!0),l1(this,o),l1(this,r,{}),l1(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ii].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=c[g],w=y?B2[y]:null;if(y==="method"){const C=mxe(b);Object.defineProperty(this[Ii].container,C,{enumerable:!0,configurable:!0,get(){return this[Ii][C]},set(N){this[Ii][C]=N,this[Zx]()}}),this[Ii][g]=w.parse(x,b,this)}w!=null&&w.parse&&x&&(this[Ii][g]=w.parse(x,b,this))}for(const g of a)this[Ii][g]=b=>{const x=g.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:b,...u[g]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[c1]=!0,this[Zx]()}disconnectedCallback(){this[c1]=!1,this[qf]&&n.unmount(this[qf]),delete this[qf]}attributeChangedCallback(g,b,x){const y=f[g],w=c[y],C=w?B2[w]:null;y in c&&C!=null&&C.parse&&x&&(this[Ii][y]=C.parse(x,g,this),this[Zx]())}[(s=c1,o=qf,r=Ii,Zx)](){this[c1]&&(this[qf]?n.update(this[qf],this[Ii]):this[qf]=n.mount(this.container,e,this[Ii]))}}for(const m of i){const g=d[m],b=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Ii][m]},set(x){this[Ii][m]=x;const y=b?B2[b]:null;if(y!=null&&y.stringify){const w=y.stringify(x,g,this);this.getAttribute(g)!==w&&this.setAttribute(g,w)}else this[Zx]()}})}return h}function O_t(e,t,n){const r=zxe.createRoot(e),o=v.createElement(t,n);return r.render(o),{root:r,ReactComponent:t}}function L_t({root:e,ReactComponent:t},n){const r=v.createElement(t,n);e.render(r)}function $_t({root:e}){e.unmount()}function z_t(e,t={}){return F_t(e,t,{mount:O_t,update:L_t,unmount:$_t})}const B_t={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",interactionExecutionSnapshot:"json",presentationExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},V_t=z_t(uxe,{props:B_t}),H_t=v.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(a4,{context:t})," "]})});var pxe="Toggle",gxe=te.forwardRef((e,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:o,...s}=e,[i,a]=p.useControllableState({prop:n,onChange:o,defaultProp:r??!1,caller:pxe});return l.jsx(p.Primitive.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...s,ref:t,onClick:p.composeEventHandlers(e.onClick,()=>{e.disabled||a(!i)})})});gxe.displayName=pxe;var bxe=gxe;const q_t=p.cva("inline-flex items-center justify-center rounded-control text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),xxe=te.forwardRef(({className:e,variant:t,size:n,...r},o)=>l.jsx(bxe,{ref:o,className:p.cn(q_t({variant:t,size:n,className:e})),...r}));xxe.displayName=bxe.displayName;function G4(){var c,u;const e=p.useEditorStore(d=>d.card),t=p.useEditorStore(d=>d.frame),n=v.useMemo(()=>it.findCustomVisualConfigCard(t,e),[t,e]),{manifest:r}=Nf(((c=n==null?void 0:n.customCardPreferences)==null?void 0:c.url)||""),o=v.useMemo(()=>{var d;return(d=r==null?void 0:r.visuals)==null?void 0:d.find(f=>{var h;return f.name===((h=n==null?void 0:n.customCardPreferences)==null?void 0:h.componentName)})},[r,(u=n==null?void 0:n.customCardPreferences)==null?void 0:u.componentName]),s=it.resolveMultiInputType(n,o),i=v.useMemo(()=>it.getCustomVisualInputCards({frame:t,configCard:n,isMultiInputVisual:s==="multiple"}),[t,n,s]),a=v.useMemo(()=>{const d=i.findIndex(f=>(f==null?void 0:f.id)===e.id);return d<0?-1:it.getSlotIndexForCard(e,d)},[i,e]);return v.useMemo(()=>!n||s!=="multiple"||a<0?e.type:it.getEffectiveCardTypeForSlot(e,a,o==null?void 0:o.slots)??e.type,[n,s,a,e,o==null?void 0:o.slots])}function yxe({storeValue:e,defaultValue:t="",onStoreUpdate:n,delay:r=300}){const[o,s]=v.useState(e??t),i=v.useRef(null),a=v.useRef(o),c=v.useRef(e),u=v.useRef(!1),d=v.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null),u.current&&a.current!==(c.current??t)&&(n(a.current),c.current=a.current)},[t,n]);v.useEffect(()=>{if(e!==c.current){i.current&&(clearTimeout(i.current),i.current=null);const h=e??t;s(h),a.current=h,c.current=e,u.current=!1}},[e,t]),v.useEffect(()=>{if(u.current)return i.current=setTimeout(()=>{d()},r),()=>{i.current&&(clearTimeout(i.current),i.current=null)}},[r,d,o]),v.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const f=v.useCallback(h=>{const m=h??t;u.current=!0,a.current=m,s(m)},[t]);return{value:o,onChange:f,flush:d}}const U_t=300;function W_t({onExpand:e},t){const n=p.useEditorStore(C=>C.card.sql),r=p.useEditorStore(C=>C.sqlGen),o=p.useEditorStore(C=>C.card),s=G4(),{setCardSql:i,setSqlGen:a,setRunSql:c}=p.useEditorActions(),u=v.useMemo(()=>s!==o.type?{...o,type:s}:o,[o,s]),{queryKey:d}=pb(u),f=Wr(),h=v.useRef(d);h.current=d;const m=v.useRef(r);m.current=r;const g=v.useCallback(C=>{i(C)},[i]),{value:b,onChange:x,flush:y}=yxe({storeValue:n,defaultValue:"",onStoreUpdate:g,delay:U_t});v.useEffect(()=>hxe(y),[y]);function w(C){x(C),p.isObjectEmpty(m.current)||a({})}return l.jsxs("div",{className:"relative h-full w-full",children:[l.jsx(p.CodeEditor,{ref:t,value:b??"",onValueChange:w,language:"sql-jinja",embedded:!0,hideLineNumbers:!0,wrapLines:!0,placeholder:"Write your SQL here",onKeyDown:C=>{C.key==="Enter"&&C.shiftKey&&(C.preventDefault(),K4(),setTimeout(()=>{f.removeQueries({queryKey:h.current,exact:!0}),c(!0)},0))}}),e?l.jsx(p.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-2.5 top-2 z-20 h-7 w-7 bg-background/80 p-0 text-muted-foreground backdrop-blur-sm transition-colors hover:bg-accent hover:text-foreground focus-visible:text-foreground",onClick:e,"aria-label":"Expand SQL editor",title:"Expand SQL editor",children:l.jsx(Ft.Maximize2,{className:"h-3.5 w-3.5",strokeWidth:1.75})}):null]})}const K_t=v.forwardRef(W_t),G_t=300;function Y_t(e,t){const n=p.useEditorStore(g=>g.card.python),r=p.useEditorStore(g=>g.card),o=G4(),{setCardPython:s,setRunSql:i}=p.useEditorActions(),a=v.useMemo(()=>o!==r.type?{...r,type:o}:r,[r,o]),{queryKey:c}=pb(a),u=Wr(),d=v.useRef(c);d.current=c;const{value:f,onChange:h,flush:m}=yxe({storeValue:n,defaultValue:it.PYTHON_DEFAULT_CODE,onStoreUpdate:s,delay:G_t});return v.useEffect(()=>hxe(m),[m]),l.jsx(p.CodeEditor,{ref:t,value:f??"",onValueChange:h,language:"python",embedded:!0,hideLineNumbers:!0,wrapLines:!0,className:"[&_.code-editor-pre]:!pt-2 [&_.code-editor-textarea]:!pt-2",onKeyDown:g=>{g.key==="Enter"&&g.shiftKey&&(g.preventDefault(),K4(),setTimeout(()=>{u.removeQueries({queryKey:d.current,exact:!0}),i(!0)},0))}})}const Z_t=v.forwardRef(Y_t),vxe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),X_t=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),Q_t=Array.from(vxe).join(", "),J_t=3,eIt="Self-heal",tIt=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function nIt({card:e}){var W,P,G,Z,X;const t=fl(),[n,r]=v.useState({}),{authToken:o}=It(),s=p.getTokenParams(o==null?void 0:o.accessToken),{compiledAppearance:i}=p.useAppearance(),a=v.useMemo(()=>Aw(i),[i]),c=p.useEditorStore(Y=>Y.frame),u=p.useEditorStore(Y=>Y.inlineFilterValuesMap[e.id]),d=p.useEditorStore(Y=>Y.actions.setCardInlineFilterValue),f=p.useEditorStore(Y=>Y.actions.removeCardInlineFilterValue),h=e,{getCard:m,manifest:g}=Nf(((W=h.customCardPreferences)==null?void 0:W.url)||""),b=(P=g==null?void 0:g.visuals)==null?void 0:P.find(Y=>{var O;return Y.name===((O=h.customCardPreferences)==null?void 0:O.componentName)}),x=it.resolveMultiInputType(h,b)??"single",y=v.useMemo(()=>it.getCustomVisualInputCards({frame:c,configCard:h,isMultiInputVisual:x==="multiple"}),[c,h,x]),w=v.useMemo(()=>{const Y=y.findIndex(O=>(O==null?void 0:O.id)===e.id);return Y<0?-1:it.getSlotIndexForCard(e,Y)},[y,e]),C=v.useMemo(()=>x!=="multiple"||w<0?e.type:it.getEffectiveCardTypeForSlot(e,w,b==null?void 0:b.slots)??e.type,[x,w,e,b==null?void 0:b.slots]),N=v.useMemo(()=>x==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:C!==e.type?{...e,type:C}:e,[e,C,x]),{data:S,effectiveCardConfig:j}=pb(N),_=p.useInteractionStore(Y=>Y.interactionStates),k=p.useDashboardStore(Y=>{var O;return(O=Y.dashboard)==null?void 0:O.id}),T=p.useDashboardStore(Y=>Y.dashboard.filters),I=p.useDashboardStore(Y=>Y.filterValues),E=p.useDashboardStore(Y=>Y.selectedSheetId),D=v.useMemo(()=>F$({card:e,sheetId:E||"",inlineFilterValues:u,setInlineFilterValue:Y=>d(e.id,Y),removeInlineFilterValue:Y=>f(e.id,Y)}),[e,E,u,d,f]),{cardFilters:R,cardFilterValues:A}=v.useMemo(()=>Qv({card:e,interactionStates:_,currentDashboardId:k,filters:T,filterValues:I,selectedSheetId:E}),[e,_,k,T,I,E]),F=v.useCallback((Y,O)=>{const q=it.normalizeMultiInputPayload(O);r(U=>({...U,[Y]:q}))},[]),z=(G=h.customCardPreferences)==null?void 0:G.componentName,L=z?m(z):null,$=Rj((Z=h.customCardPreferences)==null?void 0:Z.settings,h),H=v.useMemo(()=>it.buildSlotOrderedCards(y),[y]),M=v.useMemo(()=>H.map((Y,O)=>it.getEffectiveCardTypeForSlot(Y,O,b==null?void 0:b.slots)),[H,b==null?void 0:b.slots]),B=v.useMemo(()=>$$(x==="multiple"?L$({slotOrderedCards:H,multiInputData:n,valueFormatPreferences:t}):[{card:e,cardConfig:j,columns:S==null?void 0:S.columns,columnKeyMap:S==null?void 0:S.columnKeyMap,valueFormatPreferences:t}]),[e,S==null?void 0:S.columnKeyMap,S==null?void 0:S.columns,j,n,H,x,t]);return z?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(v.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[L&&x==="single"&&l.jsx(L,{editing:!0,params:s,theme:a,settings:$,cardMetadata:oue({card:e,dataMetadata:S==null?void 0:S.metadata}),onDataChange:F,data:(S==null?void 0:S.records)||[],columns:(S==null?void 0:S.columns)||[],formatTemporalBucketValue:B,filters:R,filterValues:[...A||[],...u||[]],inlineFilters:D}),L&&x==="multiple"&&l.jsxs(l.Fragment,{children:[y.map((Y,O)=>{if(!Y)return null;const q=it.getSlotIndexForCard(Y,O),U=it.getEffectiveCardTypeForSlot(Y,q,b==null?void 0:b.slots);return l.jsx(a$,{onDataChange:F,card:Y,effectiveCardType:U},`${Y.id}-${q}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(L,{editing:!0,onDataChange:F,...O$({configCard:h,slotOrderedCards:H,slotTypes:M,multiInputData:n,params:s,theme:a,chartSettings:$,filters:R,filterValues:[...A||[],...u||[]],inlineFilters:D,formatTemporalBucketValue:B})})})]})]},(X=h.customCardPreferences)==null?void 0:X.componentName)}):null}const rIt=v.memo(nIt),oIt=p.create()(p.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(o=>o.type===n&&o.id===r),toggleStar:n=>{e(r=>{const o=r.starredCharts.findIndex(s=>s.type===n.type&&s.id===n.id);return o>=0?{starredCharts:r.starredCharts.filter((s,i)=>i!==o)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(o=>o.type===n&&o.id===r)}),{name:"semaphor-starred-charts"}));var wxe=["PageUp","PageDown"],Cxe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Sxe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},ax="Slider",[eO,sIt,iIt]=p.createCollection(ax),[Nxe]=p.createContextScope(ax,[iIt]),[aIt,LT]=Nxe(ax),jxe=te.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:s=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:m=!1,form:g,...b}=e,x=te.useRef(new Set),y=te.useRef(0),C=i==="horizontal"?lIt:cIt,[N=[],S]=p.useControllableState({prop:d,defaultProp:u,onChange:E=>{var R;(R=[...x.current][y.current])==null||R.focus(),f(E)}}),j=te.useRef(N);function _(E){const D=mIt(N,E);I(E,D)}function k(E){I(E,y.current)}function T(){const E=j.current[y.current];N[y.current]!==E&&h(N)}function I(E,D,{commit:R}={commit:!1}){const A=xIt(s),F=yIt(Math.round((E-r)/s)*s+r,A),z=p.clamp(F,[r,o]);S((L=[])=>{const $=fIt(L,z,D);if(bIt($,c*s)){y.current=$.indexOf(z);const H=String($)!==String(L);return H&&R&&h($),H?$:L}else return L})}return l.jsx(aIt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:y,thumbs:x.current,values:N,orientation:i,form:g,children:l.jsx(eO.Provider,{scope:e.__scopeSlider,children:l.jsx(eO.Slot,{scope:e.__scopeSlider,children:l.jsx(C,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:p.composeEventHandlers(b.onPointerDown,()=>{a||(j.current=N)}),min:r,max:o,inverted:m,onSlideStart:a?void 0:_,onSlideMove:a?void 0:k,onSlideEnd:a?void 0:T,onHomeKeyDown:()=>!a&&I(r,0,{commit:!0}),onEndKeyDown:()=>!a&&I(o,N.length-1,{commit:!0}),onStepKeyDown:({event:E,direction:D})=>{if(!a){const F=wxe.includes(E.key)||E.shiftKey&&Cxe.includes(E.key)?10:1,z=y.current,L=N[z],$=s*F*D;I(L+$,z,{commit:!0})}}})})})})});jxe.displayName=ax;var[kxe,_xe]=Nxe(ax,{startEdge:"left",endEdge:"right",size:"width",direction:1}),lIt=te.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=te.useState(null),m=p.useComposedRefs(t,C=>h(C)),g=te.useRef(void 0),b=p.useDirection(o),x=b==="ltr",y=x&&!s||!x&&s;function w(C){const N=g.current||f.getBoundingClientRect(),S=[0,N.width],_=Y4(S,y?[n,r]:[r,n]);return g.current=N,_(C-N.left)}return l.jsx(kxe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:l.jsx(Ixe,{dir:b,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const N=w(C.clientX);i==null||i(N)},onSlideMove:C=>{const N=w(C.clientX);a==null||a(N)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:C=>{const S=Sxe[y?"from-left":"from-right"].includes(C.key);u==null||u({event:C,direction:S?-1:1})}})})}),cIt=te.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=te.useRef(null),f=p.useComposedRefs(t,d),h=te.useRef(void 0),m=!o;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],C=Y4(y,m?[r,n]:[n,r]);return h.current=x,C(b-x.top)}return l.jsx(kxe,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:l.jsx(Ixe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);s==null||s(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Sxe[m?"from-bottom":"from-top"].includes(b.key);c==null||c({event:b,direction:y?-1:1})}})})}),Ixe=te.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=LT(ax,n);return l.jsx(p.Primitive.span,{...u,ref:t,onKeyDown:p.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):wxe.concat(Cxe).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:p.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:p.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&o(f)}),onPointerUp:p.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),s(f))})})}),Txe="SliderTrack",Exe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=LT(Txe,n);return l.jsx(p.Primitive.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:t})});Exe.displayName=Txe;var tO="SliderRange",Dxe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=LT(tO,n),s=_xe(tO,n),i=te.useRef(null),a=p.useComposedRefs(t,i),c=o.values.length,u=o.values.map(h=>Axe(h,o.min,o.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(p.Primitive.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...e.style,[s.startEdge]:d+"%",[s.endEdge]:f+"%"}})});Dxe.displayName=tO;var nO="SliderThumb",Mxe=te.forwardRef((e,t)=>{const n=sIt(e.__scopeSlider),[r,o]=te.useState(null),s=p.useComposedRefs(t,a=>o(a)),i=te.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return l.jsx(uIt,{...e,ref:s,index:i})}),uIt=te.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:o,...s}=e,i=LT(nO,n),a=_xe(nO,n),[c,u]=te.useState(null),d=p.useComposedRefs(t,w=>u(w)),f=c?i.form||!!c.closest("form"):!0,h=p.useSize(c),m=i.values[r],g=m===void 0?0:Axe(m,i.min,i.max),b=hIt(r,i.values.length),x=h==null?void 0:h[a.size],y=x?pIt(x,g,a.direction):0;return te.useEffect(()=>{if(c)return i.thumbs.add(c),()=>{i.thumbs.delete(c)}},[c,i.thumbs]),l.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[l.jsx(eO.ItemSlot,{scope:e.__scopeSlider,children:l.jsx(p.Primitive.span,{role:"slider","aria-label":e["aria-label"]||b,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:p.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&l.jsx(Rxe,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});Mxe.displayName=nO;var dIt="RadioBubbleInput",Rxe=te.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const o=te.useRef(null),s=p.useComposedRefs(o,r),i=p.usePrevious(t);return te.useEffect(()=>{const a=o.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),l.jsx(p.Primitive.input,{style:{display:"none"},...n,ref:s,defaultValue:t})});Rxe.displayName=dIt;function fIt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,s)=>o-s)}function Axe(e,t,n){const s=100/(n-t)*(e-t);return p.clamp(s,[0,100])}function hIt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function mIt(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function pIt(e,t,n){const r=e/2,s=Y4([0,50],[0,r]);return(r-s(t)*n)*n}function gIt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function bIt(e,t){if(t>0){const n=gIt(e);return Math.min(...n)>=t}return!0}function Y4(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function xIt(e){return(String(e).split(".")[1]||"").length}function yIt(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var Pxe=jxe,vIt=Exe,wIt=Dxe,CIt=Mxe;const Fxe=te.forwardRef(({className:e,...t},n)=>l.jsxs(Pxe,{ref:n,className:p.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx(vIt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(wIt,{className:"absolute h-full bg-primary"})}),l.jsx(CIt,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Fxe.displayName=Pxe.displayName;exports.Accordion=Jz;exports.AccordionContent=mv;exports.AccordionItem=fv;exports.AccordionTrigger=hv;exports.AddDataPicker=B4;exports.AggregateTable=hI;exports.Alert=rL;exports.AlertDescription=oL;exports.AlertDialog=ff;exports.AlertDialogAction=Du;exports.AlertDialogCancel=Mu;exports.AlertDialogContent=ku;exports.AlertDialogDescription=Eu;exports.AlertDialogFooter=Iu;exports.AlertDialogHeader=_u;exports.AlertDialogTitle=Tu;exports.AlertDialogTrigger=JSe;exports.AlertTitle=mte;exports.ArrowDown=es;exports.ArrowDownIcon=dQe;exports.ArrowLeft=zv;exports.ArrowRight=Bv;exports.ArrowUp=bs;exports.ArrowUpIcon=hQe;exports.AssistantContextEntityControls=YF;exports.AssistantVirtualizedMessages=nxe;exports.AxisConfigurator=Wm;exports.BackgroundRunPill=kct;exports.Badge=mi;exports.Bell=h1;exports.BookType=oZ;exports.BriefingAuthor=Pfe;exports.BriefingAuthorDialog=Ffe;exports.BriefingUiCapabilitiesBoundary=Gct;exports.BriefingUiCapabilitiesProvider=JI;exports.BriefingsApiError=Uw;exports.BulletChartIcon=Gbe;exports.CSS=Ki;exports.CalculatedFieldEditor=fme;exports.Calculator=iZ;exports.Calendar=za;exports.CalendarClock=SO;exports.Card=hN;exports.CardContent=CO;exports.CardHeader=wO;exports.CardSummary=tF;exports.CardTitle=cb;exports.ChartArea=fR;exports.ChartColumnIncreasing=lZ;exports.ChartColumnStacked=cZ;exports.ChartJsVisual=Tw;exports.ChartLine=uZ;exports.ChartNoAxesGantt=fZ;exports.ChartPie=hZ;exports.ChartScatter=mZ;exports.ChatInputWithContext=V4;exports.Checkbox=Tn;exports.ChevronLeft=Mm;exports.ChevronsUpDown=bZ;exports.Circle=NO;exports.CircleAlert=Ca;exports.CircleCheck=xZ;exports.CircleHelp=yZ;exports.Clock=vZ;exports.CodeHighlighter=Fd;exports.CodeXml=m1;exports.Collapsible=vu;exports.CollapsibleContent=Cu;exports.CollapsibleTrigger=wu;exports.ColorField=da;exports.Command=cT;exports.CommandEmpty=dT;exports.CommandGroup=fT;exports.CommandInput=Bz;exports.CommandItem=hT;exports.CommandList=uT;exports.CommandSeparator=Dhe;exports.ComparisonMetadataBadge=Foe;exports.Container=JO;exports.ControlDefaultValueEditor=Pme;exports.ControlDefinitionOptionsEditor=Ame;exports.ControlIdInput=Eme;exports.ControlVisibilitySettings=fgt;exports.Copy=Jh;exports.CopyButton=Pd;exports.CopyPlus=mR;exports.Cross2Icon=bQe;exports.CustomFilterPopover=A$;exports.CustomScrollArea=hl;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=Are;exports.Dashboard=uxe;exports.DashboardCard=zfe;exports.DashboardCreateDialogBase=hQ;exports.DashboardExportDialog=rxe;exports.DashboardPlus=C_t;exports.DashboardWC=V_t;exports.DataTableConditionalFormattingSettings=Npe;exports.DataTablePagination=rI;exports.Database=ss;exports.DateRangePicker=E$;exports.DefaultChatTransport=M4;exports.Dialog=Mo;exports.DialogContent=go;exports.DialogDescription=Ro;exports.DialogFooter=tl;exports.DialogHeader=Is;exports.DialogTitle=bo;exports.DialogTrigger=uQ;exports.DisplayFormatPreferencesFields=k_t;exports.DisplayPreferencesProvider=HI;exports.DndContext=nC;exports.Donut=wZ;exports.Download=Su;exports.DownloadPdf=oxe;exports.DragOverlay=bhe;exports.DropdownMenu=Uo;exports.DropdownMenuCheckboxItem=nd;exports.DropdownMenuContent=Do;exports.DropdownMenuItem=kn;exports.DropdownMenuLabel=qa;exports.DropdownMenuRadioGroup=iCe;exports.DropdownMenuRadioItem=FX;exports.DropdownMenuSeparator=Sa;exports.DropdownMenuSub=qO;exports.DropdownMenuSubContent=$k;exports.DropdownMenuSubTrigger=Lk;exports.DropdownMenuTrigger=Wo;exports.EMPTY_DATA_SOURCE=sb;exports.Editable=Pj;exports.EditableText=xi;exports.EditorCustomVisual=rIt;exports.Ellipsis=Ci;exports.EllipsisVertical=Rm;exports.ErrorBoundary=Si;exports.ExportError=kb;exports.ExternalLink=Ld;exports.EyeOff=Ak;exports.Fallback=BI;exports.FallbackVisual=Vw;exports.FeedbackCategory=lf;exports.FeedbackDialog=jv;exports.FieldsList=a4;exports.FieldsSection=H_t;exports.FileCode=CZ;exports.FileText=Qs;exports.Filter=$d;exports.FilterComponent=FI;exports.FilterInfo=XP;exports.FilterableFieldsPanel=mme;exports.Grid3x3=pR;exports.GripVertical=Nu;exports.HEATMAP_PRESET_PALETTES=_A;exports.Hash=ub;exports.House=SZ;exports.HoverCard=Xm;exports.HoverCardContent=bu;exports.HoverCardTrigger=Yd;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=vxe;exports.INLINE_ALLOWED_TOOL_LIST=Q_t;exports.INLINE_BLOCKED_MUTATING_TOOLS=X_t;exports.IconButton=nu;exports.IconForFieldType=Q1;exports.Inbox=kO;exports.InfoHover=J$;exports.InlineFilterBar=Rue;exports.KPICard=tf;exports.KeyboardSensor=eC;exports.Layers=Pm;exports.Link=_O;exports.LoadingDots=xu;exports.MAX_SELF_HEAL_ATTEMPTS=J_t;exports.Map=_Z;exports.Markdown=Sz;exports.MatrixTableVisual=fI;exports.MdStackedLineChart=Wbe;exports.MultiInputEmptyRenderer=a$;exports.PanelResizeHandle=ET;exports.Pause=IZ;exports.PenLine=xR;exports.Pencil=yR;exports.PendingMessagesDisplay=Fbe;exports.PersistedDynamicVisual=VI;exports.PiChartPolar=Vbe;exports.Pin=EZ;exports.PinOff=TZ;exports.PivotTableTanstack=Wb;exports.Placeholders=Xpe;exports.Play=DZ;exports.Plus=Tr;exports.PointerSensor=Jb;exports.Progress=L4;exports.PythonEditor=Z_t;exports.RECOVERABLE_SQL_ERROR_CODES=tIt;exports.Radar=MZ;exports.RadioGroup=rl;exports.RadioGroupItem=vs;exports.RefreshCw=tc;exports.ResizableHandle=k0t;exports.ResizablePanel=OF;exports.ResizablePanelGroup=Zpe;exports.ResourceEditDialog=HQ;exports.ResourceType=lo;exports.Rows3=RZ;exports.RunCompletionBanner=_ct;exports.SELF_HEAL_TIMELINE_STEP=eIt;exports.SeedQuestions=wbe;exports.SemaphorContext=Av;exports.SemaphorContextProvider=uO;exports.SemaphorQueryClient=kY;exports.SemaphorReadyIndicator=W4;exports.SemaphorStyleWrapper=Kb;exports.Send=TO;exports.SendHorizontal=AZ;exports.Settings=EO;exports.Settings2=Fm;exports.Share2=PZ;exports.ShareDialog=VQ;exports.Sheet=a3;exports.SheetContent=oI;exports.SheetDescription=iI;exports.SheetHeader=koe;exports.SheetTitle=sI;exports.SheetTrigger=Wze;exports.Slider=Fxe;exports.SortableContext=rC;exports.Sparkles=p0;exports.SqlEditor=K_t;exports.Square=MO;exports.SquarePen=DO;exports.Star=FZ;exports.StructuralParticipantSelector=Dme;exports.SummaryCard=GP;exports.TABLE_PRESENTATION_DEFAULT_STYLE=Rd;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=ha;exports.TableBody=Gd;exports.TableCell=qn;exports.TableColumnVisibilitySettings=fpe;exports.TableHead=mo;exports.TableHeader=Zm;exports.TablePresentationSettings=mpe;exports.TableRow=Ar;exports.TableSkeleton=tz;exports.TableVisual=Zd;exports.Tag=OZ;exports.TbChartBubble=Hbe;exports.TbChartFunnel=qbe;exports.TbChartTreemap=Ube;exports.TextCard=Xg;exports.Textarea=zm;exports.TiSortNumerically=Kbe;exports.Toggle=xxe;exports.Tornado=LZ;exports.Trash2=el;exports.TriangleAlert=Zs;exports.TypeGlyph=Yw;exports.UXProvider=U4;exports.Undo2=$Z;exports.User=AO;exports.Users=Pk;exports.UsersRound=PO;exports.VisualErrorState=yue;exports.Zap=vR;exports.applyBriefingFormPatch=rv;exports.areContextEntitiesEqual=ar;exports.areEntitiesJoined=Lre;exports.arrayMove=ex;exports.briefingFormDraftToCreateRequest=rF;exports.briefingFormDraftToUpdateRequest=pde;exports.briefingToFormDraft=Qp;exports.briefingTone=_r;exports.buildCardControlUsageById=mgt;exports.buildCustomCardTheme=Aw;exports.buildDashboardControlUsageById=hgt;exports.buildDashboardSheetsInputExecutionSnapshot=vO;exports.buildDashboardStructuralParticipantIdsByControlId=Lme;exports.buildFilterFieldMeta=Kz;exports.buildFilterSemanticContext=Gz;exports.buildInlineFilterNodes=F$;exports.buildMultiInputCustomVisualProps=O$;exports.buildMultiInputTemporalPresentationInputs=L$;exports.calculateCardFilterValues=S5;exports.calculateContextAwareFilters=Qv;exports.calculateFieldState=GL;exports.canUserAccessVisuals=sNe;exports.canUserCreateDashboards=WQ;exports.canUserEdit=nNe;exports.canUserManageDashboards=oNe;exports.canUserManageGroups=iNe;exports.canUserUseFilters=rNe;exports.cancelBriefingPreviewRun=rde;exports.cancelBriefingRun=sde;exports.cancelExport=r$e;exports.chartSupportsDataLabels=Dne;exports.chartSupportsLegend=Tne;exports.chartTypes=OT;exports.cleanupKpiMetricComparisonMode=zhe;exports.cloneDeep=Ks;exports.cloneLinkedFrameWithSourceMapping=Iet;exports.closestCenter=Jw;exports.commitSharedCalculatedFields=Jf;exports.createAssistantConversationId=Hp;exports.createAssistantRequestId=ybe;exports.createBriefing=Yue;exports.createBriefingFormDraft=nF;exports.createChartConfig=Nb;exports.createCustomVisualTemporalBucketFormatter=$$;exports.createDashboardControlInputFromControl=hyt;exports.createExport=toe;exports.createUniqueDashboardInputVariableNameFromName=Od;exports.currencyPresentationTargetKey=ba;exports.dedup=wNt;exports.dedupeContextEntities=Dz;exports.deleteBriefing=Que;exports.deleteBriefingRun=ide;exports.diagnoseCurrencyPresentationBindings=y0e;exports.doesStoredFilterMatchField=rb;exports.downloadDocumentPdf=Q5;exports.downloadPdf=Uee;exports.extractSqlParamReferences=IY;exports.extractTableMetadata=Wz;exports.fieldAlreadyExists=zre;exports.flexRender=gi;exports.flushPendingEditorDrafts=K4;exports.formatDisplayFormula=cmt;exports.formatFileSize=i$e;exports.getAutoDetectedChartIcon=Xjt;exports.getBriefing=Gue;exports.getBriefingArtifact=Ttt;exports.getBriefingEvidence=Ett;exports.getBriefingPreviewRun=nde;exports.getBriefingRun=ode;exports.getCardCurrencyPresentationFields=pO;exports.getCardCurrencyPresentationTargets=gO;exports.getChartGridStyle=eDe;exports.getChartIconByType=Qjt;exports.getColorForValue=BR;exports.getCoreRowModel=eI;exports.getDefaultAxisConfig=WR;exports.getDefaultChartColors=Um;exports.getDefaultDataLabelsConfig=dw;exports.getDefaultLegendConfig=EL;exports.getDefaultRunningTotalPartitionByFieldIds=l0;exports.getDisplayedKpiResultColumnKeys=mw;exports.getDocumentSectionEditorCard=Wpt;exports.getDocumentSheetDashboardInputs=rx;exports.getDownloadUrl=n$e;exports.getEntityIcon=Nk;exports.getErrorMessage=sbe;exports.getExportStatus=t$e;exports.getExports=e$e;exports.getExpressionFieldKind=rf;exports.getFieldExpressionAnnotation=Yz;exports.getFilterCount=zj;exports.getGranularityOptionsForFieldType=Tme;exports.getKeys=yr;exports.getMatrixVisualLoadingState=X_;exports.getMetricDisplayLabel=g3e;exports.getNewField=Ure;exports.getObjectDiff=iY;exports.getPaginationRowModel=tI;exports.getRoleBasedDisplayOverrides=UQ;exports.getRunningTotalOrderByCandidates=Mht;exports.getSelectedDateFilterColumn=Uce;exports.getSortedRowModel=Soe;exports.getTableConditionalFormattingColumnOptions=xpe;exports.getTableOutputColumnOptions=ype;exports.getTablePageSizeOptions=Jre;exports.handleAggregationChange=QP;exports.handleAggregationLabelChange=Due;exports.hasFlatTableTotalsBehavior=qm;exports.hasMatrixResultData=gw;exports.horizontalListSortingStrategy=Oz;exports.inferSemanticDomainIdFromSelectedEntities=Sk;exports.isActiveBriefingRunStatus=Wj;exports.isCardSummaryVisibleOnCard=z$;exports.isCurrencyPresentationControl=b0e;exports.isDefaultColor=xTe;exports.isEligibleFlatTableTotalsCard=rw;exports.isExportComplete=s$e;exports.isExportInProgress=o$e;exports.isInAiScopeArray=vNt;exports.isManagedCalculatedExpressionField=Qa;exports.isMetricTransformEnabled=Eht;exports.isPresentationCurrencyBinding=Ov;exports.isPromiseLike=GF;exports.isSqlBackedKpi=Wre;exports.isStructuralControlBinding=g0e;exports.isSubtotalEnabledAggregateTable=Uz;exports.isSupportedDocumentTableCardType=Kpt;exports.isTableType=zEe;exports.isTerminalBriefingRunStatus=Uj;exports.lastAssistantMessageIsCompleteWithToolCalls=tbe;exports.listBriefingRuns=Itt;exports.listBriefingTenantSummaries=_tt;exports.listBriefings=ktt;exports.merge=Jl;exports.mergeAxisConfig=KR;exports.normalizeConditionalFormatting=A5;exports.normalizeContextFormatMode=yee;exports.normalizeDashboardInputVariableName=Lv;exports.pauseBriefing=Zue;exports.pivotData=sw;exports.polishBriefingText=ade;exports.prepareFeedbackData=FT;exports.previewBriefingPlan=ede;exports.remarkGfm=_z;exports.removeFromScopeArray=CNt;exports.requiresDashboardInputResolution=uf;exports.resolveCurrencyPresentationTargetFormat=See;exports.resolveDashboardBriefingsVisibility=Ofe;exports.resolveDashboardControlsVisibility=uNe;exports.resolveDashboardInputContext=Yi;exports.resolveDashboardTitleEditability=cNe;exports.resolveDomainCalculatedFieldForEdit=opt;exports.resolveMatrixCardMeasureInstances=Mk;exports.resolvePendingPivotTableResultState=q3e;exports.resolveTablePageSize=G_;exports.resolveTablePresentationStyle=p3;exports.resumeBriefing=Xue;exports.runBriefingNow=Jue;exports.runBriefingPreview=tde;exports.sanitizeAIScope=obe;exports.saveCalculatedFieldToCardScope=IF;exports.saveCalculatedFieldToSharedScope=hme;exports.saveCalculatedFieldToSheetScope=TF;exports.seedSemanticMetricFormatDefaults=Vhe;exports.setTableColumnVisibility=ooe;exports.setupEditorWithCard=S_;exports.showAllTableColumns=g$e;exports.showJoinRequiredNotification=$re;exports.sortByColumnsToSortState=Woe;exports.sortStateToSortByColumns=Koe;exports.sortableKeyboardCoordinates=$z;exports.supportsLiveNumericPresentation=Fv;exports.supportsMetricTransformForMetric=Bhe;exports.supportsTableConditionalFormatting=ppe;exports.toEntityArray=Xa;exports.ue=lt;exports.updateBriefing=UI;exports.useActiveExports=gNe;exports.useActiveToolStatus=Lbe;exports.useAddFrameWithFreshSemanticExecutionPayload=Q$;exports.useAddNewFrame=Kfe;exports.useAssistantContainer=ZQ;exports.useAssistantContextEntities=eT;exports.useAssistantLayoutStore=Mh;exports.useAssistantPanel=GQ;exports.useAssistantProfile=vbe;exports.useAutoSubmitQueue=Obe;exports.useBrandStudioPreview=c_t;exports.useBriefingRunPolling=sF;exports.useBriefingUiCapabilities=Lfe;exports.useCalendarContext=_3e;exports.useCard=A3e;exports.useCardNumericPresentation=Ta;exports.useCardSummary=B$;exports.useChartNumericPresentation=jb;exports.useChat=rbe;exports.useColumns=Vz;exports.useCreateVisualWithFrame=nSe;exports.useCurrentUserInfo=ti;exports.useCustomVisual=Nf;exports.useCustomVisualsQuery=R$;exports.useDashboardAppearance=Ru;exports.useDashboardById=UX;exports.useDashboardInteractionMode=Iue;exports.useDashboardPreferences=Lm;exports.useDashboardQuery=Pv;exports.useDashboardStructuralParticipants=$me;exports.useDashboardSummary=due;exports.useDataColumns=qhe;exports.useDateFilterHook=VGe;exports.useDefaultDashboardMutation=LX;exports.useDisplayPreferences=cl;exports.useDroppable=ghe;exports.useEditorAside=mT;exports.useEditorCardQuery=pb;exports.useEffectiveEditorCardType=G4;exports.useEnsureReactGlobals=ble;exports.useExportActions=XQ;exports.useExportStore=Gk;exports.useFieldManagement=Hhe;exports.useFilterableFields=Ohe;exports.useFullscreenAssistant=YQ;exports.useGroupMembers=o1e;exports.useGroups=XO;exports.useHasDashboardId=QQ;exports.useInProgressExportsCount=bNe;exports.useJoinabilityMap=qz;exports.useManagementActions=Dm;exports.useManagementStore=_s;exports.useMutation=ks;exports.usePivotTableConfig=Gm;exports.usePluginQuery=Jce;exports.useQuery=Un;exports.useQueryClient=Wr;exports.useReactTable=nI;exports.useResolveExistingFrameSemanticExecutionPayload=Met;exports.useResolvedDefaultCurrency=XL;exports.useResolvedTemporalStylePreferences=fl;exports.useResolvedValueFormatLocale=ZL;exports.useResourceManagement=WO;exports.useResourceUpdateState=WX;exports.useScopedFields=Fhe;exports.useSelectedVisual=n0e;exports.useSemaphorContext=It;exports.useSensor=nb;exports.useSensors=oT;exports.useSortable=tx;exports.useStarredChartsStore=oIt;exports.useSurfaceAppearance=dc;exports.useTableQueryState=Ooe;exports.useTextFilterHook=bUe;exports.useTheme=oO;exports.useTimezone=dl;exports.useTopoJson=hw;exports.useUnifiedUsers=Wk;exports.useUpdateResource=BX;exports.useUpdateVisualMutation=rSe;exports.useUserPreferences=mQ;exports.useVisualById=Bk;exports.useVisualManagement=tSe;exports.validateBriefingFormDraft=oF;exports.validateFieldForChartType=$he;exports.verticalListSortingStrategy=Lz;
|
|
1392
|
+
`).trim(),k=j.map((T,I)=>{var R,A;let E="",D;if((R=T.url)!=null&&R.startsWith("data:")){const F=T.url.match(/data:[^;]+;base64,(.+)/);F&&(E=F[1],(A=T.mediaType)!=null&&A.startsWith("image/")&&(D=T.url))}return{id:`${e.id||t}-file-${I}`,name:T.filename||`File ${I+1}`,size:0,type:T.mediaType||"application/octet-stream",data:E,preview:D}});return l.jsx(Nkt,{text:_||void 0,files:k.length>0?k:void 0})}const f=((C=e.parts)==null?void 0:C.filter(S=>S.type==="reasoning"))||[],h=f.length>0,m=f.some(S=>S.state==="streaming"),g=f.filter(S=>S.text&&S.text.trim().length>0),b=h&&(g.length>0||m)?l.jsxs(vu,{className:"space-y-2",defaultOpen:!1,children:[l.jsx(wu,{asChild:!0,children:l.jsxs("button",{type:"button",className:"group inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:[l.jsx(Ft.ChevronRight,{className:"h-3 w-3 transition-transform duration-200 group-data-[state=open]:rotate-90"}),l.jsx("span",{className:m?"animate-pulse":"",children:m?"Reasoning":"Show reasoning"}),g.length>1&&l.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["(",g.length," steps)"]})]})}),l.jsx(Cu,{children:l.jsx("ol",{className:"space-y-2 border-l border-border/60 pl-3",children:g.map((S,j)=>l.jsxs("li",{className:"relative",children:[l.jsx("span",{className:"absolute -left-[15px] top-[3px] grid h-4 w-4 place-items-center rounded-full bg-muted font-mono text-[9px] text-muted-foreground",children:j+1}),l.jsx(IG,{className:"text-[12px] leading-[1.55] text-muted-foreground",text:S.text})]},`${e.id||t}-reasoning-${j}`))})})]},`${e.id||t}-reasoning`):null,x=(N=e.parts)==null?void 0:N.map((S,j)=>{var k;const _=`${e.id||t}-${j}`;switch(S.type){case"text":{const T=typeof S.text=="string"?S.text:JSON.stringify(S.text??"",null,2);if(e.role==="assistant"){const{cleanedText:I,quickReplies:E}=vkt(T),D=I.trim().length>0;return l.jsxs("div",{className:"space-y-2.5",children:[D&&l.jsx(IG,{text:I,handleRun:i,onAddToDashboard:o,messageId:e.id,messages:n}),E.length>0&&a&&d&&l.jsxs("div",{className:"space-y-1.5",children:[E.length>=3&&l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Suggested next steps"}),l.jsx("div",{className:"flex flex-wrap gap-1",children:E.map(({label:R,value:A},F)=>l.jsxs(p.Tooltip,{children:[l.jsx(p.TooltipTrigger,{asChild:!0,children:l.jsx(p.Button,{size:"sm",variant:"outline",className:"h-6 max-w-[220px] rounded-control border-border/60 bg-background px-2 text-[11px] font-normal text-foreground/85 transition-colors hover:border-border hover:bg-muted/40 hover:text-foreground disabled:opacity-50",disabled:c,onClick:()=>a(A),children:l.jsx("span",{className:"truncate",children:R})})}),l.jsx(p.TooltipContent,{side:"top",align:"center",children:l.jsx("p",{className:"max-w-xs text-xs",children:A})})]},`${_}-qr-${F}`))})]})]},_)}return e.role==="system"&&s?l.jsx(jkt,{text:T},_):null}case"error":{const T=S,I=T.errorText??T.error??T.message;return l.jsx("div",{className:"my-4",children:l.jsx(q4,{errorMessage:I})},_)}case"reasoning":return null;default:return((k=S.type)!=null&&k.startsWith("tool-")||S.type==="dynamic-tool")&&H4(S,r)?l.jsx(Si,{FallbackComponent:({error:T,resetErrorBoundary:I})=>l.jsx(Skt,{error:T,resetErrorBoundary:I}),children:l.jsx(pkt,{part:S,idx:_,messageId:e.id,showTools:r,onAddToDashboard:o,messages:n})},_):null}});return e.role==="assistant"?txe(e,r)?l.jsxs(exe,{who:"Assistant",className:"space-y-2",children:[b,x]}):null:l.jsxs("div",{className:"space-y-2",children:[b,x]})}const Tkt=8,Ekt=24,Dkt=20;function Mkt(e,t,n,r){return e==="error"&&t?!0:r?!1:!!(n||e==="submitted"||e==="streaming")}function nxe({messages:e,showTools:t=!1,showSystemMessage:n=!1,handleRun:r,onAddToDashboard:o,onQuickReply:s,disableQuickReplies:i=!1,status:a,errorMessage:c,activeToolText:u,className:d,rowContentClassName:f,statusClassName:h,latestButtonClassName:m,scrollToEndSignal:g=0}){const b=v.useRef(null),x=v.useRef(null),y=v.useRef(e.length),w=v.useRef(!1),C=v.useRef(null),N=v.useRef(!1),S=v.useRef(g),[j,_]=v.useState(!0),[k,T]=v.useState(0),[I,E]=v.useState(Ekt);S.current!==g&&(S.current=g,N.current=!0);const D=e[e.length-1],R=txe(D,t),A=Mkt(a,c,u,R),F=uI({count:e.length,getScrollElement:()=>b.current,estimateSize:H=>{const M=e[H];return(M==null?void 0:M.role)==="user"?88:180},getItemKey:H=>{const M=e[H];return(M==null?void 0:M.id)||`message-${H}`},anchorTo:"end",followOnAppend:!0,scrollEndThreshold:Tkt,overscan:6,gap:20,paddingEnd:A?I+Dkt:0,useAnimationFrameWithResizeObserver:!0,onChange:H=>{const M=H.isAtEnd();_(B=>B===M?B:M),M&&T(0)}}),z=v.useCallback((H="smooth")=>{C.current!==null&&cancelAnimationFrame(C.current),C.current=requestAnimationFrame(()=>{C.current=null,F.scrollToEnd({behavior:H})}),T(0),_(!0)},[F]);v.useLayoutEffect(()=>{w.current||(w.current=!0,z("auto"))},[z]),v.useLayoutEffect(()=>{N.current&&(N.current=!1,z("auto"))},[e.length,g,z]),v.useEffect(()=>{const H=y.current;y.current=e.length,e.length>H&&!F.isAtEnd()&&T(M=>M+e.length-H),e.length===0&&(T(0),_(!0),w.current=!1,N.current=!1)},[e.length,F]);const L=F.getVirtualItems(),$=F.getTotalSize();return v.useEffect(()=>()=>{C.current!==null&&cancelAnimationFrame(C.current)},[]),v.useLayoutEffect(()=>{const H=x.current;if(!H||!A)return;const M=()=>{const W=Math.ceil(H.getBoundingClientRect().height);W>0&&E(P=>P===W?P:W)};if(M(),typeof ResizeObserver>"u")return;const B=new ResizeObserver(M);return B.observe(H),()=>B.disconnect()},[A,a,c,u]),l.jsxs(l.Fragment,{children:[l.jsx(hl,{"data-role":"assistant-virtualized-scroll-area",ref:b,className:p.cn("min-h-0 min-w-0 flex-1 basis-0",d),children:l.jsxs("div",{className:"relative w-full",style:{height:$},children:[L.map(H=>{const M=e[H.index];return M?l.jsx("div",{ref:F.measureElement,"data-index":H.index,className:"absolute left-0 top-0 w-full",style:{transform:`translateY(${H.start}px)`},children:l.jsx("div",{className:p.cn("min-w-0",f),children:l.jsx(Ikt,{message:M,messageIndex:H.index,messages:e,showTools:t,showSystemMessage:n,handleRun:r,onAddToDashboard:o,onQuickReply:s,disableQuickReplies:i})})},H.key):null}),A&&l.jsx("div",{ref:x,className:p.cn("absolute left-0 top-0 w-full",h),style:{transform:`translateY(${Math.max($-I,0)}px)`},children:l.jsx("div",{className:p.cn("min-w-0",f),children:l.jsx(kkt,{status:a,errorMessage:c,activeToolText:u})})})]})}),!j&&l.jsxs("button",{type:"button",onClick:()=>z("smooth"),"aria-label":"Scroll to latest",className:p.cn("absolute right-4 z-10 inline-flex h-7 items-center gap-1.5 rounded-full border border-border bg-background px-2.5 text-[11px] text-foreground shadow-[0_1px_2px_rgba(0,0,0,0.08)] transition-colors hover:bg-muted/40",m),children:[l.jsx(es,{className:"h-3 w-3"}),"Latest",k>0&&l.jsx("span",{className:"grid h-4 min-w-[16px] place-items-center rounded-full bg-foreground px-1 font-mono text-[9px] tabular-nums text-background",children:k>9?"9+":k})]})]})}function Rkt(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return"";const t=e;return(typeof t.userSql=="string"?t.userSql:"")||(typeof t.sourceSql=="string"?t.sourceSql:"")||(typeof t.sql=="string"?t.sql:"")}const Akt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Pkt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:o}){const[s,i]=v.useState(!1),[a,c]=v.useState(dt.isDevEnv),[u,d]=v.useState(!1),[f,h]=v.useState("auto"),[m,g]=v.useState(!1),[b,x]=v.useState(!1),[y,w]=v.useState(0),C=n??b,{isLocalDev:N,isConsoleMode:S}=Lm(),j=N||S||a,_=v.useRef(null);p.useDashboardStore(re=>re.dashboard.aiScopeTables),p.useDashboardStore(re=>re.isDashboardEditing);const k=p.useDashboardStore(re=>re.selectedSheetId),{setDataSource:T}=p.useEditorActions(),{setSelectedFrameId:I,setIsDashboardEditing:E}=p.useDashboardActions(),D=Q$(),{clearAssistantMessageContexts:R}=p.useAIActions(),{clearQueue:A}=p.useQueueActions(),{clearFileAttachments:F,getFileAttachments:z}=p.useFileActions(),L=p.useFileAttachments("dashboard"),$=p.useEditorStore(re=>re.card.dataSource),{assistantProfile:H}=vbe(),M=p.useDashboardStore(re=>re.handleOpenAssistantProfile),{selectedEntities:B,applyDashboardDefaultEntities:W}=eT("dashboard"),{sendMessage:P,isLoading:G,messages:Z,setMessages:X,status:Y,stop:O,errorMessage:q,clearError:U}=zNt({dynamicVisualMode:f}),V=v.useCallback(()=>{w(re=>re+1)},[]),K=v.useCallback(re=>{r==null||r(re),n===void 0&&x(re)},[n,r]),Q=v.useCallback(()=>{K(!C)},[C,K]);v.useEffect(()=>{if(!C)return;function re(pe){pe.key==="Escape"&&K(!1)}return window.addEventListener("keydown",re),()=>{window.removeEventListener("keydown",re)}},[C,K]);const[se,oe]=v.useState(""),me=re=>{oe(re.target.value)};async function le({sql:re,cardTitle:pe,connectionId:Ee,cardType:Te,python:ze,cardConfig:Pe,dataSource:He,customVisualPreferences:ye,visualizationMode:Ke,dynamicCardPreferences:We}){if(!k)return;const Qe=Ke==="dynamic",xe=dt.hasValidCardConfig(Pe),Ve=Ee||(He==null?void 0:He.connectionId)||"",Ae=He?{...He,connectionId:Ve||He.connectionId,connectionType:He.connectionType||"",mode:He.mode||"database",selectedEntities:He.selectedEntities||[]}:Ve?{connectionId:Ve,connectionType:"",mode:"database",selectedEntities:[]}:sb,Be=!(xe&&(!Qe||(We==null?void 0:We.provenance)==="card-config"||(We==null?void 0:We.provenance)==="query_spec")),Ie=Be?Rkt(re):"",$e=Be?ze:"",st={id:dt.v4(),title:pe||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:Te==="horizontalBar"?"y":"x"},...Qe&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:Te,sql:Ie,python:$e,dataSource:Ae,config:Pe,connectionId:Ve,visualizationMode:Ke,dynamicCardPreferences:We,customCardPreferences:ye?{url:ye.url,componentName:ye.componentName,pluginChartType:ye.pluginChartType,settings:ye.settings,type:"component"}:void 0},ct={id:dt.v4(),cards:[st],activeCardId:st.id};try{await D(k,ct,"end"),E(!0),I(ct.id)}catch(rt){console.error("Failed to add assistant visual to dashboard:",rt),lt.error(rt instanceof Error?rt.message:"Failed to prepare semantic metadata for the new visual")}}const ue=re=>{re.preventDefault();const pe=se.trim();if(!pe&&L.length===0)return;const Ee=[];pe&&Ee.push({type:"text",text:pe}),L.forEach(Te=>{Te.data&&Ee.push({type:"file",mediaType:Te.type,filename:Te.name,url:`data:${Te.type};base64,${Te.data}`})}),P({role:"user",parts:Ee}),oe(""),F("dashboard"),V()};v.useEffect(()=>{var re;e&&((re=_.current)==null||re.focus())},[e]),Obe({assistantType:"dashboard",status:Y,isLoading:G,sendMessage:P});const{hasActiveTools:ne,activeToolText:de}=Lbe(Z);function Ce(re){const pe={role:"user",parts:[{type:"text",text:re.title+" "+re.subtitle}]};P(pe),V()}function ce(re){P({role:"user",parts:[{type:"text",text:re}]}),V()}function ie(re){P({role:"user",parts:[{type:"text",text:re}]}),V()}const we=v.useCallback(async()=>{const re=JSON.stringify(Z??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(re),lt.success("Conversation copied")}catch(pe){console.error("Failed to copy conversation",pe),lt.error("Unable to copy conversation")}},[Z]),fe=(se==null?void 0:se.length)===0&&(Z==null?void 0:Z.filter(re=>re.role==="user").length)===0;function ae(){return l.jsx("div",{"data-role":"header",className:"flex items-center gap-2",children:l.jsx("span",{className:"text-[13px] font-medium text-foreground",children:"Assistant"})})}function ee(){return l.jsxs(Uo,{children:[l.jsx(Wo,{asChild:!0,children:l.jsx(nu,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:l.jsx(Rm,{className:"size-3.5"})})}),l.jsxs(Do,{align:"end",children:[l.jsx(qa,{children:"Options"}),l.jsx(Sa,{}),l.jsx(nd,{checked:s,onCheckedChange:i,children:"Token Usage"}),l.jsx(nd,{checked:a,onCheckedChange:c,children:"Tool Invocations"}),l.jsx(nd,{checked:u,onCheckedChange:d,children:"System Message"}),(N||S)&&l.jsxs(l.Fragment,{children:[l.jsx(Sa,{}),l.jsx(qa,{children:"Dynamic Visuals"}),l.jsx(nd,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),l.jsx(nd,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),l.jsx(nd,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const J=l.jsxs("div",{"data-role":"dashboard-assistant",className:p.cn("relative flex h-full grow flex-col break-words bg-background",C&&"rounded-card border border-border/60 shadow-xl"),children:[l.jsxs("header",{"data-role":"header-section",className:"flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3",children:[ae(),M&&l.jsxs("button",{type:"button",onClick:M,className:"inline-flex h-6 items-center gap-1 rounded-[4px] border border-border/60 bg-muted/40 px-1.5 text-[11px] text-muted-foreground transition-colors hover:border-border hover:text-foreground",title:"Edit assistant profile",children:[l.jsx("span",{className:"h-1 w-1 rounded-full bg-muted-foreground/60"}),l.jsx("span",{className:"max-w-[180px] truncate",children:(H==null?void 0:H.name)||"Default profile"})]}),l.jsxs("div",{"data-role":"header-actions",className:"ml-auto flex items-center gap-0.5",children:[S&&ee(),j&&l.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-6 px-1.5 text-[11px] text-muted-foreground hover:text-foreground",onClick:we,children:"Copy Conversation"}),l.jsx(nu,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:C?"Exit fullscreen":"Expand",onClick:Q,children:C?l.jsx(Ft.Minimize2,{className:"h-3.5 w-3.5"}):l.jsx(Ft.Maximize2,{className:"h-3.5 w-3.5"})}),l.jsx(nu,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:"New chat",onClick:()=>{const re=Z.filter(pe=>pe.role==="assistant").map(pe=>pe.id).filter(pe=>!!pe);X([]),A("dashboard"),U(),R(re)},children:l.jsx(DO,{className:"h-3.5 w-3.5"})}),l.jsx(nu,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:"Close",onClick:()=>{t(!1)},children:l.jsx(je.X,{className:"h-3.5 w-3.5"})})]})]}),l.jsx(nxe,{messages:Z,showTools:a,showSystemMessage:u,onAddToDashboard:le,onQuickReply:ie,disableQuickReplies:G,status:Y,errorMessage:q,activeToolText:G&&ne?de:void 0,className:p.cn(C?"px-6 py-5":"px-3 py-3"),rowContentClassName:p.cn(C&&"mx-auto w-full max-w-[680px]"),latestButtonClassName:e?"bottom-[148px]":"hidden",scrollToEndSignal:y}),l.jsxs("div",{className:"shrink-0 space-y-2 border-t border-border/60 px-3 pb-3 pt-2",children:[!H&&fe&&l.jsx(Xpe,{onClick:Ce,placeholders:Akt}),fe&&H&&l.jsx(wbe,{seedQuestions:H.seedQuestions||[],handleSeedQuestionClick:ce}),l.jsx(Fbe,{assistantType:"dashboard"}),l.jsx(V4,{ref:_,setInput:oe,stop:O,input:se,handleInputChange:me,handleSubmit:re=>{ue(re)},isLoading:G,status:Y,assistantType:"dashboard",onFocus:()=>{}})]}),l.jsx(B4,{incomingSelectedEntities:B,open:m,onOpenChange:g,dataSource:$||sb,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:re=>W()})]});return C&&o?br.createPortal(l.jsx(Kb,{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background/95 px-4 pb-4 pt-[calc(var(--app-header-height,15px)+0.5rem)] backdrop-blur-sm",children:l.jsx("div",{className:"flex h-full w-full",children:J})}),o):J}function Fkt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=p.useDashboardActions(),o=_ue(),s=p.useDashboardStore(d=>d.dashboard.sheets),a=p.useDashboardStore(d=>d.selectedSheetId)??(s==null?void 0:s[0].id),c=p.useDashboardStore(d=>d.isDashboardEditing),u=p.useDashboardStore(d=>d.isVisualEditing);v.useEffect(()=>{if(!c||u)return;async function d(m){if(Okt(m.target))return;const g=m.ctrlKey||m.metaKey;g&&m.key==="c"?(await f(),lt.success("Card copied to clipboard"),m.preventDefault()):g&&m.key==="v"&&(await h(),m.preventDefault())}async function f(){try{const m=n();m&&await navigator.clipboard.writeText(JSON.stringify(m))}catch(m){console.error("Failed to copy text:",m)}}async function h(){if(!a)return null;try{const m=await navigator.clipboard.readText(),g=Lkt(m);if(g!=null&&g.id){const b=Nue(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await o(a,b),r(b.id),lt.success("Card pasted from clipboard")}return m}catch(m){return console.error("Failed to paste text:",m),null}}return t==null||t.addEventListener("keydown",d),()=>t==null?void 0:t.removeEventListener("keydown",d)},[o,n,r,a,c,u,t])}function Okt(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.closest("[contenteditable]");return t&&t.getAttribute("contenteditable")!=="false"?!0:!!e.closest('input, textarea, select, [role="textbox"]')}function Lkt(e){try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.id=="string"&&Array.isArray(t.cards)?t:null}catch{return null}}function $kt(e,t){switch(e.interactionMode){case"drillToDetail":zkt(e,t);break;case"drillThrough":Bkt(e,t);break;case"drillToURL":Vkt(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 zkt(e,t){var c;const{targetInsightId:n,contextMode:r,displayMode:o,filterGroups:s}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=s.flatMap(u=>u.filters);break;case"full":{const u=((c=t.getCurrentFilters)==null?void 0:c.call(t))||[],d=s.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}o==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function Bkt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:o,sourceCardId:s}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=o.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",c=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:c,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:c,filters:i,contextMode:r})}function Vkt(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 Hkt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:o,contextMode:s,cardTitle:i,cardDescription:a}){return l.jsx(Mo,{open:e,onOpenChange:t,children:l.jsxs(go,{className:"flex max-h-[90vh] max-w-[90vw] flex-col gap-0 overflow-hidden p-0",children:[l.jsxs(Is,{className:"space-y-1 border-b border-border px-5 pb-3.5 pt-4 text-left",children:[l.jsx(bo,{className:"text-[15px] font-semibold tracking-tight",children:i||"Insight detail"}),l.jsx(Ro,{className:"text-[12px] leading-[1.5] text-muted-foreground",children:a||"View detailed insight data with applied filters"})]}),l.jsx(Mue,{filters:r,filterDefinitions:o,contextMode:s}),l.jsx("div",{className:"h-[400px] min-h-0 flex-1 overflow-auto px-5 py-4",children:n?l.jsx(Bfe,{insightId:n,filters:r,contextMode:s}):l.jsx("div",{className:"flex items-center justify-center p-12 text-[13px] text-muted-foreground",children:"No insight selected"})})]})})}function qkt(){const e=p.useInteractionStore(N=>N.interactionStates),t=p.useInteractionStore(N=>N.setInteractionState),n=p.useInteractionStore(N=>N.clearLastInteractionEvent),r=p.useInteractionStore(N=>N.replaceCardWithInsight),o=p.useInteractionStore(N=>N.setPendingDrillThrough),s=p.useInteractionStore(N=>N.pendingDrillThrough),i=p.useInteractionStore(N=>N.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:c}=p.useDashboardActions(),{selectDashboard:u}=Dm(),d=p.useDashboardStore(N=>N.dashboard),f=p.useDashboardStore(N=>N.filterValues),{data:h,isLoading:m}=UX((s==null?void 0:s.targetDashboardId)||"",{enabled:!!(s!=null&&s.targetDashboardId)}),[g,b]=v.useState({open:!1,insightId:""}),x=Vfe(g.insightId,{enabled:g.open&&!!g.insightId}),y=v.useRef(new Set),w=v.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:N,filters:S,contextMode:j})=>{b({open:!0,insightId:N,filters:S,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:j})},replaceCardContent:({cardId:N,insightId:S,filters:j,contextMode:_})=>{r(N,S,j,_)},getCurrentFilters:()=>f||[],navigateWithDrill:c,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:o,setGlobalDrillContext:({filters:N,contextMode:S,sourceDashboardId:j,sourceDashboardTitle:_,targetDashboardId:k})=>{const T={filters:N},I={sourceCardId:p.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[T]},E={...p.createInitialInteractionState(),appliedClickFilters:[I],contextMode:S,sourceDashboardId:j,sourceDashboardTitle:_,targetDashboardId:k};t(p.DRILL_CONTEXT_CARD_ID,E)}}),[a,r,f,c,d,o,t]);v.useEffect(()=>{Object.entries(e).forEach(([N,S])=>{if(S!=null&&S.lastInteractionEvent){const j=S.lastInteractionEvent,_=`${N}-${j.interactionMode}-${j.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{$kt(j,w)}catch(k){console.error("Error executing interaction event:",k)}finally{n(N),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,w]),v.useEffect(()=>{if(!(!s||!h||m))try{u(h),c(s.targetDashboardId,s.sourceDashboardId,s.sourceDashboardTitle,s.filters,s.contextMode),i()}catch(N){console.error("[DrillThrough] Error during automatic navigation:",N),i()}},[s,h,m,u,c,i]);const C=()=>{b({open:!1,insightId:""})};return l.jsxs(l.Fragment,{children:[l.jsx(Hkt,{open:g.open,onOpenChange:C,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),s&&m&&l.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:l.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[l.jsx(p.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),l.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function Ukt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,o=Wkt(ez(t));return r==="="?`${n} = ${o}`:`${n} ${r} ${o}`}).join(", ")}function Wkt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function Kkt(e){return e?`Back to ${e}`:"Back"}function Gkt(){var y,w,C,N,S;const e=p.useInteractionStore(j=>j.interactionStates[p.DRILL_CONTEXT_CARD_ID]),t=p.useDashboardStore(j=>j.actions.goBackFromDrill),n=p.useDashboardStore(j=>j.actions.clearDrillContext),{selectDashboard:r}=Dm(),[o,s]=v.useState({x:16,y:16}),[i,a]=v.useState(!1),c=v.useRef({x:0,y:0});v.useEffect(()=>{if(!i)return;const j=k=>{s({x:k.clientX-c.current.x,y:k.clientY-c.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",j),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",j),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((N=(C=(w=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:w.filterGroups)==null?void 0:C[0])==null?void 0:N.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 m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(j){console.error("[DrillBack] Error during back navigation:",j)}},g=()=>{n()},b=j=>{j.target.closest("button")||(a(!0),c.current={x:j.clientX-o.x,y:j.clientY-o.y})};Ukt(f);const x=Kkt(d);return l.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${o.x}px, ${o.y}px)`,transition:i?"none":void 0},children:l.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:b,style:{cursor:i?"grabbing":"grab"},children:[l.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[l.jsxs("div",{className:"flex flex-col gap-2",children:[l.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((j,_)=>{const k=j.field.label||j.field.name,T=String(j.value);return l.jsxs(mi,{variant:"secondary",className:"pointer-events-none text-xs",children:[k," = ",T]},_)})})]}),l.jsx(p.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:l.jsx(je.X,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:l.jsxs(p.Button,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[l.jsx(zv,{className:"mr-2 h-4 w-4"}),x]})})]})})}function Ykt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function Zkt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:o,filterQueryContext:s,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:m,transition:g,isDragging:b}=tx({id:`filter:${e.id}`,disabled:n||!t}),x={transform:Ki.Translate.toString(m),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return l.jsx("div",{ref:h,style:x,...d,children:l.jsx(P$,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:o,filterQueryContext:s,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:c,onRemoveFilter:u})})}const OG="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",Xkt=[];function rxe({open:e,onOpenChange:t}){const[n,r]=v.useState(!1),[o,s]=v.useState(!1),[i,a]=v.useState({sheetSelection:"current",protectPdf:!1,password:""}),c=p.useDashboardStore(X=>{var Y;return(Y=X.dashboard)==null?void 0:Y.sheets}),u=p.useDashboardStore(X=>X.dashboard),d=p.useDashboardStore(X=>X.dashboardInputValues),f=p.useDashboardStore(X=>X.filterValues),h=p.useDashboardStore(X=>X.controlValues),m=p.useDashboardStore(X=>X.inlineFilterValuesMap),g=p.useDashboardStore(X=>X.cardControlValuesMap),b=p.useDashboardStore(X=>X.selectedSheetId),x=p.useDashboardStore(X=>X.selectedSheetId?X.documentInputRuntimeBySheetId[X.selectedSheetId]:void 0),y=p.useDashboardStore(X=>X.isDownloadingPdf),w=p.useDashboardStore(X=>X.reportContext),{authToken:C,tokenProps:N}=It(),S=c==null?void 0:c.find(X=>X.id===b),j=v.useMemo(()=>p.getDashboardExportSheets(c),[c]),_=p.isDocumentSheet(S),k=_&&S?S.document:void 0,T=v.useMemo(()=>_&&S?rx(u,S.id):[],[S,_,u]),I=T.length>0,E=v.useMemo(()=>_&&S?kpe(u,S.id):!1,[S,_,u]),D=v.useMemo(()=>I?T.map(lC):(k==null?void 0:k.inputs)||Xkt,[k,T,I]),R=w==null?void 0:w.calendar.tz,A=v.useMemo(()=>Nme(D),[D]),F=v.useMemo(()=>Cme(D,R),[D,R]),z=v.useMemo(()=>Sme(D),[D]),L=x?x.filterValuesByInputId:F,$=x?x.controlValuesByInputId:z,H=v.useMemo(()=>_?E&&S&&k?YY({dashboard:u,sheetId:S.id,sheetKind:"document",sectionIds:k.sections.map(X=>X.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},timezone:R}):_me(D,L,$,A,A):[],[k,D,S,_,u,g,h,f,m,d,$,L,A,R,E]),M=!!S,B=j.length>0,W=((c==null?void 0:c.length)||0)>1||_,P=i.sheetSelection==="current"&&(!M||_&&H.length>0)||i.sheetSelection==="all"&&!B;v.useEffect(()=>{e&&i.sheetSelection==="all"&&!B&&a(X=>({...X,sheetSelection:"current"}))},[B,e,i.sheetSelection]);const G=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function Z(){if(y){lt.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){lt.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!M){lt.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!B){lt.error("No dashboard sheets are available to export");return}s(!0);const X=i.sheetSelection==="current"&&_,Y=X?i.protectPdf?"Generating protected document PDF... may take up to 60 seconds":"Generating document PDF... may take up to 60 seconds":i.sheetSelection==="all"?"Generating PDF for all dashboard sheets... This may take a while.":i.protectPdf?"Generating protected PDF... may take up to 60 seconds":"Generating PDF... may take up to 60 seconds",O=lt.loading(Y);try{if(X){if(!k||!S)throw new Error("Selected document sheet is missing document data");if(H.length>0){lt.dismiss(O),lt.error(`Set ${H.join(", ")} before exporting`);return}const U=new Date().toISOString(),V=E?ZY({dashboard:u,sheetId:S.id,sheetKind:"document",sectionIds:k.sections.map(K=>K.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},generatedAt:U,timezone:R}).snapshot:void 0;await Q5(N.apiServiceUrl,C,{sheetId:S.id,title:S.title||"Document",pageSize:k.page.size,orientation:k.page.orientation,timezone:R,password:i.protectPdf?i.password:void 0,inputSnapshot:V,...V?{}:{inputValues:{sheetId:S.id,filterValuesByInputId:L,controlValuesByInputId:$,generatedAt:U}}})}else{const U=eoe();await Uee(N.apiServiceUrl,C,i.protectPdf?i.password:void 0,i.sheetSelection,U)}lt.dismiss(O);const q=X?i.protectPdf?"Protected document PDF downloaded successfully!":"Document PDF downloaded successfully!":i.sheetSelection==="all"?"Dashboard sheets PDF downloaded successfully!":i.protectPdf?"Protected PDF downloaded successfully!":"PDF downloaded successfully!";lt.success(q,{duration:2e3}),G()}catch(q){lt.dismiss(O),lt.error("Failed to download PDF",{description:j_(q,"Please try again or contact support."),descriptionClassName:N_,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",q)}finally{s(!1)}}return l.jsx(Mo,{open:e,onOpenChange:X=>{if(!X){G();return}t(!0)},children:l.jsxs(go,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[l.jsxs(Is,{children:[l.jsx(bo,{className:"text-[15px]",children:_?"Export document":"Export dashboard"}),l.jsx(Ro,{className:"text-[13px] leading-5",children:_?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),l.jsxs("div",{className:"space-y-4 py-1",children:[W&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx(p.Label,{className:OG,children:"Export scope"}),l.jsxs(rl,{value:i.sheetSelection,onValueChange:X=>a({...i,sheetSelection:X}),className:"gap-1.5",children:[l.jsxs(p.Label,{htmlFor:"scope-current",className:p.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!M&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(vs,{value:"current",id:"scope-current",disabled:!M}),_?"This document":"This sheet"," (",(S==null?void 0:S.title)||"Current",")"]}),l.jsxs(p.Label,{htmlFor:"scope-all",className:p.cn("flex cursor-pointer items-center gap-2 rounded-control px-1 py-1 text-[13px] font-normal hover:bg-muted/50",!B&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[l.jsx(vs,{value:"all",id:"scope-all",disabled:!B}),"Dashboard sheets (",j.length," ",j.length===1?"sheet":"sheets",")"]})]}),_&&l.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:H.length>0?`Set ${H.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),l.jsx(p.Separator,{className:"bg-border/60"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsxs(p.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[l.jsx(Tn,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:X=>{a({...i,protectPdf:X,password:X?i.password:""}),X||r(!1)}}),l.jsx(Vv,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&l.jsxs("div",{className:"ml-6 space-y-1.5",children:[l.jsx(p.Label,{htmlFor:"pdf-password",className:OG,children:"Password"}),l.jsxs("div",{className:"relative",children:[l.jsx(p.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:X=>a({...i,password:X.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:X=>{X.key==="Enter"&&i.password&&Z()}}),l.jsx("button",{type:"button",className:"absolute right-1 top-1/2 flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>r(!n),"aria-label":n?"Hide password":"Show password",children:n?l.jsx(Ak,{className:"h-3.5 w-3.5"}):l.jsx(Ft.Eye,{className:"h-3.5 w-3.5"})})]}),l.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),l.jsxs(tl,{children:[l.jsx(p.Button,{variant:"outline",size:"xs",onClick:G,disabled:o,children:"Cancel"}),l.jsx(p.Button,{size:"xs",onClick:Z,disabled:o||y||P,children:o?l.jsxs(l.Fragment,{children:[l.jsx(p.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):l.jsxs(l.Fragment,{children:[l.jsx(Su,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function oxe({iconClassName:e,open:t,onOpenChange:n}){const[r,o]=v.useState(!1),s=t!==void 0,i=s?t:r,a=u=>{s||o(u),n==null||n(u)},c=p.useDashboardStore(u=>u.isDownloadingPdf);return l.jsxs(l.Fragment,{children:[s?null:l.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:c,onClick:()=>a(!0),children:l.jsx(Su,{className:p.cn("size-4",e)})}),l.jsx(rxe,{open:i,onOpenChange:a})]})}function LG(e,t,n){const r=new Set(t),o=[...n];return e.map(s=>r.has(s.id)?o.shift()??s.id:s.id)}function Qkt({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:o,listeners:s,setNodeRef:i,transform:a,transition:c,isDragging:u}=tx({id:`control:${e.id}`,disabled:!n}),d={transform:Ki.Translate.toString(a),transition:c,opacity:u?.5:1,zIndex:u?10:void 0};return l.jsx("div",{ref:i,style:d,...o,children:l.jsx(qme,{control:e,value:t,isEditing:n,dragListeners:n?s:void 0,onChange:r})})}function $G(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function zG(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function Jkt(e,t,n){const r=new Set([...t.map(a=>`filter:${a.id}`),...n.map(a=>`control:${a.id}`)]);if(!(e!=null&&e.length))return zG(t,n);const o=e.filter(a=>r.has(a)),s=new Set(o),i=zG(t,n).filter(a=>!s.has(a));return[...o,...i]}function e_t(e,t){return p.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function t_t(e){return Qh(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>Qh(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function F2(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function n_t(e){return sxe(e).filter(t=>{var n,r;return t.filter.hide||t.filter.location==="frame"?!1:((n=t.compatibility)==null?void 0:n.source)==="dashboardFilter"?!0:(((r=t.presentation)==null?void 0:r.placement)||"toolbar")==="toolbar"})}function sxe(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=e_t(e.dashboard,t);return Rk(ab({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!t_t({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function r_t(e,t){return"toolbar"}function o_t(){const e=dc("interactive"),t=p.useDashboardStore(q=>q.selectedSheetId),n=p.useDashboardStore(q=>q.dashboard.filters),r=p.useDashboardStore(q=>q.dashboard.filterLayout),o=p.useDashboardStore(q=>q.isDashboardEditing),s=p.useDashboardStore(q=>q.controlValues),i=p.useDashboardStore(q=>q.filterValues);p.useDashboardStore(q=>q.filteringCards);const a=p.useDashboardStore(q=>q.inlineFilterValuesMap),c=p.useDashboardStore(q=>q.dashboardInputValues),u=p.useInteractionStore(q=>q.clearAllClickFilters),d=p.useInteractionStore(q=>Object.entries(q.interactionStates).reduce((U,[V,K])=>{var Q;return V===p.DRILL_CONTEXT_CARD_ID?U:U+(((Q=K.appliedClickFilters)==null?void 0:Q.length)??0)},0)),f=p.useDashboardStore(q=>q.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:m,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:w,setFilteringCards:C,upsertDashboardInput:N}=p.useDashboardActions(),S=oT(nb(Jb,{activationConstraint:{distance:5}})),j=p.useDashboardStore(q=>q.dashboard),_=n_t({dashboard:j,selectedSheetId:t}).filter(q=>r_t(q.filter)==="toolbar"),k=sxe({dashboard:j,selectedSheetId:t}),T=_.map(q=>q.filter),I=new Map(_.map(q=>[`filter:${q.filter.id}`,q])),E=stt(j),D=E.filter(q=>!q.hidden&&nv(q)==="toolbar"),R=E.filter(q=>!q.hidden&&nv(q)==="advanced"),A=Jkt(r==null?void 0:r.toolbarItemOrder,T,D),F=new Map(T.map(q=>[`filter:${q.id}`,q])),z=new Map(D.map(q=>[`control:${q.id}`,q]));function L(q){const{active:U,over:V}=q;if(!V||U.id===V.id)return;const K=String(U.id),Q=String(V.id),se=A.findIndex(ce=>ce===K),oe=A.findIndex(ce=>ce===Q);if(se===-1||oe===-1)return;const me=ex(A,se,oe);y({toolbarItemOrder:me});const le=new Set((n||[]).map(ce=>ce.id)),ue=A.filter(ce=>ce.startsWith("filter:")).map(ce=>ce.replace("filter:","")).filter(ce=>le.has(ce)),ne=me.filter(ce=>ce.startsWith("filter:")).map(ce=>ce.replace("filter:","")).filter(ce=>le.has(ce)),de=A.filter(ce=>ce.startsWith("control:")).map(ce=>ce.replace("control:","")),Ce=me.filter(ce=>ce.startsWith("control:")).map(ce=>ce.replace("control:",""));h(LG(n||[],ue,ne)),g(LG(j.controls||[],de,Ce))}const $=(r==null?void 0:r.toolbarWrap)??!1,H=(r==null?void 0:r.showDownloadButton)??!1,M=k.filter(F2),B=k.filter(q=>{if(F2(q))return!1;const U=p.getDashboardInputRuntimeSlot(c,q,{sheetId:t});return(U==null?void 0:U.status)==="set"||(U==null?void 0:U.status)==="cleared"}),W=new Set([...M,...B].map(q=>q.filter.id)),P=(i==null?void 0:i.filter(q=>!W.has(q.filterId)&&$G(q)).length)??0,G=[...M,...B],Z=G.filter(q=>{const U=p.hydrateAuthoredDashboardInputSlot({dashboard:j,input:q,runtimeValues:c,target:{sheetId:t}});return(U==null?void 0:U.status)==="set"&&U.value.kind==="filter"&&$G(U.value.filterValue)}).length,X=a?Object.values(a).reduce((q,U)=>q+((U==null?void 0:U.length)??0),0):0,Y=P+Z+X+d,O=()=>{w([]),G.forEach(q=>{m(q,{sheetId:t})}),C([]),u(),a&&Object.entries(a).forEach(([q,U])=>{U==null||U.forEach(V=>{f(q,V.filterId)})})};return!T.length&&!D.length&&!R.length&&!H&&Y===0?null:l.jsx("div",{className:"z-20 border-b border-border/60 bg-background/95 px-3 py-2 backdrop-blur supports-[backdrop-filter]:bg-background/85",style:e.containerStyle,role:"toolbar","aria-label":"Dashboard filters and controls",children:l.jsx(nC,{sensors:S,collisionDetection:Jw,onDragEnd:L,children:l.jsxs("div",{className:p.cn("flex items-center",$?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[l.jsx(rC,{items:A,strategy:Oz,children:l.jsx(MF,{className:"gap-3 pr-0",wrap:$,children:A.map(q=>{const U=F.get(q);if(U){const K=I.get(q),Q=K&&F2(K);return l.jsx(Zkt,{filter:U,isEditing:o,storageOptions:Q?{storageTarget:"dashboardInput",dashboardInput:K,sheetId:t??void 0}:void 0,inputVariableName:Q?K.variableName:void 0,onUpdateFilter:Q?(se,oe)=>{N({...K,variableName:(oe==null?void 0:oe.variableName)||K.variableName,filter:se})}:void 0,onRemoveFilter:Q?()=>{w((i||[]).filter(se=>se.filterId!==U.id)),b(K.id)}:void 0},q)}const V=z.get(q);return V?l.jsx(Qkt,{control:V,value:s==null?void 0:s[V.id],isEditing:o,onChange:K=>x(V.id,K)},q):null})})}),R.length>0&&l.jsx(zue,{title:"",controls:R,values:s,onChange:(q,U)=>x(q.id,U),immediatePlacement:"toolbar",advancedLabel:"More controls"}),Y>0&&l.jsxs("button",{type:"button",onClick:O,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[l.jsx(je.X,{className:"h-3 w-3"}),"Clear all",l.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:Y})]}),H&&l.jsx("div",{className:p.cn(Y>0?"ml-1.5":"ml-auto"),children:l.jsx(oxe,{})})]})})})}function ixe(){var ie,we;const{showAssistant:e,tokenProps:t,renderMode:n}=It(),r=Ykt((ie=t.config)==null?void 0:ie.showDashboardAssistant,e),{preferences:o}=Lm(),s=(we=o==null?void 0:o.cardDisplay)==null?void 0:we.mode,i=mf(s),a=eee({displayMode:s,renderMode:n}),c=v.useRef(null),u=v.useRef(null),[d,f]=v.useState(!1),{handleDragStart:h,isDraggingRef:m,getStyle:g,getPositionClasses:b}=I0t({initialPosition:"bottom-right"}),x=Mh(fe=>fe.setFullscreen),y=Mh(fe=>fe.setPanelOpen),w=Mh(fe=>fe.setContainer),C=GQ("dashboard"),N=YQ(),S=ZQ("dashboard"),j=C.isOpen,_=N==="dashboard",k=p.useDashboardStore(fe=>fe.isVisualEditing),T=p.useDashboardStore(fe=>fe.themeStyle),I=Ru(),E=p.useDashboardStore(fe=>{var ae;return(ae=fe.dashboard)==null?void 0:ae.sheets}),D=p.useDashboardStore(fe=>fe.showFilters),R=p.useDashboardStore(fe=>fe.isDashboardEditing),A=p.useDashboardStore(fe=>fe.selectedSheetId),F=E==null?void 0:E.find(fe=>fe.id===A),z=p.useDashboardStore(fe=>{var ae,ee,J;return(J=(ee=(ae=fe.dashboard)==null?void 0:ae.sheets)==null?void 0:ee.find(re=>re.id===fe.selectedSheetId))==null?void 0:J.kind}),L=p.useDashboardStore(fe=>{var ae,ee;return((ee=(ae=fe.dashboard)==null?void 0:ae.summary)==null?void 0:ee.position)||"top"}),$=z==="document",H=p.useDashboardStore(fe=>{var ae;return(ae=fe.dashboard)==null?void 0:ae.id}),{getDefaultSheetId:M,setDefaultSheetId:B,clearDefaultSheetId:W}=_Y(H),[P,G]=v.useState(null),{setSelectedSheetId:Z,setSheetTitle:X,addSheet:Y,setSheets:O}=p.useDashboardActions();Fkt(u);const{setActiveAssistantType:q}=p.useAIActions();v.useEffect(()=>{if(H){const fe=M();G(fe)}},[H,M]),v.useEffect(()=>{j?q("dashboard"):N==="dashboard"&&x(null)},[j,q,N,x]),v.useEffect(()=>{var fe;j||(fe=c.current)==null||fe.resize(0)},[j]);function U(fe){var ae,ee;fe?((ae=c.current)==null||ae.resize(40),y("dashboard",!0),x("dashboard"),q("dashboard")):(y("dashboard",!1),x(null),(ee=c.current)==null||ee.resize(0),q(null))}function V(fe="dashboard"){const ae={id:dt.v4(),title:fe==="document"?"New Document":"New Sheet",...fe==="document"?{kind:fe,document:p.createDefaultDocumentDefinition()}:{}};Y(ae),Z(ae.id)}function K(fe,ae){if(!H)return;P===fe?(W(),G(null),lt.success("Default sheet cleared")):(B(fe),G(fe),lt.success(`"${ae}" set as default sheet`))}function Q(fe){var ae;fe<1?(y("dashboard",!1),x(null),q(null),(ae=c.current)==null||ae.resize(0)):(j||y("dashboard",!0),q("dashboard"))}function se(){return(T==null?void 0:T.canvasTheme)==="muted"||!(T!=null&&T.canvasTheme)?"hsl(var(--semaphor-muted))":(T==null?void 0:T.canvasTheme)==="clear"?"":T==null?void 0:T.canvasTheme}const oe=(fe,ae)=>{fe.dataTransfer.setData("tabIndex",ae.toString())},me=fe=>{fe.preventDefault()},le=(fe,ae)=>{const ee=fe.dataTransfer.getData("tabIndex");if(ee===ae.toString())return;const J=Array.from(E||[]),[re]=J.splice(parseInt(ee),1);J.splice(ae,0,re),O(J)},ue=r===!0&&!i&&!j&&!k&&!D;function ne(){if(E&&E.length>1||R)return l.jsx("div",{className:"relative flex w-full items-stretch border-b border-border",children:l.jsxs("div",{className:"relative min-w-0 flex-1",children:[l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 w-4 bg-gradient-to-r from-background to-transparent"}),l.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 right-0 z-10 w-4 bg-gradient-to-l from-background to-transparent"}),l.jsxs(p.TabsList,{role:"tab-list",className:"flex w-0 min-w-full items-stretch justify-start overflow-x-auto rounded-none bg-transparent p-0 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[E==null?void 0:E.map((fe,ae)=>{const ee=A===fe.id,J=P===fe.id;return l.jsxs(p.TabsTrigger,{draggable:!0,onDragStart:re=>oe(re,ae),onDragOver:me,onDrop:re=>le(re,ae),onClick:()=>Z(fe.id),className:p.cn("group relative inline-flex h-9 shrink-0 items-center gap-1.5 rounded-none bg-transparent px-3 py-0 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-transparent hover:text-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none","after:pointer-events-none after:absolute after:inset-x-2 after:-bottom-px after:h-0.5 after:bg-transparent data-[state=active]:after:bg-foreground"),value:fe.id,children:[fe.kind==="document"&&l.jsx(Qs,{className:"h-3 w-3 text-muted-foreground"}),l.jsx(Pj,{enabled:R&&ee,text:fe.title,onSave:re=>X(fe.id,re),children:fe.title},fe.id),l.jsx("span",{role:"button",tabIndex:0,"aria-label":J?"Clear default sheet":"Set as default sheet",title:J?"Clear default sheet":"Set as default sheet",onClick:re=>{re.stopPropagation(),K(fe.id,fe.title||"Sheet")},onKeyDown:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),re.stopPropagation(),K(fe.id,fe.title||"Sheet"))},className:p.cn("inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] transition-opacity hover:bg-muted focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",ee||J?"opacity-100":"opacity-0 group-hover:opacity-100"),children:l.jsx(FZ,{className:p.cn("h-3 w-3 transition-colors",J?"fill-current text-amber-500":"text-muted-foreground")})}),R&&ee&&E.length>1&&l.jsx("span",{role:"button",tabIndex:0,"aria-label":"Delete sheet",className:"inline-flex h-4 w-4 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus:outline-none focus-visible:ring-1 focus-visible:ring-foreground",onClick:re=>{re.stopPropagation(),f(!0)},onKeyDown:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),re.stopPropagation(),f(!0))},children:l.jsx(je.X,{className:"h-3 w-3"})})]},fe.id)}),R&&l.jsxs(Uo,{children:[l.jsx(Wo,{asChild:!0,children:l.jsxs("button",{type:"button","aria-label":"Add sheet",className:"ml-1 inline-flex h-9 shrink-0 items-center gap-1 px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground",children:[l.jsx(Tr,{className:"h-3 w-3"}),"Sheet"]})}),l.jsxs(Do,{align:"start",className:"w-48",children:[l.jsxs(kn,{onSelect:()=>V("dashboard"),children:[l.jsx(em,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),l.jsxs(kn,{onSelect:()=>V("document"),children:[l.jsx(Qs,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})})}function de(){return l.jsx("div",{ref:u,style:{},className:"h-full min-h-0 grow",children:E==null?void 0:E.map(fe=>l.jsx(p.TabsContent,{style:{backgroundColor:se(),...I.dashboardCanvasStyle},className:p.cn("mt-0 h-full min-h-0",{}),value:fe.id,children:l.jsx(RK,{sheet:fe})},fe.id))})}function Ce(){return l.jsxs(p.Tabs,{"data-role":"dashboard-tabs-container",className:p.cn("relative flex h-full flex-col",T==null?void 0:T.dashboardTabsContainer),onValueChange:fe=>{Z(fe)},value:A||void 0,children:[ne(),L==="top"&&!$&&l.jsx(GP,{}),A&&!$&&l.jsx(o_t,{}),$?l.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:de()}):l.jsx(hl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:de()}),L==="bottom"&&!$&&l.jsx(GP,{}),l.jsx(T0t,{open:d,setOpen:f})]})}const ce=v.useCallback(fe=>{w("dashboard",fe)},[w]);return E?a&&A&&!$?l.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',A,'" was not found or is not a document sheet in the loaded dashboard.']}):a&&$&&F?l.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:l.jsx(RK,{sheet:F})}):l.jsxs(l.Fragment,{children:[l.jsx(qkt,{}),l.jsx(Gkt,{}),l.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[l.jsxs(Zpe,{className:p.cn("flex-1 basis-0 overflow-y-auto transition-opacity",_&&"pointer-events-none opacity-0"),direction:"horizontal",children:[l.jsx(OF,{children:Ce()}),r===!0&&l.jsxs(l.Fragment,{children:[l.jsx(_0t,{open:j,onTabClick:U,withHandle:!0,disabled:!j}),l.jsx(OF,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:Q,defaultSize:j?40:0,ref:c,children:l.jsx("div",{className:"grow overflow-y-auto",children:l.jsx(Pkt,{open:j,setOpen:U,isFullscreen:_,onFullscreenChange:fe=>x(fe?"dashboard":null),fullscreenContainer:S})})})]})]}),l.jsx("div",{ref:ce,className:p.cn("absolute inset-0",!_&&"pointer-events-none")}),ue&&l.jsx("div",{className:p.cn("absolute z-50 transition-all duration-300 ease-in-out",b().horizontal,b().vertical),style:g(),children:l.jsx(p.Button,{size:"sm",variant:"outline",className:"h-12 w-12 cursor-grab rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted active:cursor-grabbing",onClick:()=>{m.current||U(!0)},onMouseDown:h,onTouchStart:h,title:"Open Assistant (drag to move)",children:l.jsx(_ve,{className:"h-5 w-5"})})})]})]}):null}const axe=v.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:o,children:s,className:i,style:a,...c},u)=>{const d=v.useId(),f=v.useMemo(()=>s_t(d),[d]),{theme:h}=oO(),m=i_t(h),g=v.useMemo(()=>o??cf.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,o,n]),b=v.useMemo(()=>p.compileAppearance({spec:g,systemMode:m}),[g,m]),x=v.useMemo(()=>p.createAppearanceContextValue(f,b),[b,f]);return l.jsx(p.AppearanceContext.Provider,{value:x,children:l.jsx(Kb,{...c,ref:u,className:i,style:a,children:s})})});axe.displayName="AppearanceProvider";function s_t(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function i_t(e){const t=iN(e),[n,r]=v.useState(()=>a_t());return v.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const o=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!o)return;const s=()=>{r(o.matches?"dark":"light")};return s(),typeof o.addEventListener=="function"?(o.addEventListener("change",s),()=>o.removeEventListener("change",s)):((a=o.addListener)==null||a.call(o,s),()=>{var c;return(c=o.removeListener)==null?void 0:c.call(o,s)})},[t]),t==="system"?n:t}function a_t(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const lxe=v.createContext({openBrandStudioPreview:()=>{}}),l_t=lxe.Provider;function c_t(){return v.useContext(lxe)}function u_t({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const o=iN(t),[s,i]=v.useState(()=>d_t(n)||o),a=v.useCallback(u=>{const d=iN(u);f_t(n,d),i(d)},[n]),c=v.useMemo(()=>({theme:s,setTheme:a}),[s,a]);return l.jsx(sY.Provider,{...r,value:c,children:e})}function d_t(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=iN(t,"system");return n===t?n:null}catch{return null}}function f_t(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const h_t=v.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function U4({appearance:e,children:t}){var E,D;const{authToken:n,id:r,tokenProps:o}=It(),s=Pv(),i=(E=s.data)==null?void 0:E.organizationAppearance,a=(D=o.config)==null?void 0:D.appearance,[c,u]=v.useState(!1),[d,f]=v.useState(null),[h,m]=v.useState(null),[g,b]=v.useState(null),[x,y]=v.useState(null),w=`${o.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,C=Un({queryKey:zX({resourceType:lo.DASHBOARD,apiServiceUrl:o.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>p.getRequest(`${o.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:R=>(R==null?void 0:R.organizationAppearance)??null,enabled:!s.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});v.useEffect(()=>{i!==void 0&&y({scopeKey:w,appearance:i})},[i,w]),v.useEffect(()=>{C.data!==void 0&&y({scopeKey:w,appearance:C.data})},[C.data,w]);const N=(x==null?void 0:x.scopeKey)===w?x.appearance:null,S=i!==void 0?i:C.data!==void 0?C.data:N,j=v.useMemo(()=>cf.resolveAppearance({organizationAppearance:S,tokenAppearance:a,reactAppearance:e}),[e,S,a]),_=v.useCallback(()=>{f(g??h??j),u(!0)},[g,h,j]),k=v.useCallback(()=>{u(!1)},[]);v.useEffect(()=>{f(null),m(null),b(null),u(!1)},[r]);const T=v.useMemo(()=>({openBrandStudioPreview:_}),[_]),I=g??h??e;return l.jsx(u_t,{defaultTheme:"system",storageKey:"vite-ui-theme",children:l.jsx(l_t,{value:T,children:l.jsx(axe,{organizationAppearance:S,tokenAppearance:a,reactAppearance:I,style:{height:"100%",width:"100%"},children:l.jsxs(p.TooltipProvider,{delayDuration:0,children:[t,c&&l.jsx("aside",{"aria-label":"Brand Studio","aria-modal":"false",role:"dialog",className:"fixed bottom-0 right-0 top-0 z-50 flex w-[min(520px,100vw)] flex-col border-l border-border bg-background text-foreground shadow-sm",children:l.jsx(v.Suspense,{fallback:l.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:l.jsx(h_t,{appearance:d,onDraftChange:b,onSave:R=>{m(R),b(R),f(R)},onCancel:k})})})]})})})})}function cxe({children:e,preferences:t}){const{currentUser:n}=ti(),r=v.useMemo(()=>{var o,s;return{preferences:t||{},isLocalDev:((o=t==null?void 0:t.uiMode)==null?void 0:o.developer)||!1,isConsoleMode:((s=t==null?void 0:t.uiMode)==null?void 0:s.console)||!1}},[t]);return l.jsx(OX.Provider,{value:r,children:l.jsx(HI,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function m_t(e=2e3,t=500){const n=Jye(),[r,o]=v.useState(!1),[s,i]=v.useState(!1),a=v.useRef(null);return v.useEffect(()=>{const c=setTimeout(()=>o(!0),e);return()=>clearTimeout(c)},[e]),v.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),s}function W4({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const o=m_t(e,t);return v.useEffect(()=>(o&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[o,n,r]),l.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:o?"ready":""})}function uxe(e){if(typeof window>"u")return null;const{preferences:t}=e;return l.jsx(Si,{FallbackComponent:BI,children:l.jsx(uO,{dashboardProps:e,children:l.jsxs(JI,{children:[l.jsx(W4,{componentType:"dashboard",componentId:e.id}),l.jsx(U4,{appearance:e.appearance,children:l.jsx(cxe,{preferences:t,children:l.jsx("main",{className:"flex h-full flex-col",children:l.jsx(JO,{...e,type:"dashboard",children:l.jsx(ixe,{})})})})})]})})})}function p_t(e=[]){const t=v.useRef(null),n=v.useRef(null),r=v.useRef(null),[o,s]=v.useState(),i=v.useCallback(()=>{var m,g,b;const a=((m=t.current)==null?void 0:m.clientWidth)??0,c=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-c-u-8,h=Math.max(f,0);s(x=>x===h?x:h)},[]);return v.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const c=new ResizeObserver(()=>i());return c.observe(a),i(),()=>c.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:o,updateAvailableWidth:i}}function g_t({filter:e}){var g;const t=p.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=Lm(),r=mf((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),o=p.useDashboardStore(b=>b.filterValues),s=o==null?void 0:o.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:c}=p.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:m}=p_t([t,s,r]);return v.useEffect(()=>{m()},[e.title,m]),l.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[l.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[l.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:l.jsx(p.Label,{className:"my-1 block w-full text-sm",children:l.jsx(xi,{value:e.title||e.column,onSave:b=>c({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),l.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&l.jsx(A$,{filter:e,isEditing:t}),t&&l.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:l.jsx(je.X,{className:"size-3.5"})})]})]}),l.jsx("div",{className:"hidden",ref:f})]})}function b_t(){const e=p.useDashboardStore(r=>r.dashboard.filters),t=p.useDashboardStore(r=>r.theme),n=e==null?void 0:e.filter(r=>r.hide);return n!=null&&n.length?l.jsx("div",{className:p.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":t==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":t==="dark"}),children:n==null?void 0:n.map(r=>l.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[l.jsx(g_t,{filter:r}),l.jsx(FI,{filter:r})]},r.id))}):null}function x_t(){var s;const e=p.useDashboardStore(i=>i.dashboard),t=p.useDashboardStore(i=>i.selectedSheetId),n=p.useDashboardStore(i=>i.isDashboardEditing),r=(s=e.sheets)==null?void 0:s.find(i=>i.id===t),o=p.isDocumentSheet(r);return l.jsx("div",{role:"dashboard-plus-main",className:"flex min-h-0 grow basis-0 overflow-hidden",children:l.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[n&&!o&&l.jsx(b_t,{}),l.jsx(ixe,{})]})})}const y_t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-BBnq7SH-.cjs"))),v_t=v.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-DDVhyor8.cjs"))),w_t=v.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-BEw43pFy.cjs")));function C_t({showControls:e=!1,showFooter:t=!0,...n}){const r=p.useDashboardStore(a=>a.isVisualEditing),o=p.useDashboardStore(a=>a.showDashboardJSON),{appearance:s,preferences:i}=n;return l.jsx(Si,{FallbackComponent:BI,children:l.jsx(uO,{dashboardProps:n,children:l.jsxs(JI,{children:[l.jsx(W4,{componentType:"surfboard",componentId:n.id}),l.jsxs(U4,{appearance:s,children:[l.jsx(RCe,{toastOptions:{classNames:{toast:"max-w-[calc(100vw-2rem)] overflow-x-hidden !items-start [--toast-close-button-end:0.5rem] [--toast-close-button-start:auto] [--toast-close-button-transform:translate(0,0)] sm:max-w-[44rem]",content:"min-w-0 flex-1",icon:"mt-0.5 shrink-0",title:"max-w-full break-words pr-8",description:"max-w-full break-words",closeButton:"!top-2 h-6 w-6 rounded-md border-border bg-background text-muted-foreground hover:bg-muted hover:text-foreground"}}}),l.jsxs(cxe,{preferences:i,children:[o&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(w_t,{})}),l.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(y_t,{})}),l.jsx("div",{className:"flex grow overflow-hidden",children:l.jsx("div",{className:"flex min-w-0 flex-1",children:l.jsxs(JO,{...n,type:"dashboard",children:[r&&l.jsx(v.Suspense,{fallback:null,children:l.jsx(v_t,{})}),l.jsx(v.Activity,{mode:r?"hidden":"visible",children:l.jsx(x_t,{})})]})})})]})]})]})]})})})}const XF=[{value:"en-US",label:"English (United States)"},{value:"en-GB",label:"English (United Kingdom)"},{value:"de-DE",label:"German (Germany)"},{value:"fr-FR",label:"French (France)"},{value:"es-ES",label:"Spanish (Spain)"},{value:"it-IT",label:"Italian (Italy)"},{value:"nl-NL",label:"Dutch (Netherlands)"},{value:"pt-BR",label:"Portuguese (Brazil)"},{value:"ja-JP",label:"Japanese (Japan)"},{value:"en-IN",label:"English (India)"},{value:"en-NZ",label:"English (New Zealand)"},{value:"mi-NZ",label:"Māori (New Zealand)"}],dxe=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","INR","BRL","KWD"]),S_t=Li.getSupportedCurrencyCodes(),N_t=S_t.filter(e=>!dxe.has(e)),fxe=[{value:"short",label:"Short"},{value:"medium",label:"Medium"},{value:"long",label:"Long"}],BG="2026-07-31",O2="2026-07-31T14:30:45";function QF(e){switch(e){case"viewer_user":return"user";case"viewer_tenant_user":return"tenant user";case"viewer_tenant":return"tenant";case"viewer_organization":return"organization";case"session_initial":return"embedded session";case"system_default":return"system";default:return"another preference level"}}function L2(e){var t;return((t=fxe.find(n=>n.value===e))==null?void 0:t.label)??e}function j_t(e){const t=XF.find(n=>n.value===e);return t?`${t.label} — ${t.value}`:e}function $2(e){return{short:e("short"),medium:e("medium"),long:e("long")}}function z2({id:e,label:t,value:n,inherited:r,inheritedSource:o,examples:s,disabled:i,onValueChange:a}){const c=n===void 0?`Inherited · ${L2(r)}`:L2(n);return l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{htmlFor:e,className:"text-[11px] text-muted-foreground",children:t}),l.jsxs(p.Select,{value:n??"inherit",disabled:i,onValueChange:a,children:[l.jsx(p.SelectTrigger,{id:e,size:"xs",children:l.jsx(p.SelectValue,{children:c})}),l.jsxs(p.SelectContent,{children:[l.jsx(p.SelectItem,{value:"inherit",className:"[&>span:last-child]:w-full",children:l.jsxs("span",{className:"flex w-full min-w-0 items-center justify-between gap-4",children:[l.jsxs("span",{children:["Inherited from ",QF(o)," ·"," ",L2(r)]}),l.jsx("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:s[r]})]})}),fxe.map(u=>l.jsx(p.SelectItem,{value:u.value,className:"[&>span:last-child]:w-full",children:l.jsxs("span",{className:"flex w-full min-w-0 items-center justify-between gap-4",children:[l.jsx("span",{children:u.label}),l.jsx("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:s[u.value]})]})},u.value))]})]})]})}function k_t({value:e,inherited:t,inheritedSources:n,onChange:r,disabled:o}){var j,_,k,T;const s=v.useId(),i=v.useId(),a=v.useId(),c=v.useId(),u=v.useId(),f=(e.locale===void 0?void 0:Li.canonicalizeSupportedLocale(e.locale))??t.locale,h=e.defaultCurrency??t.defaultCurrency,m={locale:f,dateStyle:e.dateStyle??t.dateStyle,dateTime:{dateStyle:((j=e.dateTime)==null?void 0:j.dateStyle)??t.dateTime.dateStyle,timeStyle:((_=e.dateTime)==null?void 0:_.timeStyle)??t.dateTime.timeStyle},defaultCurrency:h},g=new Intl.NumberFormat(f,{style:"currency",currency:h}).format(1e3),b=$t.resolveRawTemporalFormat({preferences:m,calendar:{tz:"UTC"}}),x=$t.formatRawTemporalValue({value:BG,metadata:{kind:"raw_temporal",valueKind:"date"},format:b}).text,y=$t.formatRawTemporalValue({value:O2,metadata:{kind:"raw_temporal",valueKind:"wall_datetime"},format:b}).text,w=$2(I=>$t.formatRawTemporalValue({value:BG,metadata:{kind:"raw_temporal",valueKind:"date"},format:$t.resolveRawTemporalFormat({preferences:{...m,dateStyle:I},calendar:{tz:"UTC"}})}).text),C=$2(I=>$t.formatRawTemporalValue({value:O2,metadata:{kind:"raw_temporal",valueKind:"wall_datetime"},format:$t.resolveRawTemporalFormat({preferences:{...m,dateTime:{...m.dateTime,dateStyle:I}},calendar:{tz:"UTC"}})}).text),N=$2(I=>$t.formatRawTemporalValue({value:O2,metadata:{kind:"raw_temporal",valueKind:"wall_datetime"},format:$t.resolveRawTemporalFormat({preferences:{...m,dateTime:{...m.dateTime,timeStyle:I}},calendar:{tz:"UTC"}})}).text),S=(I,E)=>{const D={...e.dateTime,[I]:E==="inherit"?void 0:E};r({...e,dateTime:D.dateStyle===void 0&&D.timeStyle===void 0?void 0:D})};return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{htmlFor:s,className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Locale"}),l.jsxs(p.Select,{value:e.locale??"inherit",disabled:o,onValueChange:I=>r({...e,locale:I==="inherit"?void 0:I}),children:[l.jsx(p.SelectTrigger,{id:s,size:"xs",children:l.jsx(p.SelectValue,{children:e.locale===void 0?`Inherited · ${t.locale}`:j_t(e.locale)})}),l.jsxs(p.SelectContent,{children:[l.jsxs(p.SelectItem,{value:"inherit",children:["Inherited from ",QF(n.locale)," ·"," ",t.locale]}),e.locale&&!XF.some(I=>I.value===e.locale)&&l.jsx(p.SelectItem,{value:e.locale,children:e.locale}),XF.map(I=>l.jsxs(p.SelectItem,{value:I.value,children:[I.label," — ",I.value]},I.value))]})]})]}),l.jsxs("fieldset",{className:"space-y-2",children:[l.jsx("legend",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Date values"}),l.jsx(z2,{id:a,label:"Format",value:e.dateStyle,inherited:t.dateStyle,inheritedSource:n.dateStyle,examples:w,disabled:o,onValueChange:I=>r({...e,dateStyle:I==="inherit"?void 0:I})})]}),l.jsxs("fieldset",{className:"space-y-2",children:[l.jsx("legend",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Date & time values"}),l.jsx(z2,{id:c,label:"Date",value:(k=e.dateTime)==null?void 0:k.dateStyle,inherited:t.dateTime.dateStyle,inheritedSource:n.dateTime.dateStyle,examples:C,disabled:o,onValueChange:I=>S("dateStyle",I)}),l.jsx(z2,{id:u,label:"Time",value:(T=e.dateTime)==null?void 0:T.timeStyle,inherited:t.dateTime.timeStyle,inheritedSource:n.dateTime.timeStyle,examples:N,disabled:o,onValueChange:I=>S("timeStyle",I)})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx(p.Label,{htmlFor:i,className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default currency"}),l.jsxs(p.Select,{value:e.defaultCurrency??"inherit",disabled:o,onValueChange:I=>r({...e,defaultCurrency:I==="inherit"?void 0:I}),children:[l.jsx(p.SelectTrigger,{id:i,size:"xs",children:l.jsx(p.SelectValue,{children:e.defaultCurrency===void 0?`Inherited · ${t.defaultCurrency}`:e.defaultCurrency})}),l.jsxs(p.SelectContent,{children:[l.jsxs(p.SelectItem,{value:"inherit",children:["Inherited from ",QF(n.defaultCurrency)," ·"," ",t.defaultCurrency]}),[...dxe].map(I=>l.jsx(p.SelectItem,{value:I,children:I},I)),N_t.map(I=>l.jsx(p.SelectItem,{value:I,children:I},I))]})]})]}),l.jsxs("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2",children:[l.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Preview"}),l.jsxs("dl",{className:"mt-1.5 space-y-1 text-[12px]",children:[l.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Date"}),l.jsx("dd",{className:"text-right font-medium text-foreground",children:x})]}),l.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Date & time"}),l.jsx("dd",{className:"text-right font-medium text-foreground",children:y})]}),l.jsxs("div",{className:"flex items-baseline justify-between gap-4",children:[l.jsx("dt",{className:"text-muted-foreground",children:"Currency"}),l.jsx("dd",{className:"text-right font-medium text-foreground",children:g})]})]})]}),l.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Currency values are not converted. Date examples use a fixed reference value and the Gregorian calendar."})]})}const JF=new Set;function hxe(e){return JF.add(e),()=>{JF.delete(e)}}function K4(){JF.forEach(e=>{e()})}var __t=Object.defineProperty,I_t=(e,t,n)=>t in e?__t(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,l1=(e,t,n)=>I_t(e,typeof t!="symbol"?t+"":t,n);const T_t={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},E_t={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}},D_t={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function M_t(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function mxe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const R_t={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const o=mxe(t);if(typeof n<"u"&&o in n.container)return n.container[o]})();return typeof r=="function"?r.bind(n):void 0}},A_t={stringify:e=>`${e}`,parse:e=>parseFloat(e)},P_t={stringify:e=>e,parse:e=>e},B2={string:P_t,number:A_t,boolean:T_t,function:E_t,method:R_t,json:D_t},Zx=Symbol.for("r2wc.render"),c1=Symbol.for("r2wc.connected"),qf=Symbol.for("r2wc.context"),Ii=Symbol.for("r2wc.props");function F_t(e,t,n){var r,o,s;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),c={},u={},d={},f={};for(const m of i){c[m]=Array.isArray(t.props)?"string":t.props[m];const g=M_t(m);d[m]=g,f[g]=m}for(const m of a)u[m]=Array.isArray(t.events)?{}:t.events[m];class h extends HTMLElement{constructor(){super(),l1(this,s,!0),l1(this,o),l1(this,r,{}),l1(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Ii].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=c[g],w=y?B2[y]:null;if(y==="method"){const C=mxe(b);Object.defineProperty(this[Ii].container,C,{enumerable:!0,configurable:!0,get(){return this[Ii][C]},set(N){this[Ii][C]=N,this[Zx]()}}),this[Ii][g]=w.parse(x,b,this)}w!=null&&w.parse&&x&&(this[Ii][g]=w.parse(x,b,this))}for(const g of a)this[Ii][g]=b=>{const x=g.replace(/^on/,"").toLowerCase();this.dispatchEvent(new CustomEvent(x,{detail:b,...u[g]}))}}static get observedAttributes(){return Object.keys(f)}connectedCallback(){this[c1]=!0,this[Zx]()}disconnectedCallback(){this[c1]=!1,this[qf]&&n.unmount(this[qf]),delete this[qf]}attributeChangedCallback(g,b,x){const y=f[g],w=c[y],C=w?B2[w]:null;y in c&&C!=null&&C.parse&&x&&(this[Ii][y]=C.parse(x,g,this),this[Zx]())}[(s=c1,o=qf,r=Ii,Zx)](){this[c1]&&(this[qf]?n.update(this[qf],this[Ii]):this[qf]=n.mount(this.container,e,this[Ii]))}}for(const m of i){const g=d[m],b=c[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Ii][m]},set(x){this[Ii][m]=x;const y=b?B2[b]:null;if(y!=null&&y.stringify){const w=y.stringify(x,g,this);this.getAttribute(g)!==w&&this.setAttribute(g,w)}else this[Zx]()}})}return h}function O_t(e,t,n){const r=zxe.createRoot(e),o=v.createElement(t,n);return r.render(o),{root:r,ReactComponent:t}}function L_t({root:e,ReactComponent:t},n){const r=v.createElement(t,n);e.render(r)}function $_t({root:e}){e.unmount()}function z_t(e,t={}){return F_t(e,t,{mount:O_t,update:L_t,unmount:$_t})}const B_t={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",interactionExecutionSnapshot:"json",presentationExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},V_t=z_t(uxe,{props:B_t}),H_t=v.memo(function({context:t="editor"}={}){return l.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",l.jsx(a4,{context:t})," "]})});var pxe="Toggle",gxe=te.forwardRef((e,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:o,...s}=e,[i,a]=p.useControllableState({prop:n,onChange:o,defaultProp:r??!1,caller:pxe});return l.jsx(p.Primitive.button,{type:"button","aria-pressed":i,"data-state":i?"on":"off","data-disabled":e.disabled?"":void 0,...s,ref:t,onClick:p.composeEventHandlers(e.onClick,()=>{e.disabled||a(!i)})})});gxe.displayName=pxe;var bxe=gxe;const q_t=p.cva("inline-flex items-center justify-center rounded-control text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground"},size:{default:"h-10 px-3",sm:"h-9 px-2.5",lg:"h-11 px-5"}},defaultVariants:{variant:"default",size:"default"}}),xxe=te.forwardRef(({className:e,variant:t,size:n,...r},o)=>l.jsx(bxe,{ref:o,className:p.cn(q_t({variant:t,size:n,className:e})),...r}));xxe.displayName=bxe.displayName;function G4(){var c,u;const e=p.useEditorStore(d=>d.card),t=p.useEditorStore(d=>d.frame),n=v.useMemo(()=>it.findCustomVisualConfigCard(t,e),[t,e]),{manifest:r}=Nf(((c=n==null?void 0:n.customCardPreferences)==null?void 0:c.url)||""),o=v.useMemo(()=>{var d;return(d=r==null?void 0:r.visuals)==null?void 0:d.find(f=>{var h;return f.name===((h=n==null?void 0:n.customCardPreferences)==null?void 0:h.componentName)})},[r,(u=n==null?void 0:n.customCardPreferences)==null?void 0:u.componentName]),s=it.resolveMultiInputType(n,o),i=v.useMemo(()=>it.getCustomVisualInputCards({frame:t,configCard:n,isMultiInputVisual:s==="multiple"}),[t,n,s]),a=v.useMemo(()=>{const d=i.findIndex(f=>(f==null?void 0:f.id)===e.id);return d<0?-1:it.getSlotIndexForCard(e,d)},[i,e]);return v.useMemo(()=>!n||s!=="multiple"||a<0?e.type:it.getEffectiveCardTypeForSlot(e,a,o==null?void 0:o.slots)??e.type,[n,s,a,e,o==null?void 0:o.slots])}function yxe({storeValue:e,defaultValue:t="",onStoreUpdate:n,delay:r=300}){const[o,s]=v.useState(e??t),i=v.useRef(null),a=v.useRef(o),c=v.useRef(e),u=v.useRef(!1),d=v.useCallback(()=>{i.current&&(clearTimeout(i.current),i.current=null),u.current&&a.current!==(c.current??t)&&(n(a.current),c.current=a.current)},[t,n]);v.useEffect(()=>{if(e!==c.current){i.current&&(clearTimeout(i.current),i.current=null);const h=e??t;s(h),a.current=h,c.current=e,u.current=!1}},[e,t]),v.useEffect(()=>{if(u.current)return i.current=setTimeout(()=>{d()},r),()=>{i.current&&(clearTimeout(i.current),i.current=null)}},[r,d,o]),v.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]);const f=v.useCallback(h=>{const m=h??t;u.current=!0,a.current=m,s(m)},[t]);return{value:o,onChange:f,flush:d}}const U_t=300;function W_t({onExpand:e},t){const n=p.useEditorStore(C=>C.card.sql),r=p.useEditorStore(C=>C.sqlGen),o=p.useEditorStore(C=>C.card),s=G4(),{setCardSql:i,setSqlGen:a,setRunSql:c}=p.useEditorActions(),u=v.useMemo(()=>s!==o.type?{...o,type:s}:o,[o,s]),{queryKey:d}=pb(u),f=Wr(),h=v.useRef(d);h.current=d;const m=v.useRef(r);m.current=r;const g=v.useCallback(C=>{i(C)},[i]),{value:b,onChange:x,flush:y}=yxe({storeValue:n,defaultValue:"",onStoreUpdate:g,delay:U_t});v.useEffect(()=>hxe(y),[y]);function w(C){x(C),p.isObjectEmpty(m.current)||a({})}return l.jsxs("div",{className:"relative h-full w-full",children:[l.jsx(p.CodeEditor,{ref:t,value:b??"",onValueChange:w,language:"sql-jinja",embedded:!0,hideLineNumbers:!0,wrapLines:!0,placeholder:"Write your SQL here",onKeyDown:C=>{C.key==="Enter"&&C.shiftKey&&(C.preventDefault(),K4(),setTimeout(()=>{f.removeQueries({queryKey:h.current,exact:!0}),c(!0)},0))}}),e?l.jsx(p.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-2.5 top-2 z-20 h-7 w-7 bg-background/80 p-0 text-muted-foreground backdrop-blur-sm transition-colors hover:bg-accent hover:text-foreground focus-visible:text-foreground",onClick:e,"aria-label":"Expand SQL editor",title:"Expand SQL editor",children:l.jsx(Ft.Maximize2,{className:"h-3.5 w-3.5",strokeWidth:1.75})}):null]})}const K_t=v.forwardRef(W_t),G_t=300;function Y_t(e,t){const n=p.useEditorStore(g=>g.card.python),r=p.useEditorStore(g=>g.card),o=G4(),{setCardPython:s,setRunSql:i}=p.useEditorActions(),a=v.useMemo(()=>o!==r.type?{...r,type:o}:r,[r,o]),{queryKey:c}=pb(a),u=Wr(),d=v.useRef(c);d.current=c;const{value:f,onChange:h,flush:m}=yxe({storeValue:n,defaultValue:it.PYTHON_DEFAULT_CODE,onStoreUpdate:s,delay:G_t});return v.useEffect(()=>hxe(m),[m]),l.jsx(p.CodeEditor,{ref:t,value:f??"",onValueChange:h,language:"python",embedded:!0,hideLineNumbers:!0,wrapLines:!0,className:"[&_.code-editor-pre]:!pt-2 [&_.code-editor-textarea]:!pt-2",onKeyDown:g=>{g.key==="Enter"&&g.shiftKey&&(g.preventDefault(),K4(),setTimeout(()=>{u.removeQueries({queryKey:d.current,exact:!0}),i(!0)},0))}})}const Z_t=v.forwardRef(Y_t),vxe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),X_t=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),Q_t=Array.from(vxe).join(", "),J_t=3,eIt="Self-heal",tIt=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function nIt({card:e}){var W,P,G,Z,X;const t=fl(),[n,r]=v.useState({}),{authToken:o}=It(),s=p.getTokenParams(o==null?void 0:o.accessToken),{compiledAppearance:i}=p.useAppearance(),a=v.useMemo(()=>Aw(i),[i]),c=p.useEditorStore(Y=>Y.frame),u=p.useEditorStore(Y=>Y.inlineFilterValuesMap[e.id]),d=p.useEditorStore(Y=>Y.actions.setCardInlineFilterValue),f=p.useEditorStore(Y=>Y.actions.removeCardInlineFilterValue),h=e,{getCard:m,manifest:g}=Nf(((W=h.customCardPreferences)==null?void 0:W.url)||""),b=(P=g==null?void 0:g.visuals)==null?void 0:P.find(Y=>{var O;return Y.name===((O=h.customCardPreferences)==null?void 0:O.componentName)}),x=it.resolveMultiInputType(h,b)??"single",y=v.useMemo(()=>it.getCustomVisualInputCards({frame:c,configCard:h,isMultiInputVisual:x==="multiple"}),[c,h,x]),w=v.useMemo(()=>{const Y=y.findIndex(O=>(O==null?void 0:O.id)===e.id);return Y<0?-1:it.getSlotIndexForCard(e,Y)},[y,e]),C=v.useMemo(()=>x!=="multiple"||w<0?e.type:it.getEffectiveCardTypeForSlot(e,w,b==null?void 0:b.slots)??e.type,[x,w,e,b==null?void 0:b.slots]),N=v.useMemo(()=>x==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:C!==e.type?{...e,type:C}:e,[e,C,x]),{data:S,effectiveCardConfig:j}=pb(N),_=p.useInteractionStore(Y=>Y.interactionStates),k=p.useDashboardStore(Y=>{var O;return(O=Y.dashboard)==null?void 0:O.id}),T=p.useDashboardStore(Y=>Y.dashboard.filters),I=p.useDashboardStore(Y=>Y.filterValues),E=p.useDashboardStore(Y=>Y.selectedSheetId),D=v.useMemo(()=>F$({card:e,sheetId:E||"",inlineFilterValues:u,setInlineFilterValue:Y=>d(e.id,Y),removeInlineFilterValue:Y=>f(e.id,Y)}),[e,E,u,d,f]),{cardFilters:R,cardFilterValues:A}=v.useMemo(()=>Qv({card:e,interactionStates:_,currentDashboardId:k,filters:T,filterValues:I,selectedSheetId:E}),[e,_,k,T,I,E]),F=v.useCallback((Y,O)=>{const q=it.normalizeMultiInputPayload(O);r(U=>({...U,[Y]:q}))},[]),z=(G=h.customCardPreferences)==null?void 0:G.componentName,L=z?m(z):null,$=Rj((Z=h.customCardPreferences)==null?void 0:Z.settings,h),H=v.useMemo(()=>it.buildSlotOrderedCards(y),[y]),M=v.useMemo(()=>H.map((Y,O)=>it.getEffectiveCardTypeForSlot(Y,O,b==null?void 0:b.slots)),[H,b==null?void 0:b.slots]),B=v.useMemo(()=>$$(x==="multiple"?L$({slotOrderedCards:H,multiInputData:n,valueFormatPreferences:t}):[{card:e,cardConfig:j,columns:S==null?void 0:S.columns,columnKeyMap:S==null?void 0:S.columnKeyMap,valueFormatPreferences:t}]),[e,S==null?void 0:S.columnKeyMap,S==null?void 0:S.columns,j,n,H,x,t]);return z?l.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:l.jsxs(v.Suspense,{fallback:l.jsx(l.Fragment,{}),children:[L&&x==="single"&&l.jsx(L,{editing:!0,params:s,theme:a,settings:$,cardMetadata:oue({card:e,dataMetadata:S==null?void 0:S.metadata}),onDataChange:F,data:(S==null?void 0:S.records)||[],columns:(S==null?void 0:S.columns)||[],formatTemporalBucketValue:B,filters:R,filterValues:[...A||[],...u||[]],inlineFilters:D}),L&&x==="multiple"&&l.jsxs(l.Fragment,{children:[y.map((Y,O)=>{if(!Y)return null;const q=it.getSlotIndexForCard(Y,O),U=it.getEffectiveCardTypeForSlot(Y,q,b==null?void 0:b.slots);return l.jsx(a$,{onDataChange:F,card:Y,effectiveCardType:U},`${Y.id}-${q}`)}),l.jsx("div",{className:"flex flex-col gap-2",children:l.jsx(L,{editing:!0,onDataChange:F,...O$({configCard:h,slotOrderedCards:H,slotTypes:M,multiInputData:n,params:s,theme:a,chartSettings:$,filters:R,filterValues:[...A||[],...u||[]],inlineFilters:D,formatTemporalBucketValue:B})})})]})]},(X=h.customCardPreferences)==null?void 0:X.componentName)}):null}const rIt=v.memo(nIt),oIt=p.create()(p.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(o=>o.type===n&&o.id===r),toggleStar:n=>{e(r=>{const o=r.starredCharts.findIndex(s=>s.type===n.type&&s.id===n.id);return o>=0?{starredCharts:r.starredCharts.filter((s,i)=>i!==o)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(o=>o.type===n&&o.id===r)}),{name:"semaphor-starred-charts"}));var wxe=["PageUp","PageDown"],Cxe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Sxe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},ax="Slider",[eO,sIt,iIt]=p.createCollection(ax),[Nxe]=p.createContextScope(ax,[iIt]),[aIt,LT]=Nxe(ax),jxe=te.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:s=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:c=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:m=!1,form:g,...b}=e,x=te.useRef(new Set),y=te.useRef(0),C=i==="horizontal"?lIt:cIt,[N=[],S]=p.useControllableState({prop:d,defaultProp:u,onChange:E=>{var R;(R=[...x.current][y.current])==null||R.focus(),f(E)}}),j=te.useRef(N);function _(E){const D=mIt(N,E);I(E,D)}function k(E){I(E,y.current)}function T(){const E=j.current[y.current];N[y.current]!==E&&h(N)}function I(E,D,{commit:R}={commit:!1}){const A=xIt(s),F=yIt(Math.round((E-r)/s)*s+r,A),z=p.clamp(F,[r,o]);S((L=[])=>{const $=fIt(L,z,D);if(bIt($,c*s)){y.current=$.indexOf(z);const H=String($)!==String(L);return H&&R&&h($),H?$:L}else return L})}return l.jsx(aIt,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:y,thumbs:x.current,values:N,orientation:i,form:g,children:l.jsx(eO.Provider,{scope:e.__scopeSlider,children:l.jsx(eO.Slot,{scope:e.__scopeSlider,children:l.jsx(C,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:p.composeEventHandlers(b.onPointerDown,()=>{a||(j.current=N)}),min:r,max:o,inverted:m,onSlideStart:a?void 0:_,onSlideMove:a?void 0:k,onSlideEnd:a?void 0:T,onHomeKeyDown:()=>!a&&I(r,0,{commit:!0}),onEndKeyDown:()=>!a&&I(o,N.length-1,{commit:!0}),onStepKeyDown:({event:E,direction:D})=>{if(!a){const F=wxe.includes(E.key)||E.shiftKey&&Cxe.includes(E.key)?10:1,z=y.current,L=N[z],$=s*F*D;I(L+$,z,{commit:!0})}}})})})})});jxe.displayName=ax;var[kxe,_xe]=Nxe(ax,{startEdge:"left",endEdge:"right",size:"width",direction:1}),lIt=te.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:s,onSlideStart:i,onSlideMove:a,onSlideEnd:c,onStepKeyDown:u,...d}=e,[f,h]=te.useState(null),m=p.useComposedRefs(t,C=>h(C)),g=te.useRef(void 0),b=p.useDirection(o),x=b==="ltr",y=x&&!s||!x&&s;function w(C){const N=g.current||f.getBoundingClientRect(),S=[0,N.width],_=Y4(S,y?[n,r]:[r,n]);return g.current=N,_(C-N.left)}return l.jsx(kxe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:l.jsx(Ixe,{dir:b,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const N=w(C.clientX);i==null||i(N)},onSlideMove:C=>{const N=w(C.clientX);a==null||a(N)},onSlideEnd:()=>{g.current=void 0,c==null||c()},onStepKeyDown:C=>{const S=Sxe[y?"from-left":"from-right"].includes(C.key);u==null||u({event:C,direction:S?-1:1})}})})}),cIt=te.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:s,onSlideMove:i,onSlideEnd:a,onStepKeyDown:c,...u}=e,d=te.useRef(null),f=p.useComposedRefs(t,d),h=te.useRef(void 0),m=!o;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],C=Y4(y,m?[r,n]:[n,r]);return h.current=x,C(b-x.top)}return l.jsx(kxe,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:l.jsx(Ixe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);s==null||s(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=Sxe[m?"from-bottom":"from-top"].includes(b.key);c==null||c({event:b,direction:y?-1:1})}})})}),Ixe=te.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:s,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:c,...u}=e,d=LT(ax,n);return l.jsx(p.Primitive.span,{...u,ref:t,onKeyDown:p.composeEventHandlers(e.onKeyDown,f=>{f.key==="Home"?(i(f),f.preventDefault()):f.key==="End"?(a(f),f.preventDefault()):wxe.concat(Cxe).includes(f.key)&&(c(f),f.preventDefault())}),onPointerDown:p.composeEventHandlers(e.onPointerDown,f=>{const h=f.target;h.setPointerCapture(f.pointerId),f.preventDefault(),d.thumbs.has(h)?h.focus():r(f)}),onPointerMove:p.composeEventHandlers(e.onPointerMove,f=>{f.target.hasPointerCapture(f.pointerId)&&o(f)}),onPointerUp:p.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),s(f))})})}),Txe="SliderTrack",Exe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=LT(Txe,n);return l.jsx(p.Primitive.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:t})});Exe.displayName=Txe;var tO="SliderRange",Dxe=te.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=LT(tO,n),s=_xe(tO,n),i=te.useRef(null),a=p.useComposedRefs(t,i),c=o.values.length,u=o.values.map(h=>Axe(h,o.min,o.max)),d=c>1?Math.min(...u):0,f=100-Math.max(...u);return l.jsx(p.Primitive.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...e.style,[s.startEdge]:d+"%",[s.endEdge]:f+"%"}})});Dxe.displayName=tO;var nO="SliderThumb",Mxe=te.forwardRef((e,t)=>{const n=sIt(e.__scopeSlider),[r,o]=te.useState(null),s=p.useComposedRefs(t,a=>o(a)),i=te.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return l.jsx(uIt,{...e,ref:s,index:i})}),uIt=te.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:o,...s}=e,i=LT(nO,n),a=_xe(nO,n),[c,u]=te.useState(null),d=p.useComposedRefs(t,w=>u(w)),f=c?i.form||!!c.closest("form"):!0,h=p.useSize(c),m=i.values[r],g=m===void 0?0:Axe(m,i.min,i.max),b=hIt(r,i.values.length),x=h==null?void 0:h[a.size],y=x?pIt(x,g,a.direction):0;return te.useEffect(()=>{if(c)return i.thumbs.add(c),()=>{i.thumbs.delete(c)}},[c,i.thumbs]),l.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[l.jsx(eO.ItemSlot,{scope:e.__scopeSlider,children:l.jsx(p.Primitive.span,{role:"slider","aria-label":e["aria-label"]||b,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...s,ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:p.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&l.jsx(Rxe,{name:o??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});Mxe.displayName=nO;var dIt="RadioBubbleInput",Rxe=te.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const o=te.useRef(null),s=p.useComposedRefs(o,r),i=p.usePrevious(t);return te.useEffect(()=>{const a=o.current;if(!a)return;const c=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(c,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),l.jsx(p.Primitive.input,{style:{display:"none"},...n,ref:s,defaultValue:t})});Rxe.displayName=dIt;function fIt(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,s)=>o-s)}function Axe(e,t,n){const s=100/(n-t)*(e-t);return p.clamp(s,[0,100])}function hIt(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function mIt(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function pIt(e,t,n){const r=e/2,s=Y4([0,50],[0,r]);return(r-s(t)*n)*n}function gIt(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function bIt(e,t){if(t>0){const n=gIt(e);return Math.min(...n)>=t}return!0}function Y4(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function xIt(e){return(String(e).split(".")[1]||"").length}function yIt(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var Pxe=jxe,vIt=Exe,wIt=Dxe,CIt=Mxe;const Fxe=te.forwardRef(({className:e,...t},n)=>l.jsxs(Pxe,{ref:n,className:p.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[l.jsx(vIt,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:l.jsx(wIt,{className:"absolute h-full bg-primary"})}),l.jsx(CIt,{className:"block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"})]}));Fxe.displayName=Pxe.displayName;exports.Accordion=Jz;exports.AccordionContent=mv;exports.AccordionItem=fv;exports.AccordionTrigger=hv;exports.AddDataPicker=B4;exports.AggregateTable=hI;exports.Alert=rL;exports.AlertDescription=oL;exports.AlertDialog=ff;exports.AlertDialogAction=Du;exports.AlertDialogCancel=Mu;exports.AlertDialogContent=ku;exports.AlertDialogDescription=Eu;exports.AlertDialogFooter=Iu;exports.AlertDialogHeader=_u;exports.AlertDialogTitle=Tu;exports.AlertDialogTrigger=JSe;exports.AlertTitle=mte;exports.ArrowDown=es;exports.ArrowDownIcon=dQe;exports.ArrowLeft=zv;exports.ArrowRight=Bv;exports.ArrowUp=bs;exports.ArrowUpIcon=hQe;exports.AssistantContextEntityControls=YF;exports.AssistantVirtualizedMessages=nxe;exports.AxisConfigurator=Wm;exports.BackgroundRunPill=kct;exports.Badge=mi;exports.Bell=h1;exports.BookType=oZ;exports.BriefingAuthor=Pfe;exports.BriefingAuthorDialog=Ffe;exports.BriefingUiCapabilitiesBoundary=Gct;exports.BriefingUiCapabilitiesProvider=JI;exports.BriefingsApiError=Uw;exports.BulletChartIcon=Gbe;exports.CSS=Ki;exports.CalculatedFieldEditor=fme;exports.Calculator=iZ;exports.Calendar=za;exports.CalendarClock=SO;exports.Card=hN;exports.CardContent=CO;exports.CardHeader=wO;exports.CardSummary=tF;exports.CardTitle=cb;exports.ChartArea=fR;exports.ChartColumnIncreasing=lZ;exports.ChartColumnStacked=cZ;exports.ChartJsVisual=Tw;exports.ChartLine=uZ;exports.ChartNoAxesGantt=fZ;exports.ChartPie=hZ;exports.ChartScatter=mZ;exports.ChatInputWithContext=V4;exports.Checkbox=Tn;exports.ChevronLeft=Mm;exports.ChevronsUpDown=bZ;exports.Circle=NO;exports.CircleAlert=Ca;exports.CircleCheck=xZ;exports.CircleHelp=yZ;exports.Clock=vZ;exports.CodeHighlighter=Fd;exports.CodeXml=m1;exports.Collapsible=vu;exports.CollapsibleContent=Cu;exports.CollapsibleTrigger=wu;exports.ColorField=da;exports.Command=cT;exports.CommandEmpty=dT;exports.CommandGroup=fT;exports.CommandInput=Bz;exports.CommandItem=hT;exports.CommandList=uT;exports.CommandSeparator=Dhe;exports.ComparisonMetadataBadge=Foe;exports.Container=JO;exports.ControlDefaultValueEditor=Pme;exports.ControlDefinitionOptionsEditor=Ame;exports.ControlIdInput=Eme;exports.ControlVisibilitySettings=fgt;exports.Copy=Jh;exports.CopyButton=Pd;exports.CopyPlus=mR;exports.Cross2Icon=bQe;exports.CustomFilterPopover=A$;exports.CustomScrollArea=hl;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=Are;exports.Dashboard=uxe;exports.DashboardCard=zfe;exports.DashboardCreateDialogBase=hQ;exports.DashboardExportDialog=rxe;exports.DashboardPlus=C_t;exports.DashboardWC=V_t;exports.DataTableConditionalFormattingSettings=Npe;exports.DataTablePagination=rI;exports.Database=ss;exports.DateRangePicker=E$;exports.DefaultChatTransport=M4;exports.Dialog=Mo;exports.DialogContent=go;exports.DialogDescription=Ro;exports.DialogFooter=tl;exports.DialogHeader=Is;exports.DialogTitle=bo;exports.DialogTrigger=uQ;exports.DisplayFormatPreferencesFields=k_t;exports.DisplayPreferencesProvider=HI;exports.DndContext=nC;exports.Donut=wZ;exports.Download=Su;exports.DownloadPdf=oxe;exports.DragOverlay=bhe;exports.DropdownMenu=Uo;exports.DropdownMenuCheckboxItem=nd;exports.DropdownMenuContent=Do;exports.DropdownMenuItem=kn;exports.DropdownMenuLabel=qa;exports.DropdownMenuRadioGroup=iCe;exports.DropdownMenuRadioItem=FX;exports.DropdownMenuSeparator=Sa;exports.DropdownMenuSub=qO;exports.DropdownMenuSubContent=$k;exports.DropdownMenuSubTrigger=Lk;exports.DropdownMenuTrigger=Wo;exports.EMPTY_DATA_SOURCE=sb;exports.Editable=Pj;exports.EditableText=xi;exports.EditorCustomVisual=rIt;exports.Ellipsis=Ci;exports.EllipsisVertical=Rm;exports.ErrorBoundary=Si;exports.ExportError=kb;exports.ExternalLink=Ld;exports.EyeOff=Ak;exports.Fallback=BI;exports.FallbackVisual=Vw;exports.FeedbackCategory=lf;exports.FeedbackDialog=jv;exports.FieldsList=a4;exports.FieldsSection=H_t;exports.FileCode=CZ;exports.FileText=Qs;exports.Filter=$d;exports.FilterComponent=FI;exports.FilterInfo=XP;exports.FilterableFieldsPanel=mme;exports.Grid3x3=pR;exports.GripVertical=Nu;exports.HEATMAP_PRESET_PALETTES=_A;exports.Hash=ub;exports.House=SZ;exports.HoverCard=Xm;exports.HoverCardContent=bu;exports.HoverCardTrigger=Yd;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=vxe;exports.INLINE_ALLOWED_TOOL_LIST=Q_t;exports.INLINE_BLOCKED_MUTATING_TOOLS=X_t;exports.IconButton=nu;exports.IconForFieldType=Q1;exports.Inbox=kO;exports.InfoHover=J$;exports.InlineFilterBar=Rue;exports.KPICard=tf;exports.KeyboardSensor=eC;exports.Layers=Pm;exports.Link=_O;exports.LoadingDots=xu;exports.MAX_SELF_HEAL_ATTEMPTS=J_t;exports.Map=_Z;exports.Markdown=Sz;exports.MatrixTableVisual=fI;exports.MdStackedLineChart=Wbe;exports.MultiInputEmptyRenderer=a$;exports.PanelResizeHandle=ET;exports.Pause=IZ;exports.PenLine=xR;exports.Pencil=yR;exports.PendingMessagesDisplay=Fbe;exports.PersistedDynamicVisual=VI;exports.PiChartPolar=Vbe;exports.Pin=EZ;exports.PinOff=TZ;exports.PivotTableTanstack=Wb;exports.Placeholders=Xpe;exports.Play=DZ;exports.Plus=Tr;exports.PointerSensor=Jb;exports.Progress=L4;exports.PythonEditor=Z_t;exports.RECOVERABLE_SQL_ERROR_CODES=tIt;exports.Radar=MZ;exports.RadioGroup=rl;exports.RadioGroupItem=vs;exports.RefreshCw=tc;exports.ResizableHandle=k0t;exports.ResizablePanel=OF;exports.ResizablePanelGroup=Zpe;exports.ResourceEditDialog=HQ;exports.ResourceType=lo;exports.Rows3=RZ;exports.RunCompletionBanner=_ct;exports.SELF_HEAL_TIMELINE_STEP=eIt;exports.SeedQuestions=wbe;exports.SemaphorContext=Av;exports.SemaphorContextProvider=uO;exports.SemaphorQueryClient=kY;exports.SemaphorReadyIndicator=W4;exports.SemaphorStyleWrapper=Kb;exports.Send=TO;exports.SendHorizontal=AZ;exports.Settings=EO;exports.Settings2=Fm;exports.Share2=PZ;exports.ShareDialog=VQ;exports.Sheet=a3;exports.SheetContent=oI;exports.SheetDescription=iI;exports.SheetHeader=koe;exports.SheetTitle=sI;exports.SheetTrigger=Wze;exports.Slider=Fxe;exports.SortableContext=rC;exports.Sparkles=p0;exports.SqlEditor=K_t;exports.Square=MO;exports.SquarePen=DO;exports.Star=FZ;exports.StructuralParticipantSelector=Dme;exports.SummaryCard=GP;exports.TABLE_PRESENTATION_DEFAULT_STYLE=Rd;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=ha;exports.TableBody=Gd;exports.TableCell=qn;exports.TableColumnVisibilitySettings=fpe;exports.TableHead=mo;exports.TableHeader=Zm;exports.TablePresentationSettings=mpe;exports.TableRow=Ar;exports.TableSkeleton=tz;exports.TableVisual=Zd;exports.Tag=OZ;exports.TbChartBubble=Hbe;exports.TbChartFunnel=qbe;exports.TbChartTreemap=Ube;exports.TextCard=Xg;exports.Textarea=zm;exports.TiSortNumerically=Kbe;exports.Toggle=xxe;exports.Tornado=LZ;exports.Trash2=el;exports.TriangleAlert=Zs;exports.TypeGlyph=Yw;exports.UXProvider=U4;exports.Undo2=$Z;exports.User=AO;exports.Users=Pk;exports.UsersRound=PO;exports.VisualErrorState=yue;exports.Zap=vR;exports.applyBriefingFormPatch=rv;exports.areContextEntitiesEqual=ar;exports.areEntitiesJoined=Lre;exports.arrayMove=ex;exports.briefingFormDraftToCreateRequest=rF;exports.briefingFormDraftToUpdateRequest=pde;exports.briefingToFormDraft=Qp;exports.briefingTone=_r;exports.buildCardControlUsageById=mgt;exports.buildCustomCardTheme=Aw;exports.buildDashboardControlUsageById=hgt;exports.buildDashboardSheetsInputExecutionSnapshot=vO;exports.buildDashboardStructuralParticipantIdsByControlId=Lme;exports.buildFilterFieldMeta=Kz;exports.buildFilterSemanticContext=Gz;exports.buildInlineFilterNodes=F$;exports.buildMultiInputCustomVisualProps=O$;exports.buildMultiInputTemporalPresentationInputs=L$;exports.calculateCardFilterValues=S5;exports.calculateContextAwareFilters=Qv;exports.calculateFieldState=GL;exports.canUserAccessVisuals=sNe;exports.canUserCreateDashboards=WQ;exports.canUserEdit=nNe;exports.canUserManageDashboards=oNe;exports.canUserManageGroups=iNe;exports.canUserUseFilters=rNe;exports.cancelBriefingPreviewRun=rde;exports.cancelBriefingRun=sde;exports.cancelExport=r$e;exports.chartSupportsDataLabels=Dne;exports.chartSupportsLegend=Tne;exports.chartTypes=OT;exports.cleanupKpiMetricComparisonMode=zhe;exports.cloneDeep=Ks;exports.cloneLinkedFrameWithSourceMapping=Iet;exports.closestCenter=Jw;exports.commitSharedCalculatedFields=Jf;exports.createAssistantConversationId=Hp;exports.createAssistantRequestId=ybe;exports.createBriefing=Yue;exports.createBriefingFormDraft=nF;exports.createChartConfig=Nb;exports.createCustomVisualTemporalBucketFormatter=$$;exports.createDashboardControlInputFromControl=hyt;exports.createExport=toe;exports.createUniqueDashboardInputVariableNameFromName=Od;exports.currencyPresentationTargetKey=ba;exports.dedup=wNt;exports.dedupeContextEntities=Dz;exports.deleteBriefing=Que;exports.deleteBriefingRun=ide;exports.diagnoseCurrencyPresentationBindings=y0e;exports.doesStoredFilterMatchField=rb;exports.downloadDocumentPdf=Q5;exports.downloadPdf=Uee;exports.extractSqlParamReferences=IY;exports.extractTableMetadata=Wz;exports.fieldAlreadyExists=zre;exports.flexRender=gi;exports.flushPendingEditorDrafts=K4;exports.formatDisplayFormula=cmt;exports.formatFileSize=i$e;exports.getAutoDetectedChartIcon=Xjt;exports.getBriefing=Gue;exports.getBriefingArtifact=Ttt;exports.getBriefingEvidence=Ett;exports.getBriefingPreviewRun=nde;exports.getBriefingRun=ode;exports.getCardCurrencyPresentationFields=pO;exports.getCardCurrencyPresentationTargets=gO;exports.getChartGridStyle=eDe;exports.getChartIconByType=Qjt;exports.getColorForValue=BR;exports.getCoreRowModel=eI;exports.getDefaultAxisConfig=WR;exports.getDefaultChartColors=Um;exports.getDefaultDataLabelsConfig=dw;exports.getDefaultLegendConfig=EL;exports.getDefaultRunningTotalPartitionByFieldIds=l0;exports.getDisplayedKpiResultColumnKeys=mw;exports.getDocumentSectionEditorCard=Wpt;exports.getDocumentSheetDashboardInputs=rx;exports.getDownloadUrl=n$e;exports.getEntityIcon=Nk;exports.getErrorMessage=sbe;exports.getExportStatus=t$e;exports.getExports=e$e;exports.getExpressionFieldKind=rf;exports.getFieldExpressionAnnotation=Yz;exports.getFilterCount=zj;exports.getGranularityOptionsForFieldType=Tme;exports.getKeys=yr;exports.getMatrixVisualLoadingState=X_;exports.getMetricDisplayLabel=g3e;exports.getNewField=Ure;exports.getObjectDiff=iY;exports.getPaginationRowModel=tI;exports.getRoleBasedDisplayOverrides=UQ;exports.getRunningTotalOrderByCandidates=Mht;exports.getSelectedDateFilterColumn=Uce;exports.getSortedRowModel=Soe;exports.getTableConditionalFormattingColumnOptions=xpe;exports.getTableOutputColumnOptions=ype;exports.getTablePageSizeOptions=Jre;exports.handleAggregationChange=QP;exports.handleAggregationLabelChange=Due;exports.hasFlatTableTotalsBehavior=qm;exports.hasMatrixResultData=gw;exports.horizontalListSortingStrategy=Oz;exports.inferSemanticDomainIdFromSelectedEntities=Sk;exports.isActiveBriefingRunStatus=Wj;exports.isCardSummaryVisibleOnCard=z$;exports.isCurrencyPresentationControl=b0e;exports.isDefaultColor=xTe;exports.isEligibleFlatTableTotalsCard=rw;exports.isExportComplete=s$e;exports.isExportInProgress=o$e;exports.isInAiScopeArray=vNt;exports.isManagedCalculatedExpressionField=Qa;exports.isMetricTransformEnabled=Eht;exports.isPresentationCurrencyBinding=Ov;exports.isPromiseLike=GF;exports.isSqlBackedKpi=Wre;exports.isStructuralControlBinding=g0e;exports.isSubtotalEnabledAggregateTable=Uz;exports.isSupportedDocumentTableCardType=Kpt;exports.isTableType=zEe;exports.isTerminalBriefingRunStatus=Uj;exports.lastAssistantMessageIsCompleteWithToolCalls=tbe;exports.listBriefingRuns=Itt;exports.listBriefingTenantSummaries=_tt;exports.listBriefings=ktt;exports.merge=Jl;exports.mergeAxisConfig=KR;exports.normalizeConditionalFormatting=A5;exports.normalizeContextFormatMode=yee;exports.normalizeDashboardInputVariableName=Lv;exports.pauseBriefing=Zue;exports.pivotData=sw;exports.polishBriefingText=ade;exports.prepareFeedbackData=FT;exports.previewBriefingPlan=ede;exports.remarkGfm=_z;exports.removeFromScopeArray=CNt;exports.requiresDashboardInputResolution=uf;exports.resolveCurrencyPresentationTargetFormat=See;exports.resolveDashboardBriefingsVisibility=Ofe;exports.resolveDashboardControlsVisibility=uNe;exports.resolveDashboardInputContext=Yi;exports.resolveDashboardTitleEditability=cNe;exports.resolveDomainCalculatedFieldForEdit=opt;exports.resolveMatrixCardMeasureInstances=Mk;exports.resolvePendingPivotTableResultState=q3e;exports.resolveTablePageSize=G_;exports.resolveTablePresentationStyle=p3;exports.resumeBriefing=Xue;exports.runBriefingNow=Jue;exports.runBriefingPreview=tde;exports.sanitizeAIScope=obe;exports.saveCalculatedFieldToCardScope=IF;exports.saveCalculatedFieldToSharedScope=hme;exports.saveCalculatedFieldToSheetScope=TF;exports.seedSemanticMetricFormatDefaults=Vhe;exports.setTableColumnVisibility=ooe;exports.setupEditorWithCard=S_;exports.showAllTableColumns=g$e;exports.showJoinRequiredNotification=$re;exports.sortByColumnsToSortState=Woe;exports.sortStateToSortByColumns=Koe;exports.sortableKeyboardCoordinates=$z;exports.supportsLiveNumericPresentation=Fv;exports.supportsMetricTransformForMetric=Bhe;exports.supportsTableConditionalFormatting=ppe;exports.toEntityArray=Xa;exports.ue=lt;exports.updateBriefing=UI;exports.useActiveExports=gNe;exports.useActiveToolStatus=Lbe;exports.useAddFrameWithFreshSemanticExecutionPayload=Q$;exports.useAddNewFrame=Kfe;exports.useAssistantContainer=ZQ;exports.useAssistantContextEntities=eT;exports.useAssistantLayoutStore=Mh;exports.useAssistantPanel=GQ;exports.useAssistantProfile=vbe;exports.useAutoSubmitQueue=Obe;exports.useBrandStudioPreview=c_t;exports.useBriefingRunPolling=sF;exports.useBriefingUiCapabilities=Lfe;exports.useCalendarContext=_3e;exports.useCard=A3e;exports.useCardNumericPresentation=Ta;exports.useCardSummary=B$;exports.useChartNumericPresentation=jb;exports.useChat=rbe;exports.useColumns=Vz;exports.useCreateVisualWithFrame=nSe;exports.useCurrentUserInfo=ti;exports.useCustomVisual=Nf;exports.useCustomVisualsQuery=R$;exports.useDashboardAppearance=Ru;exports.useDashboardById=UX;exports.useDashboardInteractionMode=Iue;exports.useDashboardPreferences=Lm;exports.useDashboardQuery=Pv;exports.useDashboardStructuralParticipants=$me;exports.useDashboardSummary=due;exports.useDataColumns=qhe;exports.useDateFilterHook=VGe;exports.useDefaultDashboardMutation=LX;exports.useDisplayPreferences=cl;exports.useDroppable=ghe;exports.useEditorAside=mT;exports.useEditorCardQuery=pb;exports.useEffectiveEditorCardType=G4;exports.useEnsureReactGlobals=ble;exports.useExportActions=XQ;exports.useExportStore=Gk;exports.useFieldManagement=Hhe;exports.useFilterableFields=Ohe;exports.useFullscreenAssistant=YQ;exports.useGroupMembers=o1e;exports.useGroups=XO;exports.useHasDashboardId=QQ;exports.useInProgressExportsCount=bNe;exports.useJoinabilityMap=qz;exports.useManagementActions=Dm;exports.useManagementStore=_s;exports.useMutation=ks;exports.usePivotTableConfig=Gm;exports.usePluginQuery=Jce;exports.useQuery=Un;exports.useQueryClient=Wr;exports.useReactTable=nI;exports.useResolveExistingFrameSemanticExecutionPayload=Met;exports.useResolvedDefaultCurrency=XL;exports.useResolvedTemporalStylePreferences=fl;exports.useResolvedValueFormatLocale=ZL;exports.useResourceManagement=WO;exports.useResourceUpdateState=WX;exports.useScopedFields=Fhe;exports.useSelectedVisual=n0e;exports.useSemaphorContext=It;exports.useSensor=nb;exports.useSensors=oT;exports.useSortable=tx;exports.useStarredChartsStore=oIt;exports.useSurfaceAppearance=dc;exports.useTableQueryState=Ooe;exports.useTextFilterHook=bUe;exports.useTheme=oO;exports.useTimezone=dl;exports.useTopoJson=hw;exports.useUnifiedUsers=Wk;exports.useUpdateResource=BX;exports.useUpdateVisualMutation=rSe;exports.useUserPreferences=mQ;exports.useVisualById=Bk;exports.useVisualManagement=tSe;exports.validateBriefingFormDraft=oF;exports.validateFieldForChartType=$he;exports.verticalListSortingStrategy=Lz;
|