react-semaphor 0.1.369 → 0.1.371
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/analytics-protocol/index.cjs +1 -1
- package/dist/analytics-protocol/index.js +40 -38
- package/dist/chunks/{calendar-preferences-dialog-6q51A6XC.js → calendar-preferences-dialog-ClBAkMmF.js} +1 -1
- package/dist/chunks/{calendar-preferences-dialog-CUGzkNcE.js → calendar-preferences-dialog-Dn6o2r2Y.js} +1 -1
- package/dist/chunks/{dashboard-briefing-launcher-BEZnvIla.js → dashboard-briefing-launcher-BO-kXtEd.js} +1 -1
- package/dist/chunks/{dashboard-briefing-launcher-ptERmNJr.js → dashboard-briefing-launcher-D3Xfc_26.js} +3 -3
- package/dist/chunks/{dashboard-controls-CqKC5oEk.js → dashboard-controls-B3sdy_Zx.js} +3 -3
- package/dist/chunks/{dashboard-controls-CGt6_hMf.js → dashboard-controls-DcXMFgGR.js} +1 -1
- package/dist/chunks/{dashboard-json-6SgPm_QW.js → dashboard-json-BWfkEy48.js} +1 -1
- package/dist/chunks/{dashboard-json-CYSbOdmE.js → dashboard-json-CFURS_OR.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-w6hKbjlw.js → edit-dashboard-visual-BD2AJLiT.js} +1 -1
- package/dist/chunks/{edit-dashboard-visual-ByQx_M2i.js → edit-dashboard-visual-DjdhKiP2.js} +3 -3
- package/dist/chunks/{index-CPyEi9gS.js → index-C0Qnfr_7.js} +5 -4
- package/dist/chunks/{index-BtqYNH_S.js → index-DlLvzmJF.js} +2 -2
- package/dist/chunks/{resource-management-panel-Bf8-3eUf.js → resource-management-panel-DytUMSGA.js} +1 -1
- package/dist/chunks/{resource-management-panel-mJ84NxzC.js → resource-management-panel-YvIfaphX.js} +2 -2
- package/dist/chunks/{use-create-flow-overlay-state-BfoXDDrd.js → use-create-flow-overlay-state-BETXykC9.js} +2 -2
- package/dist/chunks/{use-create-flow-overlay-state-c6rCm36x.js → use-create-flow-overlay-state-CwIG1Ekp.js} +1 -1
- package/dist/chunks/{use-visual-utils-NN0e3fBP.js → use-visual-utils-Bk135OgA.js} +1 -1
- package/dist/chunks/{use-visual-utils-C_c-aiqi.js → use-visual-utils-BzFjIykb.js} +1 -1
- package/dist/chunks/{validation-nOPr0mTk.js → validation-CQFpcSSP.js} +446 -246
- package/dist/chunks/validation-D4Zz6WPD.js +1 -0
- package/dist/chunks/validators-CuKnUZFO.js +2171 -0
- package/dist/chunks/validators-DHee9kM2.js +1 -0
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/dashboard-authoring/index.cjs +1 -1
- package/dist/dashboard-authoring/index.js +1 -1
- package/dist/data-app-builder/index.cjs +1 -1
- package/dist/data-app-builder/index.js +1 -1
- package/dist/data-app-sdk/index.cjs +1 -1
- package/dist/data-app-sdk/index.js +261 -183
- package/dist/data-app-sdk-validation/index.cjs +1 -1
- package/dist/data-app-sdk-validation/index.js +4 -3
- package/dist/index.cjs +1 -1
- package/dist/index.js +5 -5
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +2 -2
- package/dist/types/analytics-protocol.d.ts +542 -2
- package/dist/types/dashboard-assistant.d.ts +508 -4
- package/dist/types/dashboard-authoring.d.ts +217 -3
- package/dist/types/dashboard.d.ts +67 -2
- package/dist/types/data-app-builder.d.ts +197 -1
- package/dist/types/data-app-sdk-validation.d.ts +520 -6
- package/dist/types/data-app-sdk.d.ts +543 -8
- package/dist/types/main.d.ts +215 -3
- package/dist/types/shared.d.ts +66 -2
- package/dist/types/surfboard.d.ts +67 -2
- package/dist/types/types.d.ts +67 -2
- package/package.json +1 -1
- package/dist/chunks/validation-Dsf7PydY.js +0 -1
- package/dist/chunks/validators-CVuWOHYv.js +0 -1032
- package/dist/chunks/validators-oc8qtP4q.js +0 -1
|
@@ -1220,7 +1220,7 @@ ${(e*100).toLocaleString()}%`}}},scales:{_index_:{display:!1,padding:10,grid:{di
|
|
|
1220
1220
|
To pick up a draggable item, press the space bar.
|
|
1221
1221
|
While dragging, use the arrow keys to move the item.
|
|
1222
1222
|
Press space again to drop the item in its new position, or press escape to cancel.
|
|
1223
|
-
`},gYe={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 bYe(e){let{announcements:t=gYe,container:n,hiddenTextDescribedById:r,screenReaderInstructions:s=pYe}=e;const{announce:o,announcement:i}=fYe(),a=pv("DndLiveRegion"),[l,u]=S.useState(!1);if(S.useEffect(()=>{u(!0)},[]),hYe(S.useMemo(()=>({onDragStart(f){let{active:h}=f;o(t.onDragStart({active:h}))},onDragMove(f){let{active:h,over:m}=f;t.onDragMove&&o(t.onDragMove({active:h,over:m}))},onDragOver(f){let{active:h,over:m}=f;o(t.onDragOver({active:h,over:m}))},onDragEnd(f){let{active:h,over:m}=f;o(t.onDragEnd({active:h,over:m}))},onDragCancel(f){let{active:h,over:m}=f;o(t.onDragCancel({active:h,over:m}))}}),[o,t])),!l)return null;const d=S.createElement(S.Fragment,null,S.createElement(uYe,{id:r,value:s.draggable}),S.createElement(dYe,{id:a,announcement:i}));return n?fr.createPortal(d,n):d}var ns;(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"})(ns||(ns={}));function nN(){}function Ep(e,t){return S.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function F_(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return S.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const ya=Object.freeze({x:0,y:0});function Loe(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function xYe(e,t){const n=tN(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 $oe(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function yYe(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function p9(e){let{left:t,top:n,height:r,width:s}=e;return[{x:t,y:n},{x:t+s,y:n},{x:t,y:n+r},{x:t+s,y:n+r}]}function zoe(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function g9(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 gv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=g9(t,t.left,t.top),o=[];for(const i of r){const{id:a}=i,l=n.get(a);if(l){const u=Loe(g9(l),s);o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort($oe)},vYe=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=p9(t),o=[];for(const i of r){const{id:a}=i,l=n.get(a);if(l){const u=p9(l),d=s.reduce((h,m,g)=>h+Loe(u[g],m),0),f=Number((d/4).toFixed(4));o.push({id:a,data:{droppableContainer:i,value:f}})}}return o.sort($oe)};function wYe(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),s=Math.min(t.left+t.width,e.left+e.width),o=Math.min(t.top+t.height,e.top+e.height),i=s-r,a=o-n;if(r<s&&n<o){const l=t.width*t.height,u=e.width*e.height,d=i*a,f=d/(l+u-d);return Number(f.toFixed(4))}return 0}const SYe=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=[];for(const o of r){const{id:i}=o,a=n.get(i);if(a){const l=wYe(a,t);l>0&&s.push({id:i,data:{droppableContainer:o,value:l}})}}return s.sort(yYe)};function CYe(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function Boe(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:ya}function NYe(e){return function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s.reduce((i,a)=>({...i,top:i.top+e*a.y,bottom:i.bottom+e*a.y,left:i.left+e*a.x,right:i.right+e*a.x}),{...n})}}const kYe=NYe(1);function Voe(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 _Ye(e,t,n){const r=Voe(t);if(!r)return e;const{scaleX:s,scaleY:o,x:i,y:a}=r,l=e.left-i-(1-s)*parseFloat(n),u=e.top-a-(1-o)*parseFloat(n.slice(n.indexOf(" ")+1)),d=s?e.width/s:e.width,f=o?e.height/o:e.height;return{width:d,height:f,top:u,right:l+d,bottom:u+f,left:l}}const jYe={ignoreTransform:!1};function _g(e,t){t===void 0&&(t=jYe);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:d}=vo(e).getComputedStyle(e);u&&(n=_Ye(n,u,d))}const{top:r,left:s,width:o,height:i,bottom:a,right:l}=n;return{top:r,left:s,width:o,height:i,bottom:a,right:l}}function b9(e){return _g(e,{ignoreTransform:!0})}function EYe(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function IYe(e,t){return t===void 0&&(t=vo(e).getComputedStyle(e)),t.position==="fixed"}function TYe(e,t){t===void 0&&(t=vo(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(s=>{const o=t[s];return typeof o=="string"?n.test(o):!1})}function P_(e,t){const n=[];function r(s){if(t!=null&&n.length>=t||!s)return n;if($5(s)&&s.scrollingElement!=null&&!n.includes(s.scrollingElement))return n.push(s.scrollingElement),n;if(!hv(s)||Foe(s)||n.includes(s))return n;const o=vo(e).getComputedStyle(s);return s!==e&&TYe(s,o)&&n.push(s),IYe(s,o)?n:r(s.parentNode)}return e?r(e):n}function Hoe(e){const[t]=P_(e,1);return t??null}function xT(e){return!M_||!e?null:Ng(e)?e:L5(e)?$5(e)||e===kg(e).scrollingElement?window:hv(e)?e:null:null}function Uoe(e){return Ng(e)?e.scrollX:e.scrollLeft}function qoe(e){return Ng(e)?e.scrollY:e.scrollTop}function hA(e){return{x:Uoe(e),y:qoe(e)}}var cs;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(cs||(cs={}));function Woe(e){return!M_||!e?!1:e===document.scrollingElement}function Yoe(e){const t={x:0,y:0},n=Woe(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},s=e.scrollTop<=t.y,o=e.scrollLeft<=t.x,i=e.scrollTop>=r.y,a=e.scrollLeft>=r.x;return{isTop:s,isLeft:o,isBottom:i,isRight:a,maxScroll:r,minScroll:t}}const DYe={x:.2,y:.2};function MYe(e,t,n,r,s){let{top:o,left:i,right:a,bottom:l}=n;r===void 0&&(r=10),s===void 0&&(s=DYe);const{isTop:u,isBottom:d,isLeft:f,isRight:h}=Yoe(e),m={x:0,y:0},g={x:0,y:0},b={height:t.height*s.y,width:t.width*s.x};return!u&&o<=t.top+b.height?(m.y=cs.Backward,g.y=r*Math.abs((t.top+b.height-o)/b.height)):!d&&l>=t.bottom-b.height&&(m.y=cs.Forward,g.y=r*Math.abs((t.bottom-b.height-l)/b.height)),!h&&a>=t.right-b.width?(m.x=cs.Forward,g.x=r*Math.abs((t.right-b.width-a)/b.width)):!f&&i<=t.left+b.width&&(m.x=cs.Backward,g.x=r*Math.abs((t.left+b.width-i)/b.width)),{direction:m,speed:g}}function AYe(e){if(e===document.scrollingElement){const{innerWidth:o,innerHeight:i}=window;return{top:0,left:0,right:o,bottom:i,width:o,height:i}}const{top:t,left:n,right:r,bottom:s}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:s,width:e.clientWidth,height:e.clientHeight}}function Goe(e){return e.reduce((t,n)=>Rm(t,hA(n)),ya)}function RYe(e){return e.reduce((t,n)=>t+Uoe(n),0)}function FYe(e){return e.reduce((t,n)=>t+qoe(n),0)}function Koe(e,t){if(t===void 0&&(t=_g),!e)return;const{top:n,left:r,bottom:s,right:o}=t(e);Hoe(e)&&(s<=0||o<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const PYe=[["x",["left","right"],RYe],["y",["top","bottom"],FYe]];class z5{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=P_(n),s=Goe(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,i,a]of PYe)for(const l of i)Object.defineProperty(this,l,{get:()=>{const u=a(r),d=s[o]-u;return this.rect[l]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Dx{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var s;(s=this.target)==null||s.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function OYe(e){const{EventTarget:t}=vo(e);return e instanceof t?e:kg(e)}function yT(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 Si;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Si||(Si={}));function x9(e){e.preventDefault()}function LYe(e){e.stopPropagation()}var yn;(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"})(yn||(yn={}));const Zoe={start:[yn.Space,yn.Enter],cancel:[yn.Esc],end:[yn.Space,yn.Enter,yn.Tab]},$Ye=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case yn.Right:return{...n,x:n.x+25};case yn.Left:return{...n,x:n.x-25};case yn.Down:return{...n,y:n.y+25};case yn.Up:return{...n,y:n.y-25}}};class bv{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 Dx(kg(n)),this.windowListeners=new Dx(vo(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Si.Resize,this.handleCancel),this.windowListeners.add(Si.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Si.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&Koe(r),n(ya)}handleKeyDown(t){if(R_(t)){const{active:n,context:r,options:s}=this.props,{keyboardCodes:o=Zoe,coordinateGetter:i=$Ye,scrollBehavior:a="smooth"}=s,{code:l}=t;if(o.end.includes(l)){this.handleEnd(t);return}if(o.cancel.includes(l)){this.handleCancel(t);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:ya;this.referenceCoordinates||(this.referenceCoordinates=d);const f=i(t,{active:n,context:r.current,currentCoordinates:d});if(f){const h=Fy(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:v,isBottom:C,maxScroll:N,minScroll:k}=Yoe(b),_=AYe(b),j={x:Math.min(x===yn.Right?_.right-_.width/2:_.right,Math.max(x===yn.Right?_.left:_.left+_.width/2,f.x)),y:Math.min(x===yn.Down?_.bottom-_.height/2:_.bottom,Math.max(x===yn.Down?_.top:_.top+_.height/2,f.y))},I=x===yn.Right&&!w||x===yn.Left&&!v,E=x===yn.Down&&!C||x===yn.Up&&!y;if(I&&j.x!==f.x){const T=b.scrollLeft+h.x,D=x===yn.Right&&T<=N.x||x===yn.Left&&T>=k.x;if(D&&!h.y){b.scrollTo({left:T,behavior:a});return}D?m.x=b.scrollLeft-T:m.x=x===yn.Right?b.scrollLeft-N.x:b.scrollLeft-k.x,m.x&&b.scrollBy({left:-m.x,behavior:a});break}else if(E&&j.y!==f.y){const T=b.scrollTop+h.y,D=x===yn.Down&&T<=N.y||x===yn.Up&&T>=k.y;if(D&&!h.x){b.scrollTo({top:T,behavior:a});return}D?m.y=b.scrollTop-T:m.y=x===yn.Down?b.scrollTop-N.y:b.scrollTop-k.y,m.y&&b.scrollBy({top:-m.y,behavior:a});break}}this.handleMove(t,Rm(Fy(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()}}bv.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=Zoe,onActivation:s}=t,{active:o}=n;const{code:i}=e.nativeEvent;if(r.start.includes(i)){const a=o.activatorNode.current;return a&&e.target!==a?!1:(e.preventDefault(),s==null||s({event:e.nativeEvent}),!0)}return!1}}];function y9(e){return!!(e&&"distance"in e)}function v9(e){return!!(e&&"delay"in e)}class B5{constructor(t,n,r){var s;r===void 0&&(r=OYe(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:o}=t,{target:i}=o;this.props=t,this.events=n,this.document=kg(i),this.documentListeners=new Dx(this.document),this.listeners=new Dx(r),this.windowListeners=new Dx(vo(i)),this.initialCoordinates=(s=tN(o))!=null?s:ya,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(Si.Resize,this.handleCancel),this.windowListeners.add(Si.DragStart,x9),this.windowListeners.add(Si.VisibilityChange,this.handleCancel),this.windowListeners.add(Si.ContextMenu,x9),this.documentListeners.add(Si.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(v9(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(y9(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:s}=this.props;s(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(Si.Click,LYe,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Si.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:s,props:o}=this,{onMove:i,options:{activationConstraint:a}}=o;if(!s)return;const l=(n=tN(t))!=null?n:ya,u=Fy(s,l);if(!r&&a){if(y9(a)){if(a.tolerance!=null&&yT(u,a.tolerance))return this.handleCancel();if(yT(u,a.distance))return this.handleStart()}if(v9(a)&&yT(u,a.tolerance))return this.handleCancel();this.handlePending(a,u);return}t.cancelable&&t.preventDefault(),i(l)}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===yn.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const zYe={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class jg extends B5{constructor(t){const{event:n}=t,r=kg(n.target);super(t,zYe,r)}}jg.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 BYe={move:{name:"mousemove"},end:{name:"mouseup"}};var mA;(function(e){e[e.RightClick=2]="RightClick"})(mA||(mA={}));class VYe extends B5{constructor(t){super(t,BYe,kg(t.event.target))}}VYe.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===mA.RightClick?!1:(r==null||r({event:n}),!0)}}];const vT={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class HYe extends B5{constructor(t){super(t,vT)}static setup(){return window.addEventListener(vT.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(vT.move.name,t)};function t(){}}}HYe.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:s}=n;return s.length>1?!1:(r==null||r({event:n}),!0)}}];var Mx;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Mx||(Mx={}));var rN;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(rN||(rN={}));function UYe(e){let{acceleration:t,activator:n=Mx.Pointer,canScroll:r,draggingRect:s,enabled:o,interval:i=5,order:a=rN.TreeOrder,pointerCoordinates:l,scrollableAncestors:u,scrollableAncestorRects:d,delta:f,threshold:h}=e;const m=WYe({delta:f,disabled:!o}),[g,b]=oYe(),x=S.useRef({x:0,y:0}),y=S.useRef({x:0,y:0}),w=S.useMemo(()=>{switch(n){case Mx.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case Mx.DraggableRect:return s}},[n,s,l]),v=S.useRef(null),C=S.useCallback(()=>{const k=v.current;if(!k)return;const _=x.current.x*y.current.x,j=x.current.y*y.current.y;k.scrollBy(_,j)},[]),N=S.useMemo(()=>a===rN.TreeOrder?[...u].reverse():u,[a,u]);S.useEffect(()=>{if(!o||!u.length||!w){b();return}for(const k of N){if((r==null?void 0:r(k))===!1)continue;const _=u.indexOf(k),j=d[_];if(!j)continue;const{direction:I,speed:E}=MYe(k,j,w,t,h);for(const T of["x","y"])m[T][I[T]]||(E[T]=0,I[T]=0);if(E.x>0||E.y>0){b(),v.current=k,g(C,i),x.current=E,y.current=I;return}}x.current={x:0,y:0},y.current={x:0,y:0},b()},[t,C,r,b,o,i,JSON.stringify(w),JSON.stringify(m),g,u,N,d,JSON.stringify(h)])}const qYe={x:{[cs.Backward]:!1,[cs.Forward]:!1},y:{[cs.Backward]:!1,[cs.Forward]:!1}};function WYe(e){let{delta:t,disabled:n}=e;const r=eN(t);return mv(s=>{if(n||!r||!s)return qYe;const o={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[cs.Backward]:s.x[cs.Backward]||o.x===-1,[cs.Forward]:s.x[cs.Forward]||o.x===1},y:{[cs.Backward]:s.y[cs.Backward]||o.y===-1,[cs.Forward]:s.y[cs.Forward]||o.y===1}}},[n,t,r])}function YYe(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return mv(s=>{var o;return t==null?null:(o=r??s)!=null?o:null},[r,t])}function GYe(e,t){return S.useMemo(()=>e.reduce((n,r)=>{const{sensor:s}=r,o=s.activators.map(i=>({eventName:i.eventName,handler:t(i.handler,r)}));return[...n,...o]},[]),[e,t])}var Py;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Py||(Py={}));var pA;(function(e){e.Optimized="optimized"})(pA||(pA={}));const w9=new Map;function KYe(e,t){let{dragging:n,dependencies:r,config:s}=t;const[o,i]=S.useState(null),{frequency:a,measure:l,strategy:u}=s,d=S.useRef(e),f=x(),h=Ry(f),m=S.useCallback(function(y){y===void 0&&(y=[]),!h.current&&i(w=>w===null?y:w.concat(y.filter(v=>!w.includes(v))))},[h]),g=S.useRef(null),b=mv(y=>{if(f&&!n)return w9;if(!y||y===w9||d.current!==e||o!=null){const w=new Map;for(let v of e){if(!v)continue;if(o&&o.length>0&&!o.includes(v.id)&&v.rect.current){w.set(v.id,v.rect.current);continue}const C=v.node.current,N=C?new z5(l(C),C):null;v.rect.current=N,N&&w.set(v.id,N)}return w}return y},[e,o,n,f,l]);return S.useEffect(()=>{d.current=e},[e]),S.useEffect(()=>{f||m()},[n,f]),S.useEffect(()=>{o&&o.length>0&&i(null)},[JSON.stringify(o)]),S.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:o!=null};function x(){switch(u){case Py.Always:return!1;case Py.BeforeDragging:return n;default:return!n}}}function V5(e,t){return mv(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function ZYe(e,t){return V5(e,t)}function XYe(e){let{callback:t,disabled:n}=e;const r=A_(t),s=S.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(r)},[r,n]);return S.useEffect(()=>()=>s==null?void 0:s.disconnect(),[s]),s}function O_(e){let{callback:t,disabled:n}=e;const r=A_(t),s=S.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(r)},[n]);return S.useEffect(()=>()=>s==null?void 0:s.disconnect(),[s]),s}function QYe(e){return new z5(_g(e),e)}function S9(e,t,n){t===void 0&&(t=QYe);const[r,s]=S.useState(null);function o(){s(l=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=l??n)!=null?u:null}const d=t(e);return JSON.stringify(l)===JSON.stringify(d)?l:d})}const i=XYe({callback(l){if(e)for(const u of l){const{type:d,target:f}=u;if(d==="childList"&&f instanceof HTMLElement&&f.contains(e)){o();break}}}}),a=O_({callback:o});return xa(()=>{o(),e?(a==null||a.observe(e),i==null||i.observe(document.body,{childList:!0,subtree:!0})):(a==null||a.disconnect(),i==null||i.disconnect())},[e]),r}function JYe(e){const t=V5(e);return Boe(e,t)}const C9=[];function eGe(e){const t=S.useRef(e),n=mv(r=>e?r&&r!==C9&&e&&t.current&&e.parentNode===t.current.parentNode?r:P_(e):C9,[e]);return S.useEffect(()=>{t.current=e},[e]),n}function tGe(e){const[t,n]=S.useState(null),r=S.useRef(e),s=S.useCallback(o=>{const i=xT(o.target);i&&n(a=>a?(a.set(i,hA(i)),new Map(a)):null)},[]);return S.useEffect(()=>{const o=r.current;if(e!==o){i(o);const a=e.map(l=>{const u=xT(l);return u?(u.addEventListener("scroll",s,{passive:!0}),[u,hA(u)]):null}).filter(l=>l!=null);n(a.length?new Map(a):null),r.current=e}return()=>{i(e),i(o)};function i(a){a.forEach(l=>{const u=xT(l);u==null||u.removeEventListener("scroll",s)})}},[s,e]),S.useMemo(()=>e.length?t?Array.from(t.values()).reduce((o,i)=>Rm(o,i),ya):Goe(e):ya,[e,t])}function N9(e,t){t===void 0&&(t=[]);const n=S.useRef(null);return S.useEffect(()=>{n.current=null},t),S.useEffect(()=>{const r=e!==ya;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?Fy(e,n.current):ya}function nGe(e){S.useEffect(()=>{if(!M_)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 rGe(e,t){return S.useMemo(()=>e.reduce((n,r)=>{let{eventName:s,handler:o}=r;return n[s]=i=>{o(i,t)},n},{}),[e,t])}function Xoe(e){return S.useMemo(()=>e?EYe(e):null,[e])}const k9=[];function sGe(e,t){t===void 0&&(t=_g);const[n]=e,r=Xoe(n?vo(n):null),[s,o]=S.useState(k9);function i(){o(()=>e.length?e.map(l=>Woe(l)?r:new z5(t(l),l)):k9)}const a=O_({callback:i});return xa(()=>{a==null||a.disconnect(),i(),e.forEach(l=>a==null?void 0:a.observe(l))},[e]),s}function Qoe(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return hv(t)?t:e}function oGe(e){let{measure:t}=e;const[n,r]=S.useState(null),s=S.useCallback(u=>{for(const{target:d}of u)if(hv(d)){r(f=>{const h=t(d);return f?{...f,width:h.width,height:h.height}:h});break}},[t]),o=O_({callback:s}),i=S.useCallback(u=>{const d=Qoe(u);o==null||o.disconnect(),d&&(o==null||o.observe(d)),r(d?t(d):null)},[t,o]),[a,l]=JC(i);return S.useMemo(()=>({nodeRef:a,rect:n,setRef:l}),[n,a,l])}const iGe=[{sensor:jg,options:{}},{sensor:bv,options:{}}],aGe={current:{}},l1={draggable:{measure:b9},droppable:{measure:b9,strategy:Py.WhileDragging,frequency:pA.Optimized},dragOverlay:{measure:_g}};class Ax 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 lGe={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ax,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:nN},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:l1,measureDroppableContainers:nN,windowRect:null,measuringScheduled:!1},Joe={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:nN,draggableNodes:new Map,over:null,measureDroppableContainers:nN},xv=S.createContext(Joe),eie=S.createContext(lGe);function cGe(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ax}}}function uGe(e,t){switch(t.type){case ns.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case ns.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 ns.DragEnd:case ns.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ns.RegisterDroppable:{const{element:n}=t,{id:r}=n,s=new Ax(e.droppable.containers);return s.set(r,n),{...e,droppable:{...e.droppable,containers:s}}}case ns.SetDroppableDisabled:{const{id:n,key:r,disabled:s}=t,o=e.droppable.containers.get(n);if(!o||r!==o.key)return e;const i=new Ax(e.droppable.containers);return i.set(n,{...o,disabled:s}),{...e,droppable:{...e.droppable,containers:i}}}case ns.UnregisterDroppable:{const{id:n,key:r}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const o=new Ax(e.droppable.containers);return o.delete(n),{...e,droppable:{...e.droppable,containers:o}}}default:return e}}function dGe(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:s}=S.useContext(xv),o=eN(r),i=eN(n==null?void 0:n.id);return S.useEffect(()=>{if(!t&&!r&&o&&i!=null){if(!R_(o)||document.activeElement===o.target)return;const a=s.get(i);if(!a)return;const{activatorNode:l,node:u}=a;if(!l.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[l.current,u.current]){if(!d)continue;const f=lYe(d);if(f){f.focus();break}}})}},[r,t,s,i,o]),null}function tie(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((s,o)=>o({transform:s,...r}),n):n}function fGe(e){return S.useMemo(()=>({draggable:{...l1.draggable,...e==null?void 0:e.draggable},droppable:{...l1.droppable,...e==null?void 0:e.droppable},dragOverlay:{...l1.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 hGe(e){let{activeNode:t,measure:n,initialRect:r,config:s=!0}=e;const o=S.useRef(!1),{x:i,y:a}=typeof s=="boolean"?{x:s,y:s}:s;xa(()=>{if(!i&&!a||!t){o.current=!1;return}if(o.current||!r)return;const u=t==null?void 0:t.node.current;if(!u||u.isConnected===!1)return;const d=n(u),f=Boe(d,r);if(i||(f.x=0),a||(f.y=0),o.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const h=Hoe(u);h&&h.scrollBy({top:f.y,left:f.x})}},[t,i,a,r,n])}const L_=S.createContext({...ya,scaleX:1,scaleY:1});var $c;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})($c||($c={}));const yv=S.memo(function(t){var n,r,s,o;let{id:i,accessibility:a,autoScroll:l=!0,children:u,sensors:d=iGe,collisionDetection:f=SYe,measuring:h,modifiers:m,...g}=t;const b=S.useReducer(uGe,void 0,cGe),[x,y]=b,[w,v]=mYe(),[C,N]=S.useState($c.Uninitialized),k=C===$c.Initialized,{draggable:{active:_,nodes:j,translate:I},droppable:{containers:E}}=x,T=_!=null?j.get(_):null,D=S.useRef({initial:null,translated:null}),A=S.useMemo(()=>{var Pe;return _!=null?{id:_,data:(Pe=T==null?void 0:T.data)!=null?Pe:aGe,rect:D}:null},[_,T]),P=S.useRef(null),[R,H]=S.useState(null),[z,U]=S.useState(null),W=Ry(g,Object.values(g)),O=pv("DndDescribedBy",i),Z=S.useMemo(()=>E.getEnabled(),[E]),Y=fGe(h),{droppableRects:M,measureDroppableContainers:K,measuringScheduled:L}=KYe(Z,{dragging:k,dependencies:[I.x,I.y],config:Y.droppable}),$=YYe(j,_),B=S.useMemo(()=>z?tN(z):null,[z]),V=Xe(),F=ZYe($,Y.draggable.measure);hGe({activeNode:_!=null?j.get(_):null,config:V.layoutShiftCompensation,initialRect:F,measure:Y.draggable.measure});const q=S9($,Y.draggable.measure,F),G=S9($?$.parentElement:null),X=S.useRef({activatorEvent:null,active:null,activeNode:$,collisionRect:null,collisions:null,droppableRects:M,draggableNodes:j,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),J=E.getNodeFor((n=X.current.over)==null?void 0:n.id),fe=oGe({measure:Y.dragOverlay.measure}),ue=(r=fe.nodeRef.current)!=null?r:$,pe=k?(s=fe.rect)!=null?s:q:null,ye=!!(fe.nodeRef.current&&fe.rect),ie=JYe(ye?null:q),ae=Xoe(ue?vo(ue):null),se=eGe(k?J??$:null),Ie=sGe(se),oe=tie(m,{transform:{x:I.x-ie.x,y:I.y-ie.y,scaleX:1,scaleY:1},activatorEvent:z,active:A,activeNodeRect:q,containerNodeRect:G,draggingNodeRect:pe,over:X.current.over,overlayNodeRect:fe.rect,scrollableAncestors:se,scrollableAncestorRects:Ie,windowRect:ae}),me=B?Rm(B,I):null,we=tGe(se),ge=N9(we),re=N9(we,[q]),ne=Rm(oe,ge),he=pe?kYe(pe,oe):null,ee=A&&he?f({active:A,collisionRect:he,droppableRects:M,droppableContainers:Z,pointerCoordinates:me}):null,Ce=zoe(ee,"id"),[ve,te]=S.useState(null),_e=ye?oe:Rm(oe,re),De=CYe(_e,(o=ve==null?void 0:ve.rect)!=null?o:null,q),Fe=S.useRef(null),Ye=S.useCallback((Pe,He)=>{let{sensor:nt,options:Me}=He;if(P.current==null)return;const Ee=j.get(P.current);if(!Ee)return;const We=Pe.nativeEvent,vt=new nt({active:P.current,activeNode:Ee,event:We,options:Me,context:X,onAbort(ft){if(!j.get(ft))return;const{onDragAbort:lt}=W.current,Pt={id:ft};lt==null||lt(Pt),w({type:"onDragAbort",event:Pt})},onPending(ft,Nt,lt,Pt){if(!j.get(ft))return;const{onDragPending:Ze}=W.current,Je={id:ft,constraint:Nt,initialCoordinates:lt,offset:Pt};Ze==null||Ze(Je),w({type:"onDragPending",event:Je})},onStart(ft){const Nt=P.current;if(Nt==null)return;const lt=j.get(Nt);if(!lt)return;const{onDragStart:Pt}=W.current,Te={activatorEvent:We,active:{id:Nt,data:lt.data,rect:D}};fr.unstable_batchedUpdates(()=>{Pt==null||Pt(Te),N($c.Initializing),y({type:ns.DragStart,initialCoordinates:ft,active:Nt}),w({type:"onDragStart",event:Te}),H(Fe.current),U(We)})},onMove(ft){y({type:ns.DragMove,coordinates:ft})},onEnd:yt(ns.DragEnd),onCancel:yt(ns.DragCancel)});Fe.current=vt;function yt(ft){return async function(){const{active:lt,collisions:Pt,over:Te,scrollAdjustedTranslate:Ze}=X.current;let Je=null;if(lt&&Ze){const{cancelDrop:st}=W.current;Je={activatorEvent:We,active:lt,collisions:Pt,delta:Ze,over:Te},ft===ns.DragEnd&&typeof st=="function"&&await Promise.resolve(st(Je))&&(ft=ns.DragCancel)}P.current=null,fr.unstable_batchedUpdates(()=>{y({type:ft}),N($c.Uninitialized),te(null),H(null),U(null),Fe.current=null;const st=ft===ns.DragEnd?"onDragEnd":"onDragCancel";if(Je){const pt=W.current[st];pt==null||pt(Je),w({type:st,event:Je})}})}}},[j]),ze=S.useCallback((Pe,He)=>(nt,Me)=>{const Ee=nt.nativeEvent,We=j.get(Me);if(P.current!==null||!We||Ee.dndKit||Ee.defaultPrevented)return;const vt={active:We};Pe(nt,He.options,vt)===!0&&(Ee.dndKit={capturedBy:He.sensor},P.current=Me,Ye(nt,He))},[j,Ye]),Ve=GYe(d,ze);nGe(d),xa(()=>{q&&C===$c.Initializing&&N($c.Initialized)},[q,C]),S.useEffect(()=>{const{onDragMove:Pe}=W.current,{active:He,activatorEvent:nt,collisions:Me,over:Ee}=X.current;if(!He||!nt)return;const We={active:He,activatorEvent:nt,collisions:Me,delta:{x:ne.x,y:ne.y},over:Ee};fr.unstable_batchedUpdates(()=>{Pe==null||Pe(We),w({type:"onDragMove",event:We})})},[ne.x,ne.y]),S.useEffect(()=>{const{active:Pe,activatorEvent:He,collisions:nt,droppableContainers:Me,scrollAdjustedTranslate:Ee}=X.current;if(!Pe||P.current==null||!He||!Ee)return;const{onDragOver:We}=W.current,vt=Me.get(Ce),yt=vt&&vt.rect.current?{id:vt.id,rect:vt.rect.current,data:vt.data,disabled:vt.disabled}:null,ft={active:Pe,activatorEvent:He,collisions:nt,delta:{x:Ee.x,y:Ee.y},over:yt};fr.unstable_batchedUpdates(()=>{te(yt),We==null||We(ft),w({type:"onDragOver",event:ft})})},[Ce]),xa(()=>{X.current={activatorEvent:z,active:A,activeNode:$,collisionRect:he,collisions:ee,droppableRects:M,draggableNodes:j,draggingNode:ue,draggingNodeRect:pe,droppableContainers:E,over:ve,scrollableAncestors:se,scrollAdjustedTranslate:ne},D.current={initial:pe,translated:he}},[A,$,ee,he,j,ue,pe,M,E,ve,se,ne]),UYe({...V,delta:I,draggingRect:he,pointerCoordinates:me,scrollableAncestors:se,scrollableAncestorRects:Ie});const Ke=S.useMemo(()=>({active:A,activeNode:$,activeNodeRect:q,activatorEvent:z,collisions:ee,containerNodeRect:G,dragOverlay:fe,draggableNodes:j,droppableContainers:E,droppableRects:M,over:ve,measureDroppableContainers:K,scrollableAncestors:se,scrollableAncestorRects:Ie,measuringConfiguration:Y,measuringScheduled:L,windowRect:ae}),[A,$,q,z,ee,G,fe,j,E,M,ve,K,se,Ie,Y,L,ae]),ke=S.useMemo(()=>({activatorEvent:z,activators:Ve,active:A,activeNodeRect:q,ariaDescribedById:{draggable:O},dispatch:y,draggableNodes:j,over:ve,measureDroppableContainers:K}),[z,Ve,A,q,y,O,j,ve,K]);return S.createElement(Ooe.Provider,{value:v},S.createElement(xv.Provider,{value:ke},S.createElement(eie.Provider,{value:Ke},S.createElement(L_.Provider,{value:De},u)),S.createElement(dGe,{disabled:(a==null?void 0:a.restoreFocus)===!1})),S.createElement(bYe,{...a,hiddenTextDescribedById:O}));function Xe(){const Pe=(R==null?void 0:R.autoScrollEnabled)===!1,He=typeof l=="object"?l.enabled===!1:l===!1,nt=k&&!Pe&&!He;return typeof l=="object"?{...l,enabled:nt}:{enabled:nt}}}),mGe=S.createContext(null),_9="button",pGe="Draggable";function gGe(e){let{id:t,data:n,disabled:r=!1,attributes:s}=e;const o=pv(pGe),{activators:i,activatorEvent:a,active:l,activeNodeRect:u,ariaDescribedById:d,draggableNodes:f,over:h}=S.useContext(xv),{role:m=_9,roleDescription:g="draggable",tabIndex:b=0}=s??{},x=(l==null?void 0:l.id)===t,y=S.useContext(x?L_:mGe),[w,v]=JC(),[C,N]=JC(),k=rGe(i,t),_=Ry(n);xa(()=>(f.set(t,{id:t,key:o,node:w,activatorNode:C,data:_}),()=>{const I=f.get(t);I&&I.key===o&&f.delete(t)}),[f,t]);const j=S.useMemo(()=>({role:m,tabIndex:b,"aria-disabled":r,"aria-pressed":x&&m===_9?!0:void 0,"aria-roledescription":g,"aria-describedby":d.draggable}),[r,m,b,x,g,d.draggable]);return{active:l,activatorEvent:a,activeNodeRect:u,attributes:j,isDragging:x,listeners:r?void 0:k,node:w,over:h,setNodeRef:v,setActivatorNodeRef:N,transform:y}}function nie(){return S.useContext(eie)}const bGe="Droppable",xGe={timeout:25};function rie(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:s}=e;const o=pv(bGe),{active:i,dispatch:a,over:l,measureDroppableContainers:u}=S.useContext(xv),d=S.useRef({disabled:n}),f=S.useRef(!1),h=S.useRef(null),m=S.useRef(null),{disabled:g,updateMeasurementsFor:b,timeout:x}={...xGe,...s},y=Ry(b??r),w=S.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]),v=O_({callback:w,disabled:g||!i}),C=S.useCallback((j,I)=>{v&&(I&&(v.unobserve(I),f.current=!1),j&&v.observe(j))},[v]),[N,k]=JC(C),_=Ry(t);return S.useEffect(()=>{!v||!N.current||(v.disconnect(),f.current=!1,v.observe(N.current))},[N,v]),S.useEffect(()=>(a({type:ns.RegisterDroppable,element:{id:r,key:o,disabled:n,node:N,rect:h,data:_}}),()=>a({type:ns.UnregisterDroppable,key:o,id:r})),[r]),S.useEffect(()=>{n!==d.current.disabled&&(a({type:ns.SetDroppableDisabled,id:r,key:o,disabled:n}),d.current.disabled=n)},[r,o,n,a]),{active:i,rect:h,isOver:(l==null?void 0:l.id)===r,node:N,over:l,setNodeRef:k}}function yGe(e){let{animation:t,children:n}=e;const[r,s]=S.useState(null),[o,i]=S.useState(null),a=eN(n);return!n&&!r&&a&&s(a),xa(()=>{if(!o)return;const l=r==null?void 0:r.key,u=r==null?void 0:r.props.id;if(l==null||u==null){s(null);return}Promise.resolve(t(u,o)).then(()=>{s(null)})},[t,r,o]),S.createElement(S.Fragment,null,n,r?S.cloneElement(r,{ref:i}):null)}const vGe={x:0,y:0,scaleX:1,scaleY:1};function wGe(e){let{children:t}=e;return S.createElement(xv.Provider,{value:Joe},S.createElement(L_.Provider,{value:vGe},t))}const SGe={position:"fixed",touchAction:"none"},CGe=e=>R_(e)?"transform 250ms ease":void 0,NGe=S.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:s,children:o,className:i,rect:a,style:l,transform:u,transition:d=CGe}=e;if(!a)return null;const f=s?u:{...u,scaleX:1,scaleY:1},h={...SGe,width:a.width,height:a.height,top:a.top,left:a.left,transform:di.Transform.toString(f),transformOrigin:s&&r?xYe(r,a):void 0,transition:typeof d=="function"?d(r):d,...l};return S.createElement(n,{className:i,style:h,ref:t},o)}),kGe=e=>t=>{let{active:n,dragOverlay:r}=t;const s={},{styles:o,className:i}=e;if(o!=null&&o.active)for(const[a,l]of Object.entries(o.active))l!==void 0&&(s[a]=n.node.style.getPropertyValue(a),n.node.style.setProperty(a,l));if(o!=null&&o.dragOverlay)for(const[a,l]of Object.entries(o.dragOverlay))l!==void 0&&r.node.style.setProperty(a,l);return i!=null&&i.active&&n.node.classList.add(i.active),i!=null&&i.dragOverlay&&r.node.classList.add(i.dragOverlay),function(){for(const[l,u]of Object.entries(s))n.node.style.setProperty(l,u);i!=null&&i.active&&n.node.classList.remove(i.active)}},_Ge=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:di.Transform.toString(t)},{transform:di.Transform.toString(n)}]},jGe={duration:250,easing:"ease",keyframes:_Ge,sideEffects:kGe({styles:{active:{opacity:"0"}}})};function EGe(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:s}=e;return A_((o,i)=>{if(t===null)return;const a=n.get(o);if(!a)return;const l=a.node.current;if(!l)return;const u=Qoe(i);if(!u)return;const{transform:d}=vo(i).getComputedStyle(i),f=Voe(d);if(!f)return;const h=typeof t=="function"?t:IGe(t);return Koe(l,s.draggable.measure),h({active:{id:o,data:a.data,node:l,rect:s.draggable.measure(l)},draggableNodes:n,dragOverlay:{node:i,rect:s.dragOverlay.measure(u)},droppableContainers:r,measuringConfiguration:s,transform:f})})}function IGe(e){const{duration:t,easing:n,sideEffects:r,keyframes:s}={...jGe,...e};return o=>{let{active:i,dragOverlay:a,transform:l,...u}=o;if(!t)return;const d={x:a.rect.left-i.rect.left,y:a.rect.top-i.rect.top},f={scaleX:l.scaleX!==1?i.rect.width*l.scaleX/a.rect.width:1,scaleY:l.scaleY!==1?i.rect.height*l.scaleY/a.rect.height:1},h={x:l.x-d.x,y:l.y-d.y,...f},m=s({...u,active:i,dragOverlay:a,transform:{initial:l,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 j9=0;function TGe(e){return S.useMemo(()=>{if(e!=null)return j9++,j9},[e])}const sie=S.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:s,transition:o,modifiers:i,wrapperElement:a="div",className:l,zIndex:u=999}=e;const{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:m,draggableNodes:g,droppableContainers:b,dragOverlay:x,over:y,measuringConfiguration:w,scrollableAncestors:v,scrollableAncestorRects:C,windowRect:N}=nie(),k=S.useContext(L_),_=TGe(f==null?void 0:f.id),j=tie(i,{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:m,draggingNodeRect:x.rect,over:y,overlayNodeRect:x.rect,scrollableAncestors:v,scrollableAncestorRects:C,transform:k,windowRect:N}),I=V5(h),E=EGe({config:r,draggableNodes:g,droppableContainers:b,measuringConfiguration:w}),T=I?x.setRef:void 0;return S.createElement(wGe,null,S.createElement(yGe,{animation:E},f&&_?S.createElement(NGe,{key:_,id:f.id,ref:T,as:a,activatorEvent:d,adjustScale:t,className:l,transition:o,rect:I,style:{zIndex:u,...s},transform:j},n):null))});function Eg(e,t,n){const r=e.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function DGe(e,t){return e.reduce((n,r,s)=>{const o=t.get(r);return o&&(n[s]=o),n},Array(e.length))}function aS(e){return e!==null&&e>=0}function MGe(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 AGe(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const lS={scaleX:1,scaleY:1},H5=e=>{var t;let{rects:n,activeNodeRect:r,activeIndex:s,overIndex:o,index:i}=e;const a=(t=n[s])!=null?t:r;if(!a)return null;const l=RGe(n,i,s);if(i===s){const u=n[o];return u?{x:s<o?u.left+u.width-(a.left+a.width):u.left-a.left,y:0,...lS}:null}return i>s&&i<=o?{x:-a.width-l,y:0,...lS}:i<s&&i>=o?{x:a.width+l,y:0,...lS}:{x:0,y:0,...lS}};function RGe(e,t,n){const r=e[t],s=e[t-1],o=e[t+1];return!r||!s&&!o?0:n<t?s?r.left-(s.left+s.width):o.left-(r.left+r.width):o?o.left-(r.left+r.width):r.left-(s.left+s.width)}const oie=e=>{let{rects:t,activeIndex:n,overIndex:r,index:s}=e;const o=Eg(t,r,n),i=t[s],a=o[s];return!a||!i?null:{x:a.left-i.left,y:a.top-i.top,scaleX:a.width/i.width,scaleY:a.height/i.height}},cS={scaleX:1,scaleY:1},U5=e=>{var t;let{activeIndex:n,activeNodeRect:r,index:s,rects:o,overIndex:i}=e;const a=(t=o[n])!=null?t:r;if(!a)return null;if(s===n){const u=o[i];return u?{x:0,y:n<i?u.top+u.height-(a.top+a.height):u.top-a.top,...cS}:null}const l=FGe(o,s,n);return s>n&&s<=i?{x:0,y:-a.height-l,...cS}:s<n&&s>=i?{x:0,y:a.height+l,...cS}:{x:0,y:0,...cS}};function FGe(e,t,n){const r=e[t],s=e[t-1],o=e[t+1];return r?n<t?s?r.top-(s.top+s.height):o?o.top-(r.top+r.height):0:o?o.top-(r.top+r.height):s?r.top-(s.top+s.height):0:0}const iie="Sortable",aie=S.createContext({activeIndex:-1,containerId:iie,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:oie,disabled:{draggable:!1,droppable:!1}});function vv(e){let{children:t,id:n,items:r,strategy:s=oie,disabled:o=!1}=e;const{active:i,dragOverlay:a,droppableRects:l,over:u,measureDroppableContainers:d}=nie(),f=pv(iie,n),h=a.rect!==null,m=S.useMemo(()=>r.map(k=>typeof k=="object"&&"id"in k?k.id:k),[r]),g=i!=null,b=i?m.indexOf(i.id):-1,x=u?m.indexOf(u.id):-1,y=S.useRef(m),w=!MGe(m,y.current),v=x!==-1&&b===-1||w,C=AGe(o);xa(()=>{w&&g&&d(m)},[w,m,g,d]),S.useEffect(()=>{y.current=m},[m]);const N=S.useMemo(()=>({activeIndex:b,containerId:f,disabled:C,disableTransforms:v,items:m,overIndex:x,useDragOverlay:h,sortedRects:DGe(m,l),strategy:s}),[b,f,C.draggable,C.droppable,v,m,x,l,h,s]);return S.createElement(aie.Provider,{value:N},t)}const PGe=e=>{let{id:t,items:n,activeIndex:r,overIndex:s}=e;return Eg(n,r,s).indexOf(t)},OGe=e=>{let{containerId:t,isSorting:n,wasDragging:r,index:s,items:o,newIndex:i,previousItems:a,previousContainerId:l,transition:u}=e;return!u||!r||a!==o&&s===i?!1:n?!0:i!==s&&t===l},LGe={duration:200,easing:"ease"},lie="transform",$Ge=di.Transition.toString({property:lie,duration:0,easing:"linear"}),zGe={roleDescription:"sortable"};function BGe(e){let{disabled:t,index:n,node:r,rect:s}=e;const[o,i]=S.useState(null),a=S.useRef(n);return xa(()=>{if(!t&&n!==a.current&&r.current){const l=s.current;if(l){const u=_g(r.current,{ignoreTransform:!0}),d={x:l.left-u.left,y:l.top-u.top,scaleX:l.width/u.width,scaleY:l.height/u.height};(d.x||d.y)&&i(d)}}n!==a.current&&(a.current=n)},[t,n,r,s]),S.useEffect(()=>{o&&i(null)},[o]),o}function Ig(e){let{animateLayoutChanges:t=OGe,attributes:n,disabled:r,data:s,getNewIndex:o=PGe,id:i,strategy:a,resizeObserverConfig:l,transition:u=LGe}=e;const{items:d,containerId:f,activeIndex:h,disabled:m,disableTransforms:g,sortedRects:b,overIndex:x,useDragOverlay:y,strategy:w}=S.useContext(aie),v=VGe(r,m),C=d.indexOf(i),N=S.useMemo(()=>({sortable:{containerId:f,index:C,items:d},...s}),[f,s,C,d]),k=S.useMemo(()=>d.slice(d.indexOf(i)),[d,i]),{rect:_,node:j,isOver:I,setNodeRef:E}=rie({id:i,data:N,disabled:v.droppable,resizeObserverConfig:{updateMeasurementsFor:k,...l}}),{active:T,activatorEvent:D,activeNodeRect:A,attributes:P,setNodeRef:R,listeners:H,isDragging:z,over:U,setActivatorNodeRef:W,transform:O}=gGe({id:i,data:N,attributes:{...zGe,...n},disabled:v.draggable}),Z=sYe(E,R),Y=!!T,M=Y&&!g&&aS(h)&&aS(x),K=!y&&z,L=K&&M?O:null,B=M?L??(a??w)({rects:b,activeNodeRect:A,activeIndex:h,overIndex:x,index:C}):null,V=aS(h)&&aS(x)?o({id:i,items:d,activeIndex:h,overIndex:x}):C,F=T==null?void 0:T.id,q=S.useRef({activeId:F,items:d,newIndex:V,containerId:f}),G=d!==q.current.items,X=t({active:T,containerId:f,isDragging:z,isSorting:Y,id:i,index:C,items:d,newIndex:q.current.newIndex,previousItems:q.current.items,previousContainerId:q.current.containerId,transition:u,wasDragging:q.current.activeId!=null}),J=BGe({disabled:!X,index:C,node:j,rect:_});return S.useEffect(()=>{Y&&q.current.newIndex!==V&&(q.current.newIndex=V),f!==q.current.containerId&&(q.current.containerId=f),d!==q.current.items&&(q.current.items=d)},[Y,V,f,d]),S.useEffect(()=>{if(F===q.current.activeId)return;if(F!=null&&q.current.activeId==null){q.current.activeId=F;return}const ue=setTimeout(()=>{q.current.activeId=F},50);return()=>clearTimeout(ue)},[F]),{active:T,activeIndex:h,attributes:P,data:N,rect:_,index:C,newIndex:V,items:d,isOver:I,isSorting:Y,isDragging:z,listeners:H,node:j,overIndex:x,over:U,setNodeRef:Z,setActivatorNodeRef:W,setDroppableNodeRef:E,setDraggableNodeRef:R,transform:J??B,transition:fe()};function fe(){if(J||G&&q.current.newIndex===C)return $Ge;if(!(K&&!R_(D)||!u)&&(Y||X))return di.Transition.toString({...u,property:lie})}}function VGe(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 sN(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 HGe=[yn.Down,yn.Right,yn.Up,yn.Left],q5=(e,t)=>{let{context:{active:n,collisionRect:r,droppableRects:s,droppableContainers:o,over:i,scrollableAncestors:a}}=t;if(HGe.includes(e.code)){if(e.preventDefault(),!n||!r)return;const l=[];o.getEnabled().forEach(f=>{if(!f||f!=null&&f.disabled)return;const h=s.get(f.id);if(h)switch(e.code){case yn.Down:r.top<h.top&&l.push(f);break;case yn.Up:r.top>h.top&&l.push(f);break;case yn.Left:r.left>h.left&&l.push(f);break;case yn.Right:r.left<h.left&&l.push(f);break}});const u=vYe({collisionRect:r,droppableRects:s,droppableContainers:l});let d=zoe(u,"id");if(d===(i==null?void 0:i.id)&&u.length>1&&(d=u[1].id),d!=null){const f=o.get(n.id),h=o.get(d),m=h?s.get(h.id):null,g=h==null?void 0:h.node.current;if(g&&m&&f&&h){const x=P_(g).some((k,_)=>a[_]!==k),y=cie(f,h),w=UGe(f,h),v=x||!y?{x:0,y:0}:{x:w?r.width-m.width:0,y:w?r.height-m.height:0},C={x:m.left,y:m.top};return v.x&&v.y?C:Fy(C,v)}}}};function cie(e,t){return!sN(e)||!sN(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function UGe(e,t){return!sN(e)||!sN(t)||!cie(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function qGe(e,t,n){const[r,s]=S.useState(null),[o,i]=S.useState(""),a=()=>{const g={id:`hierarchy_${Date.now()}`,label:o||"New Hierarchy",type:"static",steps:[],default:!1};t([...e,g]),i(""),s(g.id)},l=g=>{t(e.filter(b=>b.id!==g))},u=(g,b)=>{t(e.map(x=>x.id===g?{...x,...b}:x))};return{editingHierarchy:r,setEditingHierarchy:s,newHierarchyName:o,setNewHierarchyName:i,createNewHierarchy:a,deleteHierarchy:l,updateHierarchy:u,addStepToHierarchy:(g,b)=>{const x=n.find(v=>v.id===b);if(!x)return;const y={field:x,mode:"drillDown",label:`Drill to ${x.label}`,retainFilters:!0,preferredChartType:"bar"},w=e.find(v=>v.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((v,C)=>C===b?{...v,...x}:v);u(g,{steps:w})}},setDefaultHierarchy:g=>{t(e.map(b=>({...b,default:b.id===g})))}}}function WGe({step:e,hierarchyId:t,stepIndex:n,onUpdateStep:r,open:s,onOpenChange:o,trigger:i}){return c.jsxs(p.Popover,{open:s,onOpenChange:o,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:i}),c.jsx(p.PopoverContent,{className:"z-50 w-80",align:"start",children:c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{children:[c.jsx(p.Label,{className:"mb-1 block text-xs font-medium",children:"Chart Type"}),c.jsxs(p.Select,{value:e.preferredChartType||"bar",onValueChange:a=>{r(t,n,{preferredChartType:a})},children:[c.jsx(p.SelectTrigger,{className:"h-8",children:c.jsx(p.SelectValue,{})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"bar",children:"Bar Chart"}),c.jsx(p.SelectItem,{value:"pie",children:"Pie Chart"}),c.jsx(p.SelectItem,{value:"line",children:"Line Chart"}),c.jsx(p.SelectItem,{value:"donut",children:"Donut Chart"}),c.jsx(p.SelectItem,{value:"table",children:"Table"}),c.jsx(p.SelectItem,{value:"metric",children:"Metric"})]})]})]}),c.jsxs("div",{children:[c.jsx(p.Label,{className:"mb-1 block text-xs font-medium",children:"Step Label"}),c.jsx(p.Input,{value:e.label||"",onChange:a=>r(t,n,{label:a.target.value}),placeholder:"Custom drill label",className:"h-8"})]}),c.jsxs("div",{children:[c.jsx(p.Label,{className:"mb-1 block text-xs font-medium",children:"Breadcrumb Label Template"}),c.jsx(p.Input,{value:e.breadcrumbLabelTemplate||"",onChange:a=>r(t,n,{breadcrumbLabelTemplate:a.target.value}),placeholder:"e.g., 'Region: {{value}}'",className:"h-8"})]}),c.jsx("div",{className:"flex items-center gap-4",children:c.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[c.jsx("input",{type:"checkbox",checked:e.retainFilters!==!1,onChange:a=>r(t,n,{retainFilters:a.target.checked}),className:"rounded"}),"Retain filters when drilling"]})}),c.jsx("div",{className:"flex justify-end",children:c.jsx(p.Button,{size:"sm",variant:"outline",onClick:()=>o(!1),children:"Done"})})]})})]})}function YGe({field:e,step:t,stepIndex:n,hierarchyId:r,onUpdateStep:s,onRemoveStep:o}){const[i,a]=S.useState(!1),{attributes:l,listeners:u,setNodeRef:d,transform:f,transition:h,isDragging:m}=Ig({id:`${r}-${e.id}-${n}`,disabled:!1}),g={transform:di.Transform.toString(f),transition:h,opacity:m?.8:1,zIndex:m?1e3:1};return c.jsx("div",{ref:d,style:g,className:`relative ${i?"z-[9998]":""}`,...l,children:c.jsx(WGe,{step:t,hierarchyId:r,stepIndex:n,onUpdateStep:s,open:i,onOpenChange:a,trigger:c.jsxs("div",{className:`flex cursor-pointer items-center gap-2 rounded-lg border bg-muted px-3 py-2 transition-colors hover:bg-muted/50 ${m?"shadow-lg ring-2 ring-primary":""}`,...u,onClick:b=>{b.stopPropagation(),a(x=>!x)},children:[c.jsxs("div",{className:"pointer-events-none flex items-center gap-2",children:[c.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:e.label}),t.preferredChartType&&t.preferredChartType!=="bar"&&c.jsx("span",{className:"whitespace-nowrap rounded bg-purple-100 px-1 py-0.5 text-xs text-purple-700 dark:bg-purple-900/50 dark:text-purple-300",children:t.preferredChartType}),t.linkedInsightId&&c.jsx("span",{className:"whitespace-nowrap rounded bg-green-100 px-1 py-0.5 text-xs text-green-700 dark:bg-green-900/50 dark:text-green-300",children:"📊"})]}),c.jsx("button",{className:"pointer-events-auto ml-1 text-xs text-muted-foreground hover:text-red-800 dark:hover:text-red-400",onClick:b=>{b.stopPropagation(),o(r,n)},children:c.jsx(p.X,{className:"h-3 w-3"})})]})})})}function GGe(e){return{sensors:F_(Ep(jg,{activationConstraint:{distance:5}}),Ep(bv,{coordinateGetter:q5})),handleStepDragEnd:(r,s)=>{const{active:o,over:i}=r;if(!i||o.id===i.id)return;const a=o.id.replace(`${s.id}-`,""),l=i.id.replace(`${s.id}-`,""),u=s.steps.findIndex(f=>f.field.id===a),d=s.steps.findIndex(f=>f.field.id===l);if(u!==-1&&d!==-1&&u!==d){const f=Eg(s.steps,u,d);e(s.id,{steps:f})}}}}function KGe({hierarchy:e,onUpdateStep:t,onRemoveStep:n,onUpdateHierarchy:r}){const{sensors:s}=GGe(r),[o,i]=S.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?c.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:c.jsx("div",{className:"rounded-lg border bg-muted/50 p-2 text-sm text-muted-foreground",children:"No drill steps configured. Add steps to create a drill hierarchy."})}):c.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:c.jsxs(yv,{sensors:s,collisionDetection:gv,onDragStart:d,onDragEnd:f,children:[c.jsx(vv,{items:u,strategy:H5,children:c.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(c.jsx(vr,{className:"pointer-events-none h-4 w-4 text-gray-400"},`arrow-${m}`));const b=m===0,x=m===a.length-1;return g.push(c.jsx(YGe,{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"&&fr.createPortal(c.jsx(Sg,{children:c.jsx(sie,{style:{zIndex:9999},children:o?c.jsx("div",{className:"flex items-center gap-2 rounded-lg border-2 border-blue-300 bg-blue-200 p-2 shadow-lg dark:border-blue-600 dark:bg-blue-900/70",children:c.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:o.label})}):null})}),document.body)]})})}var E9=1,ZGe=.9,XGe=.8,QGe=.17,wT=.1,ST=.999,JGe=.9999,eKe=.99,tKe=/[\\\/_+.#"@\[\(\{&]/,nKe=/[\\\/_+.#"@\[\(\{&]/g,rKe=/[\s-]/,uie=/[\s-]/g;function gA(e,t,n,r,s,o,i){if(o===t.length)return s===e.length?E9:eKe;var a=`${s},${o}`;if(i[a]!==void 0)return i[a];for(var l=r.charAt(o),u=n.indexOf(l,s),d=0,f,h,m,g;u>=0;)f=gA(e,t,n,r,u+1,o+1,i),f>d&&(u===s?f*=E9:tKe.test(e.charAt(u-1))?(f*=XGe,m=e.slice(s,u-1).match(nKe),m&&s>0&&(f*=Math.pow(ST,m.length))):rKe.test(e.charAt(u-1))?(f*=ZGe,g=e.slice(s,u-1).match(uie),g&&s>0&&(f*=Math.pow(ST,g.length))):(f*=QGe,s>0&&(f*=Math.pow(ST,u-s))),e.charAt(u)!==t.charAt(o)&&(f*=JGe)),(f<wT&&n.charAt(u-1)===r.charAt(o+1)||r.charAt(o+1)===r.charAt(o)&&n.charAt(u-1)!==r.charAt(o))&&(h=gA(e,t,n,r,u+1,o+2,i),h*wT>f&&(f=h*wT)),f>d&&(d=f),u=n.indexOf(l,u+1);return i[a]=d,d}function I9(e){return e.toLowerCase().replace(uie," ")}function sKe(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,gA(e,t,I9(e),I9(t),0,0,{})}var xb='[cmdk-group=""]',CT='[cmdk-group-items=""]',oKe='[cmdk-group-heading=""]',die='[cmdk-item=""]',T9=`${die}:not([aria-disabled="true"])`,bA="cmdk-item-select",im="data-value",iKe=(e,t,n)=>sKe(e,t,n),fie=Q.createContext(void 0),wv=()=>Q.useContext(fie),hie=Q.createContext(void 0),W5=()=>Q.useContext(hie),mie=Q.createContext(void 0),pie=Q.forwardRef((e,t)=>{let n=am(()=>{var Y,M;return{search:"",value:(M=(Y=e.value)!=null?Y:e.defaultValue)!=null?M:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=am(()=>new Set),s=am(()=>new Map),o=am(()=>new Map),i=am(()=>new Set),a=gie(e),{label:l,children:u,value:d,onValueChange:f,filter:h,shouldFilter:m,loop:g,disablePointerSelection:b=!1,vimBindings:x=!0,...y}=e,w=p.useId(),v=p.useId(),C=p.useId(),N=Q.useRef(null),k=bKe();rh(()=>{if(d!==void 0){let Y=d.trim();n.current.value=Y,_.emit()}},[d]),rh(()=>{k(6,A)},[]);let _=Q.useMemo(()=>({subscribe:Y=>(i.current.add(Y),()=>i.current.delete(Y)),snapshot:()=>n.current,setState:(Y,M,K)=>{var L,$,B,V;if(!Object.is(n.current[Y],M)){if(n.current[Y]=M,Y==="search")D(),E(),k(1,T);else if(Y==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let F=document.getElementById(C);F?F.focus():(L=document.getElementById(w))==null||L.focus()}if(k(7,()=>{var F;n.current.selectedItemId=(F=P())==null?void 0:F.id,_.emit()}),K||k(5,A),(($=a.current)==null?void 0:$.value)!==void 0){let F=M??"";(V=(B=a.current).onValueChange)==null||V.call(B,F);return}}_.emit()}},emit:()=>{i.current.forEach(Y=>Y())}}),[]),j=Q.useMemo(()=>({value:(Y,M,K)=>{var L;M!==((L=o.current.get(Y))==null?void 0:L.value)&&(o.current.set(Y,{value:M,keywords:K}),n.current.filtered.items.set(Y,I(M,K)),k(2,()=>{E(),_.emit()}))},item:(Y,M)=>(r.current.add(Y),M&&(s.current.has(M)?s.current.get(M).add(Y):s.current.set(M,new Set([Y]))),k(3,()=>{D(),E(),n.current.value||T(),_.emit()}),()=>{o.current.delete(Y),r.current.delete(Y),n.current.filtered.items.delete(Y);let K=P();k(4,()=>{D(),(K==null?void 0:K.getAttribute("id"))===Y&&T(),_.emit()})}),group:Y=>(s.current.has(Y)||s.current.set(Y,new Set),()=>{o.current.delete(Y),s.current.delete(Y)}),filter:()=>a.current.shouldFilter,label:l||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:w,inputId:C,labelId:v,listInnerRef:N}),[]);function I(Y,M){var K,L;let $=(L=(K=a.current)==null?void 0:K.filter)!=null?L:iKe;return Y?$(Y,n.current.search,M):0}function E(){if(!n.current.search||a.current.shouldFilter===!1)return;let Y=n.current.filtered.items,M=[];n.current.filtered.groups.forEach(L=>{let $=s.current.get(L),B=0;$.forEach(V=>{let F=Y.get(V);B=Math.max(F,B)}),M.push([L,B])});let K=N.current;R().sort((L,$)=>{var B,V;let F=L.getAttribute("id"),q=$.getAttribute("id");return((B=Y.get(q))!=null?B:0)-((V=Y.get(F))!=null?V:0)}).forEach(L=>{let $=L.closest(CT);$?$.appendChild(L.parentElement===$?L:L.closest(`${CT} > *`)):K.appendChild(L.parentElement===K?L:L.closest(`${CT} > *`))}),M.sort((L,$)=>$[1]-L[1]).forEach(L=>{var $;let B=($=N.current)==null?void 0:$.querySelector(`${xb}[${im}="${encodeURIComponent(L[0])}"]`);B==null||B.parentElement.appendChild(B)})}function T(){let Y=R().find(K=>K.getAttribute("aria-disabled")!=="true"),M=Y==null?void 0:Y.getAttribute(im);_.setState("value",M||void 0)}function D(){var Y,M,K,L;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let $=0;for(let B of r.current){let V=(M=(Y=o.current.get(B))==null?void 0:Y.value)!=null?M:"",F=(L=(K=o.current.get(B))==null?void 0:K.keywords)!=null?L:[],q=I(V,F);n.current.filtered.items.set(B,q),q>0&&$++}for(let[B,V]of s.current)for(let F of V)if(n.current.filtered.items.get(F)>0){n.current.filtered.groups.add(B);break}n.current.filtered.count=$}function A(){var Y,M,K;let L=P();L&&(((Y=L.parentElement)==null?void 0:Y.firstChild)===L&&((K=(M=L.closest(xb))==null?void 0:M.querySelector(oKe))==null||K.scrollIntoView({block:"nearest"})),L.scrollIntoView({block:"nearest"}))}function P(){var Y;return(Y=N.current)==null?void 0:Y.querySelector(`${die}[aria-selected="true"]`)}function R(){var Y;return Array.from(((Y=N.current)==null?void 0:Y.querySelectorAll(T9))||[])}function H(Y){let M=R()[Y];M&&_.setState("value",M.getAttribute(im))}function z(Y){var M;let K=P(),L=R(),$=L.findIndex(V=>V===K),B=L[$+Y];(M=a.current)!=null&&M.loop&&(B=$+Y<0?L[L.length-1]:$+Y===L.length?L[0]:L[$+Y]),B&&_.setState("value",B.getAttribute(im))}function U(Y){let M=P(),K=M==null?void 0:M.closest(xb),L;for(;K&&!L;)K=Y>0?pKe(K,xb):gKe(K,xb),L=K==null?void 0:K.querySelector(T9);L?_.setState("value",L.getAttribute(im)):z(Y)}let W=()=>H(R().length-1),O=Y=>{Y.preventDefault(),Y.metaKey?W():Y.altKey?U(1):z(1)},Z=Y=>{Y.preventDefault(),Y.metaKey?H(0):Y.altKey?U(-1):z(-1)};return Q.createElement(p.Primitive.div,{ref:t,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:Y=>{var M;(M=y.onKeyDown)==null||M.call(y,Y);let K=Y.nativeEvent.isComposing||Y.keyCode===229;if(!(Y.defaultPrevented||K))switch(Y.key){case"n":case"j":{x&&Y.ctrlKey&&O(Y);break}case"ArrowDown":{O(Y);break}case"p":case"k":{x&&Y.ctrlKey&&Z(Y);break}case"ArrowUp":{Z(Y);break}case"Home":{Y.preventDefault(),H(0);break}case"End":{Y.preventDefault(),W();break}case"Enter":{Y.preventDefault();let L=P();if(L){let $=new Event(bA);L.dispatchEvent($)}}}}},Q.createElement("label",{"cmdk-label":"",htmlFor:j.inputId,id:j.labelId,style:yKe},l),$_(e,Y=>Q.createElement(hie.Provider,{value:_},Q.createElement(fie.Provider,{value:j},Y))))}),aKe=Q.forwardRef((e,t)=>{var n,r;let s=p.useId(),o=Q.useRef(null),i=Q.useContext(mie),a=wv(),l=gie(e),u=(r=(n=l.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;rh(()=>{if(!u)return a.item(s,i==null?void 0:i.id)},[u]);let d=bie(s,o,[e.value,e.children,o],e.keywords),f=W5(),h=Ou(k=>k.value&&k.value===d.current),m=Ou(k=>u||a.filter()===!1?!0:k.search?k.filtered.items.get(s)>0:!0);Q.useEffect(()=>{let k=o.current;if(!(!k||e.disabled))return k.addEventListener(bA,g),()=>k.removeEventListener(bA,g)},[m,e.onSelect,e.disabled]);function g(){var k,_;b(),(_=(k=l.current).onSelect)==null||_.call(k,d.current)}function b(){f.setState("value",d.current,!0)}if(!m)return null;let{disabled:x,value:y,onSelect:w,forceMount:v,keywords:C,...N}=e;return Q.createElement(p.Primitive.div,{ref:p.composeRefs(o,t),...N,id:s,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!h,"data-disabled":!!x,"data-selected":!!h,onPointerMove:x||a.getDisablePointerSelection()?void 0:b,onClick:x?void 0:g},e.children)}),lKe=Q.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:s,...o}=e,i=p.useId(),a=Q.useRef(null),l=Q.useRef(null),u=p.useId(),d=wv(),f=Ou(m=>s||d.filter()===!1?!0:m.search?m.filtered.groups.has(i):!0);rh(()=>d.group(i),[]),bie(i,a,[e.value,e.heading,l]);let h=Q.useMemo(()=>({id:i,forceMount:s}),[s]);return Q.createElement(p.Primitive.div,{ref:p.composeRefs(a,t),...o,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&Q.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:u},n),$_(e,m=>Q.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?u:void 0},Q.createElement(mie.Provider,{value:h},m))))}),cKe=Q.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,s=Q.useRef(null),o=Ou(i=>!i.search);return!n&&!o?null:Q.createElement(p.Primitive.div,{ref:p.composeRefs(s,t),...r,"cmdk-separator":"",role:"separator"})}),uKe=Q.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,s=e.value!=null,o=W5(),i=Ou(u=>u.search),a=Ou(u=>u.selectedItemId),l=wv();return Q.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),Q.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":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":a,id:l.inputId,type:"text",value:s?e.value:i,onChange:u=>{s||o.setState("search",u.target.value),n==null||n(u.target.value)}})}),dKe=Q.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...s}=e,o=Q.useRef(null),i=Q.useRef(null),a=Ou(u=>u.selectedItemId),l=wv();return Q.useEffect(()=>{if(i.current&&o.current){let u=i.current,d=o.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=u.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return h.observe(u),()=>{cancelAnimationFrame(f),h.unobserve(u)}}},[]),Q.createElement(p.Primitive.div,{ref:p.composeRefs(o,t),...s,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:l.listId},$_(e,u=>Q.createElement("div",{ref:p.composeRefs(i,l.listInnerRef),"cmdk-list-sizer":""},u)))}),fKe=Q.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:s,contentClassName:o,container:i,...a}=e;return Q.createElement(WN,{open:n,onOpenChange:r},Q.createElement(YN,{container:i},Q.createElement(Op,{"cmdk-overlay":"",className:s}),Q.createElement(Lp,{"aria-label":e.label,"cmdk-dialog":"",className:o},Q.createElement(pie,{ref:t,...a}))))}),hKe=Q.forwardRef((e,t)=>Ou(n=>n.filtered.count===0)?Q.createElement(p.Primitive.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),mKe=Q.forwardRef((e,t)=>{let{progress:n,children:r,label:s="Loading...",...o}=e;return Q.createElement(p.Primitive.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":s},$_(e,i=>Q.createElement("div",{"aria-hidden":!0},i)))}),wo=Object.assign(pie,{List:dKe,Item:aKe,Input:uKe,Group:lKe,Separator:cKe,Dialog:fKe,Empty:hKe,Loading:mKe});function pKe(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function gKe(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function gie(e){let t=Q.useRef(e);return rh(()=>{t.current=e}),t}var rh=typeof window>"u"?Q.useEffect:Q.useLayoutEffect;function am(e){let t=Q.useRef();return t.current===void 0&&(t.current=e()),t}function Ou(e){let t=W5(),n=()=>e(t.snapshot());return Q.useSyncExternalStore(t.subscribe,n,n)}function bie(e,t,n,r=[]){let s=Q.useRef(),o=wv();return rh(()=>{var i;let a=(()=>{var u;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(u=d.current.textContent)==null?void 0:u.trim():s.current}})(),l=r.map(u=>u.trim());o.value(e,a,l),(i=t.current)==null||i.setAttribute(im,a),s.current=a}),s}var bKe=()=>{let[e,t]=Q.useState(),n=am(()=>new Map);return rh(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,s)=>{n.current.set(r,s),t({})}};function xKe(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function $_({asChild:e,children:t},n){return e&&Q.isValidElement(t)?Q.cloneElement(xKe(t),{ref:t.ref},n(t.props.children)):n(t)}var yKe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const z_=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo,{ref:n,className:p.cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));z_.displayName=wo.displayName;const Y5=Q.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[c.jsx(Xs,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(wo.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})]}));Y5.displayName=wo.Input.displayName;const B_=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo.List,{ref:n,className:p.cn("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));B_.displayName=wo.List.displayName;const V_=Q.forwardRef((e,t)=>c.jsx(wo.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));V_.displayName=wo.Empty.displayName;const H_=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo.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}));H_.displayName=wo.Group.displayName;const xie=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo.Separator,{ref:n,className:p.cn("-mx-1 h-px bg-border",e),...t}));xie.displayName=wo.Separator.displayName;const U_=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo.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}));U_.displayName=wo.Item.displayName;function vKe({hierarchy:e,sampleFieldReferences:t,onUpdateHierarchy:n,onDeleteHierarchy:r,onUpdateStep:s,onRemoveStep:o,onAddStep:i}){const[a,l]=S.useState(!1),{attributes:u,listeners:d,setNodeRef:f,transform:h,transition:m}=Ig({id:e.id,disabled:!1}),g={transform:di.Transform.toString(h),transition:m},b=e.steps.filter(x=>x.field).map(x=>x.field.id);return c.jsxs("div",{ref:f,style:g,className:"hierarchy-container relative rounded-lg border bg-background p-3 transition-shadow hover:shadow-md",children:[c.jsxs("div",{className:"mb-3 flex cursor-move items-center justify-between",...u,...d,children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("div",{onPointerDown:x=>x.stopPropagation(),onClick:x=>x.stopPropagation(),onKeyDown:x=>x.stopPropagation(),children:c.jsx(Oo,{value:e.label||"",onSave:x=>{n(e.id,{label:x})},placeholder:"Hierarchy Name",displayClassName:"font-medium",inputClassName:"font-medium"})})}),c.jsx("div",{className:"flex items-center gap-1",children:c.jsx(p.Button,{size:"sm",variant:"ghost",onClick:x=>{x.stopPropagation(),r(e.id)},onPointerDown:x=>x.stopPropagation(),children:c.jsx(rl,{className:"h-3 w-3"})})})]}),c.jsx(KGe,{hierarchy:e,onUpdateStep:s,onRemoveStep:o,onUpdateHierarchy:n}),c.jsx("div",{className:"mt-3 border-t pt-3","data-hierarchy-editing":!0,children:a?c.jsxs(z_,{className:"rounded-lg border",children:[c.jsx(Y5,{placeholder:"Search fields..."}),c.jsxs(B_,{children:[c.jsx(V_,{children:"No field found."}),c.jsx(H_,{children:t.filter(x=>!b.includes(x.id)).map(x=>c.jsx(U_,{value:x.label,onSelect:()=>{i(e.id,x.id),l(!1)},children:x.label},x.id))})]})]}):c.jsxs(p.Button,{type:"button",variant:"outline",size:"sm",onClick:x=>{x.preventDefault(),x.stopPropagation(),l(!0)},children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Add Step"]})})]})}function wKe({open:e,onOpenChange:t,drillHierarchies:n,onUpdateHierarchies:r,availableFields:s}){const[o,i]=S.useState(n);S.useEffect(()=>{e&&i(n)},[e,n]);const a=S.useMemo(()=>s.filter(w=>p.getDataType(w.dataType)==="string"),[s]),l=F_(Ep(jg),Ep(bv,{coordinateGetter:q5})),{createNewHierarchy:u,deleteHierarchy:d,updateHierarchy:f,addStepToHierarchy:h,removeStepFromHierarchy:m,updateStep:g,setDefaultHierarchy:b}=qGe(o,i,a),x=w=>{const{active:v,over:C}=w;if(v.id!==(C==null?void 0:C.id)){const N=o.findIndex(_=>_.id===v.id),k=o.findIndex(_=>_.id===(C==null?void 0:C.id));i(Eg(o,N,k))}},y=w=>{w||r(o),t(w)};return c.jsx(yo,{modal:!0,open:e,onOpenChange:y,children:c.jsx(Js,{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden p-0",onInteractOutside:w=>w.preventDefault(),onEscapeKeyDown:w=>w.preventDefault(),children:c.jsx(p.FocusScope,{trapped:!1,children:c.jsxs("div",{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden",children:[c.jsxs(Bi,{className:"border-b px-6 pb-4 pt-6",children:[c.jsx(eo,{children:"Manage Drill Hierarchies"}),c.jsx(Bo,{children:"Create multiple drill paths for different analysis scenarios. Define step-by-step navigation through your dimensions."})]}),c.jsx(p.ScrollArea,{className:"flex-1 px-6",children:c.jsxs("div",{className:"space-y-4 py-4",children:[o.length>0&&c.jsx("div",{className:"flex justify-end",children:c.jsxs(p.Button,{type:"button",size:"sm",onClick:w=>{w.preventDefault(),w.stopPropagation(),u()},children:[c.jsx(wr,{className:"mr-1 h-4 w-4"}),"Add Hierarchy"]})}),o.length>0?c.jsx(yv,{sensors:l,collisionDetection:gv,onDragEnd:x,children:c.jsx(vv,{items:o.map(w=>w.id),strategy:U5,children:c.jsx("div",{className:"space-y-4",children:o.map(w=>c.jsx(vKe,{hierarchy:w,sampleFieldReferences:a,onUpdateHierarchy:f,onDeleteHierarchy:d,onSetDefaultHierarchy:b,onUpdateStep:g,onRemoveStep:m,onAddStep:h},w.id))})})}):c.jsxs("div",{className:"rounded-lg border border-dashed p-8 text-center",children:[c.jsx("p",{className:"mb-2 text-sm text-muted-foreground",children:"No hierarchies configured yet"}),c.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:"Create your first hierarchy to enable drill-down interactions"}),c.jsxs(p.Button,{type:"button",size:"sm",variant:"outline",onClick:w=>{w.preventDefault(),w.stopPropagation(),u()},children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Create First Hierarchy"]})]})]})}),c.jsx("div",{className:"flex justify-end gap-2 border-t px-6 py-4",children:c.jsx(p.Button,{variant:"outline",onClick:()=>y(!1),children:"Done"})})]})})})})}function Oy(e){switch(e){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];case"hour":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:00 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:00 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"minute":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:00 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"second":return[{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}}function SKe({interaction:e,onUpdate:t,card:n,availableFields:r,onUpdateHierarchies:s,onManageHierarchies:o}){var T;const[i,a]=S.useState(!1),[l,u]=S.useState(!1),[d,f]=S.useState(null),[h,m]=S.useState(!1),[g,b]=S.useState({}),x=S.useMemo(()=>{var D;return((D=n.interactionConfig)==null?void 0:D.drillHierarchies)||[]},[(T=n.interactionConfig)==null?void 0:T.drillHierarchies]),y=S.useMemo(()=>{var R,H;const D=[],A=e.trigger;if(!A)return D;let P;if(A.type==="attribute"){const z=r.find(W=>W.id===A.field.id);z&&(z.dataType==="date"||z.dataType==="timestamp")&&(P=z)}else if(A.type==="metric"){const z=(H=(R=n.config)==null?void 0:R.groupByColumns)==null?void 0:H.find(U=>U.dataType==="date"||U.dataType==="timestamp");z&&(P=z)}if(P&&p.shouldAutoGenerateDateHierarchy(P,x)){const z=p.generateDateHierarchy(P);D.push(z)}return D},[r,x,e.trigger,n.config]),w=S.useMemo(()=>[...x,...y],[x,y]),v=w.find(D=>D.id===e.hierarchyId);Q.useEffect(()=>{i&&v&&v.type==="date"?f(v.id):i||f(null)},[i,v]);const C=D=>{if(y.some(P=>P.id===D)&&s){const P=y.find(R=>R.id===D);P&&s([...x,P])}t({...e,hierarchyId:D}),a(!1)},N=()=>{a(!1),u(!0),o&&o()},k=D=>{s&&s(D)},_=D=>D.steps.map(P=>P.field.label||P.field.name).join(" → "),j=D=>D&&D.charAt(0).toUpperCase()+D.slice(1),I=(D,A,P)=>{const R=[...D.steps];R[A]={...R[A],field:{...R[A].field,dateFormat:P,customFormat:P==="custom"?g[A]||"":void 0}};const H={...D,steps:R};if(s){const z=x.findIndex(U=>U.id===D.id);if(z>=0){const U=[...x];U[z]=H,s(U)}else s([...x,H])}},E=(D,A,P)=>{b(z=>({...z,[A]:P}));const R=[...D.steps];R[A]={...R[A],field:{...R[A].field,dateFormat:"custom",customFormat:P}};const H={...D,steps:R};if(s){const z=x.findIndex(U=>U.id===D.id);if(z>=0){const U=[...x];U[z]=H,s(U)}else s([...x,H])}};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Choose hierarchy"}),c.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Select which hierarchy to drill through when this interaction triggers"}),w.length>0?c.jsxs(c.Fragment,{children:[c.jsxs(p.Popover,{open:i,onOpenChange:a,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsxs(p.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[c.jsx("div",{className:"flex flex-1 flex-col items-start text-left",children:v?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{className:"font-medium",children:v.label||"Unnamed Hierarchy"})}),c.jsx("span",{className:"text-xs text-muted-foreground",children:_(v)})]}):c.jsx("span",{className:"text-muted-foreground",children:"Select hierarchy..."})}),c.jsxs("div",{className:"flex items-center gap-2",children:[v&&v.type==="date"&&c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:D=>{D.stopPropagation(),m(!h)},children:c.jsx(SR,{className:"h-3 w-3"})}),c.jsx(vr,{className:"h-4 w-4 shrink-0 opacity-50"})]})]})}),c.jsxs(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:[c.jsxs("div",{className:"flex items-center justify-between border-b p-3",children:[c.jsx("span",{className:"text-sm font-medium",children:"Select Hierarchy"}),c.jsxs(p.Button,{variant:"ghost",size:"sm",onClick:N,children:[c.jsx(wr,{className:"mr-1.5 h-3.5 w-3.5"}),"Create new"]})]}),c.jsxs("div",{className:"p-2",children:[y.length>0&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-3 py-2",children:c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"AUTO-GENERATED"})}),y.map(D=>c.jsx("div",{className:`cursor-pointer rounded-md p-3 hover:bg-muted ${e.hierarchyId===D.id?"bg-muted":""}`,onClick:()=>C(D.id),children:c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{className:"text-sm font-medium",children:D.label||"Unnamed Hierarchy"})}),c.jsx("div",{className:"text-xs text-muted-foreground",children:_(D)})]})},D.id))]}),x.length>0&&c.jsxs(c.Fragment,{children:[y.length>0&&c.jsx("div",{className:"my-2 border-t"}),x.map(D=>c.jsx("div",{className:`cursor-pointer rounded-md p-3 hover:bg-muted ${e.hierarchyId===D.id?"bg-muted":""}`,onClick:()=>C(D.id),children:c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{className:"text-sm font-medium",children:D.label||"Unnamed Hierarchy"})}),c.jsx("div",{className:"text-xs text-muted-foreground",children:_(D)})]})},D.id))]})]})]})]}),v&&v.type==="date"&&h&&c.jsxs("div",{className:"mt-3 space-y-3 rounded-md border border-border p-3",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Customize Date Formats"}),c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-6 text-xs",onClick:()=>m(!1),children:"Close"})]}),v.steps.map((D,A)=>{var z;const P=D.field.granularity;if(!P)return null;const R=Oy(P),H=D.field.dateFormat||((z=R[0])==null?void 0:z.value);return c.jsxs("div",{className:"space-y-1",children:[c.jsx(p.Label,{className:"text-xs font-medium text-muted-foreground",children:D.field.label||j(P)}),c.jsxs(p.Select,{value:H,onValueChange:U=>{I(v,A,U)},children:[c.jsx(p.SelectTrigger,{className:"h-8 text-xs",children:c.jsx(p.SelectValue,{})}),c.jsx(p.SelectContent,{children:R.map(U=>c.jsx(p.SelectItem,{value:U.value,className:"text-xs",children:U.label},U.value))})]}),H==="custom"&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx(p.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD)",value:D.field.customFormat||g[A]||"",onChange:U=>{E(v,A,U.target.value)},className:"h-8 text-xs"}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Common tokens: YYYY (year), MM (month), DD (day), HH (hour), mm (minute)"})]})]},A)})]})]}):c.jsxs("div",{className:"rounded-md border border-dashed p-6 text-center",children:[c.jsx("p",{className:"mb-2 text-sm text-muted-foreground",children:"No hierarchies configured"}),c.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:"Create a hierarchy to define your drill path"}),c.jsxs(p.Button,{variant:"outline",size:"sm",onClick:N,children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Create hierarchy"]})]})]}),c.jsx(wKe,{open:l,onOpenChange:u,drillHierarchies:x,onUpdateHierarchies:k,availableFields:r})]})}function CKe({fields:e,selectedFieldIds:t,onSelectionChange:n,searchPlaceholder:r="Search fields...",className:s=""}){const[o,i]=S.useState(""),a=e.filter(d=>d.label.toLowerCase().includes(o.toLowerCase())||d.qualifiedEntityName&&d.qualifiedEntityName.toLowerCase().includes(o.toLowerCase())),l=()=>{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 c.jsxs("div",{className:`space-y-2 ${s}`,children:[c.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[c.jsx(p.Input,{placeholder:r,value:o,onChange:d=>i(d.target.value),className:"flex-1"}),c.jsxs("span",{className:"text-xs text-muted-foreground",children:[a.length," fields"]})]}),c.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[c.jsx(p.Button,{size:"sm",variant:"outline",onClick:l,children:"Select All"}),c.jsx(p.Button,{size:"sm",variant:"outline",onClick:u,children:"Deselect All"}),c.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," selected"]})]}),c.jsx("div",{className:"grid max-h-32 grid-cols-2 gap-2 overflow-y-auto rounded border p-2",children:a.map(d=>c.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded p-2 text-xs hover:bg-muted/50",children:[c.jsx(En,{checked:t.includes(d.id),onCheckedChange:f=>{n(f?[...t,d.id]:t.filter(h=>h!==d.id))}}),c.jsx("span",{className:"font-medium",children:d.label})]},d.id))}),o&&a.length===0&&c.jsxs("div",{className:"py-4 text-center text-sm text-muted-foreground",children:['No fields found matching "',o,'"']})]})}const NKe=e=>["string","boolean"].includes(p.getDataType(e.dataType));function kKe({interaction:e,availableFields:t,onUpdate:n}){var i;const r=t.filter(NKe),s=((i=e.availableFields)==null?void 0:i.map(a=>a.id))||[],o=a=>{const l=r.filter(u=>a.includes(u.id));n({...e,availableFields:l})};return c.jsx("div",{className:"space-y-4",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{children:"Available dimensions"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose which fields users can explore dynamically"}),c.jsx(CKe,{fields:r,selectedFieldIds:s,onSelectionChange:o,searchPlaceholder:"Search fields..."}),s.length===0&&c.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ Please select at least one field"})]})})}function _Ke({value:e,onChange:t}){const[n,r]=S.useState(!1),[s,o]=S.useState(""),[i,a]=S.useState("all"),{currentUser:l}=zi(),{data:u,isLoading:d}=LR($r.DASHBOARD,s),f=(u==null?void 0:u.dashboards)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(l==null?void 0:l.id):!0),m=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),o("")};return c.jsxs(p.Popover,{open:n,onOpenChange:r,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsx(p.Button,{variant:"outline",className:p.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:m?c.jsx("span",{className:"truncate",children:m.title}):"Choose dashboard..."})}),c.jsx(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:c.jsxs(p.Tabs,{value:i,onValueChange:b=>a(b),children:[c.jsx("div",{className:"p-3 border-b",children:c.jsxs("div",{className:"relative",children:[c.jsx(Xs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(p.Input,{placeholder:"Search all dashboards...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]})}),c.jsxs(p.TabsList,{className:"w-full justify-start rounded-none border-b bg-transparent p-0",children:[c.jsx(p.TabsTrigger,{value:"me",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"created by me"}),c.jsx(p.TabsTrigger,{value:"all",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"all"})]}),c.jsx(p.TabsContent,{value:i,className:"mt-0",children:c.jsx(p.ScrollArea,{className:"h-[300px]",children:d?c.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading dashboards..."}):h.length===0?c.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:s?`No dashboards found matching "${s}"`:i==="me"?"No dashboards created by you":"No dashboards available"}):c.jsx("div",{className:"p-2",children:h.map(b=>c.jsxs("button",{onClick:()=>g(b),className:p.cn("w-full flex items-start gap-3 p-3 rounded-md hover:bg-muted/50 transition-colors text-left",e===b.id&&"bg-muted"),children:[c.jsx(ep,{className:"h-5 w-5 mt-0.5 text-muted-foreground flex-shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"font-medium text-sm truncate",children:b.title}),c.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:jKe(b.createdAt)})]})]},b.id))})})})]})})]})}function jKe(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(),l=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${l}`}const s=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),o=t.getDate();return`${s} ${o}`}function EKe({interaction:e,onUpdate:t}){return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Target dashboard"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select which dashboard to navigate to when this interaction triggers"}),c.jsx(_Ke,{value:e.targetDashboardId,onChange:(n,r)=>{const s={...e,targetDashboardId:n};!e.label&&r&&(s.label=r),t(s)}})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Propagate Filters"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose what filters to pass to the target dashboard"}),c.jsxs(p.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsxs(p.SelectValue,{placeholder:"Choose context mode...",children:[e.contextMode==="interactionFilters"&&"Interaction Filters",(e.contextMode==="full"||!e.contextMode)&&"All Filters",e.contextMode==="none"&&"None"]})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"interactionFilters",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"Interaction Filters"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass only the clicked element as a filter"})]})}),c.jsx(p.SelectItem,{value:"full",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"All Filters"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass current dashboard filters + clicked element"})]})}),c.jsx(p.SelectItem,{value:"none",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"None"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Navigate without passing any filters"})]})})]})]})]}),!e.targetDashboardId&&c.jsx("div",{className:"rounded-md bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3",children:c.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"⚠ Please select a target dashboard to complete this configuration"})}),e.targetDashboardId&&c.jsx("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:c.jsx("p",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Dashboard drill-through configured successfully"})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(p.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:jh(e.mode)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function IKe({value:e,onChange:t}){const[n,r]=S.useState(!1),[s,o]=S.useState(""),[i,a]=S.useState("all"),{currentUser:l}=zi(),{data:u,isLoading:d}=LR($r.VISUAL,s),f=(u==null?void 0:u.visuals)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(l==null?void 0:l.id):!0),m=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),o("")};return c.jsxs(p.Popover,{open:n,onOpenChange:r,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsx(p.Button,{variant:"outline",className:p.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:m?c.jsx("span",{className:"truncate",children:m.title}):"Choose insight..."})}),c.jsx(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:c.jsxs(p.Tabs,{value:i,onValueChange:b=>a(b),children:[c.jsx("div",{className:"p-3 border-b",children:c.jsxs("div",{className:"relative",children:[c.jsx(Xs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(p.Input,{placeholder:"Search all insights...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]})}),c.jsxs(p.TabsList,{className:"w-full justify-start rounded-none border-b bg-transparent p-0",children:[c.jsx(p.TabsTrigger,{value:"me",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"created by me"}),c.jsx(p.TabsTrigger,{value:"all",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"all"})]}),c.jsx(p.TabsContent,{value:i,className:"mt-0",children:c.jsx(p.ScrollArea,{className:"h-[300px]",children:d?c.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading insights..."}):h.length===0?c.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:s?`No insights found matching "${s}"`:i==="me"?"No insights created by you":"No insights available"}):c.jsx("div",{className:"p-2",children:h.map(b=>c.jsxs("button",{onClick:()=>g(b),className:p.cn("w-full flex items-start gap-3 p-3 rounded-md hover:bg-muted/50 transition-colors text-left",e===b.id&&"bg-muted"),children:[c.jsx(p.ChartColumn,{className:"h-5 w-5 mt-0.5 text-muted-foreground flex-shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"font-medium text-sm truncate",children:b.title}),c.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:TKe(b.createdAt)})]})]},b.id))})})})]})})]})}function TKe(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(),l=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${l}`}const s=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),o=t.getDate();return`${s} ${o}`}function DKe({interaction:e,onUpdate:t}){return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Target insight"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select the saved insight to navigate to"}),c.jsx(IKe,{value:e.targetInsightId,onChange:(n,r)=>{const s={...e,targetInsightId:n};!e.label&&r&&(s.label=r),t(s)}})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Propagate Filters"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose what filters to pass to the insight"}),c.jsxs(p.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsxs(p.SelectValue,{placeholder:"Choose context mode...",children:[e.contextMode==="interactionFilters"&&"Interaction Filters",(e.contextMode==="full"||!e.contextMode)&&"All Filters",e.contextMode==="none"&&"None"]})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"interactionFilters",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"Interaction Filters"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass only the clicked element as a filter"})]})}),c.jsx(p.SelectItem,{value:"full",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"All Filters"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass all current filters and selections"})]})}),c.jsx(p.SelectItem,{value:"none",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"None"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Open insight without any filters"})]})})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Display mode"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose how the insight should be displayed"}),c.jsxs(p.Select,{value:e.displayMode||"modal",onValueChange:n=>t({...e,displayMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsx(p.SelectValue,{placeholder:"Choose display mode..."})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"modal",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"Open in modal"})})}),c.jsx(p.SelectItem,{value:"replace-card",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"Replace the card"})})})]})]})]}),!e.targetInsightId&&c.jsx("div",{className:"rounded-md bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3",children:c.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"⚠ Please enter a target insight ID to complete this configuration"})}),e.targetInsightId&&c.jsx("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:c.jsx("p",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Insight drill-through configured successfully"})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(p.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:jh(e.mode)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function MKe(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 AKe(){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 RKe(e,t){const n=`{{${t}}}`;return e.includes(n)}function FKe(e,t){return t.filter(n=>RKe(e,n.id))}function PKe(e,t,n){const r=`{{${t}}}`,s=e.slice(0,n)+r+e.slice(n),o=n+r.length;return{newTemplate:s,newCursorPosition:o}}function OKe(e,t){let n=e;return t.forEach(r=>{const s=`{{${r.id}}}`;let o;if(r.category==="identifier")o=`${r.id.toUpperCase()}-abc123`;else{const i=r.label.toLowerCase();i.includes("name")?o="Example Name":i.includes("region")||i.includes("location")?o="California":i.includes("id")?o="ID-12345":i.includes("category")?o="Category A":o="Sample Value"}n=n.replace(new RegExp(s,"g"),o)}),n}function LKe({open:e,onOpenChange:t,interaction:n,availableFields:r,onSave:s}){const[o,i]=S.useState(n.urlTemplate||""),[a,l]=S.useState(0),[u,d]=S.useState(n.encodeParameters!==!1),[f,h]=S.useState(n.label||""),m=S.useRef(null);S.useEffect(()=>{e&&(i(n.urlTemplate||""),d(n.encodeParameters!==!1),h(n.label||""),l(0))},[e,n.urlTemplate,n.encodeParameters,n.label]);const g=MKe(r),b=AKe(),x=[...g,...b],y=FKe(o,x),w=p.validateURLTemplate(o),v=o&&w.valid?OKe(o,y):"",C=E=>{i(E.target.value),l(E.target.selectionStart)},N=E=>{const T=E.target;l(T.selectionStart)},k=E=>{const T=E.target;l(T.selectionStart)},_=E=>{const{newTemplate:T,newCursorPosition:D}=PKe(o,E.id,a);i(T),l(D),m.current&&(m.current.focus(),setTimeout(()=>{m.current&&m.current.setSelectionRange(D,D)},0))},j=()=>{w.valid&&(s({...n,urlTemplate:o,parameters:y,encodeParameters:u,label:f}),t(!1))},I=()=>{t(!1)};return c.jsx(yo,{open:e,onOpenChange:t,children:c.jsxs(Js,{className:"max-h-[90vh] max-w-5xl overflow-y-auto",onOpenAutoFocus:E=>{E.preventDefault(),setTimeout(()=>{var T;(T=m.current)==null||T.focus()},0)},children:[c.jsxs(Bi,{children:[c.jsx(eo,{children:"Configure Drill to URL"}),c.jsx(Bo,{children:"Build a custom URL with dynamic parameters that will open when users click on chart elements."})]}),c.jsxs("div",{className:"flex flex-col gap-6 py-4",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[c.jsxs("div",{className:"flex flex-col gap-4",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(p.Label,{htmlFor:"url-template",children:"URL"}),c.jsx(p.TooltipProvider,{children:c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx(p.Info,{className:"h-4 w-4 text-muted-foreground"})}),c.jsx(p.TooltipContent,{children:c.jsx("p",{className:"max-w-xs text-xs",children:"Enter your URL and click parameters from the right panel to insert them. Parameters will be replaced with actual values when the URL is opened."})})]})})]}),c.jsx(hh,{ref:m,id:"url-template",value:o,onChange:C,onClick:N,onKeyUp:k,placeholder:"https://example.com/product/{{product_id}}?region={{region}}",className:"min-h-[200px] font-mono text-sm"}),!w.valid&&o&&c.jsx("div",{className:"rounded-lg border border-destructive bg-destructive/10 p-3",children:c.jsx("div",{className:"text-sm text-destructive",children:w.errors.map((E,T)=>c.jsx("div",{children:E},T))})}),v&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-xs text-muted-foreground",children:"Preview:"}),c.jsx("div",{className:"rounded-md bg-muted p-3",children:c.jsx("p",{className:"break-all font-mono text-xs",children:v})})]})]}),c.jsxs("div",{className:"flex flex-col gap-4",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(p.Label,{children:"Parameters"}),c.jsx(p.TooltipProvider,{children:c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx(p.Info,{className:"h-4 w-4 text-muted-foreground"})}),c.jsx(p.TooltipContent,{children:c.jsx("p",{className:"max-w-xs text-xs",children:"Click any parameter to insert it into your URL at the cursor position. Attributes come from your chart data, Identifiers are system values."})})]})})]}),c.jsxs("div",{className:"flex flex-col gap-6 rounded-lg border p-4",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Attributes"}),c.jsxs("div",{className:"space-y-1",children:[g.map(E=>c.jsx(D9,{parameter:E,isUsed:y.some(T=>T.id===E.id),onClick:()=>_(E)},E.id)),g.length===0&&c.jsx("p",{className:"text-sm text-muted-foreground",children:"No attributes available"})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Identifiers"}),c.jsx("div",{className:"space-y-1",children:b.map(E=>c.jsx(D9,{parameter:E,isUsed:y.some(T=>T.id===E.id),onClick:()=>_(E)},E.id))})]})]})]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(En,{id:"encode-params",checked:u,onCheckedChange:E=>d(E===!0)}),c.jsx(p.Label,{htmlFor:"encode-params",className:"cursor-pointer text-sm font-normal",children:"URL encode parameters"}),c.jsx(p.TooltipProvider,{children:c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx(p.Info,{className:"h-4 w-4 text-muted-foreground"})}),c.jsx(p.TooltipContent,{children:c.jsx("p",{className:"max-w-xs text-xs",children:"Recommended. Encodes special characters in parameter values to ensure valid URLs (e.g., spaces become %20)."})})]})})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(p.TooltipProvider,{children:c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx(p.Info,{className:"h-4 w-4 text-muted-foreground"})}),c.jsx(p.TooltipContent,{children:c.jsx("p",{className:"max-w-xs text-xs",children:"How this interaction appears when multiple actions are available"})})]})})]}),c.jsx(p.Input,{value:f,onChange:E=>h(E.target.value),placeholder:jh("drillToURL")})]}),c.jsxs("div",{className:"flex items-start gap-2 rounded-lg border bg-muted/50 p-3",children:[c.jsx(p.Info,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"URLs will always open in a new browser tab when clicked."})]})]}),c.jsxs(vc,{children:[c.jsx(p.Button,{variant:"outline",onClick:I,children:"Cancel"}),c.jsx(p.Button,{onClick:j,disabled:!w.valid,children:"Save"})]})]})})}function D9({parameter:e,isUsed:t,onClick:n}){var o,i;const r=e.category==="attribute"?"🏷️":"#",s=((o=e.field)==null?void 0:o.qualifiedFieldName)||((i=e.field)==null?void 0:i.name);return c.jsxs(p.Button,{type:"button",variant:"ghost",className:"h-auto w-full justify-start gap-2 px-3 py-2 font-normal hover:bg-accent",onClick:n,children:[c.jsx("span",{className:"text-base",children:r}),c.jsxs("div",{className:"flex flex-1 flex-col items-start gap-0.5",children:[c.jsx("span",{className:"text-sm",children:e.label}),s&&c.jsx("span",{className:"text-xs text-muted-foreground",children:s})]}),t&&c.jsx(rs,{variant:"secondary",className:"ml-auto gap-1",children:c.jsx(p.Check,{className:"h-3 w-3"})})]})}function $Ke({interaction:e,availableFields:t,onUpdate:n}){const[r,s]=S.useState(!1),o=!!e.urlTemplate;return c.jsxs("div",{className:"flex flex-col gap-4",children:[o?c.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border p-4",children:[c.jsxs("div",{className:"flex items-start justify-between gap-4",children:[c.jsxs("div",{className:"flex-1 space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Jm,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"text-sm font-medium",children:"URL Template"})]}),c.jsx("div",{className:"rounded-md bg-muted p-3",children:c.jsx("p",{className:"break-all font-mono text-xs",children:e.urlTemplate})})]}),c.jsxs(p.Button,{variant:"outline",size:"sm",onClick:()=>s(!0),children:[c.jsx(CR,{className:"mr-2 h-4 w-4"}),"Edit"]})]}),e.parameters&&e.parameters.length>0&&c.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.parameters.length," parameter",e.parameters.length!==1?"s":""," configured"]}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["URL encoding:"," ",e.encodeParameters!==!1?"enabled":"disabled"]})]}):c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border border-dashed p-8",children:[c.jsx(Jm,{className:"h-8 w-8 text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"No URL configured"}),c.jsx(p.Button,{variant:"outline",size:"sm",onClick:()=>s(!0),children:"Add Custom URL"})]}),c.jsx(LKe,{open:r,onOpenChange:s,interaction:e,availableFields:t,onSave:n})]})}function zKe({interaction:e,onUpdate:t}){return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Fetch mode"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose when to load the detailed data"}),c.jsxs(p.Select,{value:e.fetchMode||"lazy",onValueChange:n=>t({...e,fetchMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsx(p.SelectValue,{placeholder:"Choose fetch mode..."})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"lazy",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"Lazy loading"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Fetch data only when user clicks"})]})}),c.jsx(p.SelectItem,{value:"preloaded",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"Preloaded"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Fetch all data when dashboard loads"})]})})]})]}),c.jsxs("div",{className:"rounded-md bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 p-3 flex gap-2",children:[c.jsx(p.Info,{className:"h-4 w-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0"}),c.jsx("div",{className:"text-xs text-blue-800 dark:text-blue-200",children:e.fetchMode==="lazy"?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"font-medium",children:"Lazy loading"}),c.jsx("div",{className:"mt-1",children:"Data is fetched on-demand when the user clicks. Best for large datasets or when detailed data isn't always needed."})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"font-medium",children:"Preloaded"}),c.jsx("div",{className:"mt-1",children:"Data is fetched when the dashboard loads. Best for small datasets or when instant drill-down is required."})]})})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Record limit"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Maximum number of detailed records to show (0 for unlimited)"}),c.jsx(p.Input,{type:"number",min:"0",placeholder:"100",value:e.inlineLimit??100,onChange:n=>{const r=parseInt(n.target.value)||0;t({...e,inlineLimit:r})}})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Display mode"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"How to display the detailed records"}),c.jsxs(p.Select,{value:e.displayMode||"table",onValueChange:n=>t({...e,displayMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsx(p.SelectValue,{placeholder:"Choose display mode..."})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"table",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"Table view"})})}),c.jsx(p.SelectItem,{value:"list",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"List view"})})}),c.jsx(p.SelectItem,{value:"cards",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"Card view"})})})]})]})]}),c.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 bg-background",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Show in modal"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Display detailed records in a modal overlay"})]}),c.jsx(p.Switch,{checked:e.showInModal??!1,onCheckedChange:n=>t({...e,showInModal:n})})]}),c.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 bg-background",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Allow export"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Enable users to export the detailed records"})]}),c.jsx(p.Switch,{checked:e.allowExport??!0,onCheckedChange:n=>t({...e,allowExport:n})})]}),c.jsxs("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:[c.jsx("div",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Inline drill configured successfully"}),c.jsxs("div",{className:"mt-2 space-y-1 text-xs text-green-700 dark:text-green-300",children:[c.jsxs("div",{children:["Mode: ",e.fetchMode==="lazy"?"Lazy loading":"Preloaded"]}),c.jsxs("div",{children:["Limit: ",e.inlineLimit===0?"Unlimited":`${e.inlineLimit} records`]}),c.jsxs("div",{children:["Display: ",e.displayMode==="table"?"Table view":e.displayMode==="list"?"List view":"Card view"]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(p.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:jh(e.mode)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function BKe({interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i,onRemove:a}){const l=e.trigger!==void 0,u=e.mode!==void 0,d=l&&u,[f,h]=S.useState(!d),m=()=>{var y;if(!l)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||jh(e.mode);return`${b} → ${x}`},g=u?XC(e.mode):null;return c.jsxs(Xm,{className:"relative p-0",children:[c.jsx(p.Button,{variant:"ghost",size:"sm",className:"absolute right-2 top-2 z-10 h-8 w-8 p-0",onClick:a,"aria-label":"Remove interaction",children:c.jsx(p.X,{className:"h-3 w-3"})}),c.jsxs(mc,{open:f,onOpenChange:h,children:[c.jsx(pc,{asChild:!0,children:c.jsxs(p.Button,{variant:"ghost",className:"h-auto w-full justify-between p-4 pr-12 hover:bg-muted/50",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[g&&c.jsx(g,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"text-left text-sm font-medium",children:m()})]}),f?c.jsx(wR,{className:"h-3 w-3 flex-shrink-0"}):c.jsx(PN,{className:"h-3 w-3 flex-shrink-0"})]})}),c.jsx(gc,{children:c.jsxs("div",{className:"space-y-6 border-t p-6",children:[c.jsx("div",{className:"space-y-3",children:l?c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["When I click on"," ",c.jsx("span",{className:"text-muted-foreground",children:"(value of)"})]}),e.trigger&&c.jsxs("div",{className:"inline-flex cursor-pointer items-center gap-2 rounded-md border bg-background px-3 py-2 hover:bg-muted/50",onClick:()=>{i({...e,trigger:void 0})},children:[QC(e.trigger.field.dataType),c.jsx("span",{className:"text-sm font-medium",children:e.trigger.field.label})]})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-sm font-medium",children:"When I click on"}),c.jsx(tYe,{value:e.trigger,onChange:b=>{i({...e,trigger:b})},metrics:t,attributes:n})]})}),l&&c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-sm font-medium",children:"I want to"}),c.jsx(nYe,{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}}})]})}),l&&u&&c.jsxs(c.Fragment,{children:[c.jsx(p.Separator,{}),c.jsx(VKe,{interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i})]})]})})]})]})}function VKe({interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i}){switch(e.mode){case"clickFilter":return c.jsx(rYe,{interaction:e,onUpdate:a=>i(a)});case"drillDown":return c.jsx(SKe,{interaction:e,onUpdate:a=>i(a),card:s,availableFields:r,onUpdateHierarchies:o});case"dynamicDrill":return c.jsx(kKe,{interaction:e,onUpdate:a=>i(a),availableFields:r});case"drillThrough":return c.jsx(EKe,{interaction:e,onUpdate:a=>i(a)});case"drillToDetail":return c.jsx(DKe,{interaction:e,onUpdate:a=>i(a)});case"drillToURL":return c.jsx($Ke,{interaction:e,availableFields:[...t,...n],onUpdate:a=>i(a)});case"inlineDrill":return c.jsx(zKe,{interaction:e,onUpdate:a=>i(a)});default:return c.jsx("div",{className:"text-sm text-muted-foreground",children:"Unknown interaction type"})}}function HKe({interactions:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onChange:i}){const[a,l]=S.useState(null),u=()=>{const h=Jqe().id,m={id:h};i([...e,m]),l(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)&&l(null)};return c.jsxs("div",{className:"space-y-4",children:[e.length>0?c.jsx("div",{className:"space-y-3",children:e.map((h,m)=>c.jsx(BKe,{interaction:h,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:g=>d(m,g),onRemove:()=>f(m)},h.id||m))}):c.jsx("div",{className:"border rounded-lg p-8 text-center bg-muted/30",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"No interactions configured"}),c.jsx("div",{className:"text-xs text-muted-foreground",children:'Click "Add Interaction" to create your first interaction'}),c.jsx("div",{className:"pt-2",children:c.jsxs(p.Button,{onClick:u,size:"sm",variant:"outline",children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Add First Interaction"]})})]})}),e.length>0&&c.jsx("div",{className:"flex justify-start pt-2",children:c.jsxs(p.Button,{onClick:u,size:"sm",variant:"outline",children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Add Interaction"]})})]})}const UKe=[],qKe=[],WKe=[];function NT(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function YKe(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 G5(e){var C;const{tokenProps:t}=mt(),n=p.useDashboardStore(N=>N.authToken)||e,{selectedConnection:r,hasSchemaSupport:s}=gK(e),o=p.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.connectionId}),i=p.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.semanticDomainId}),a=p.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.selectedEntities}),l=S.useMemo(()=>(a==null?void 0:a.filter(N=>N.type==="model"))||UKe,[a]),u=S.useMemo(()=>(a==null?void 0:a.filter(N=>p.DATABASE_ENTITY_TYPES.includes(N.type)))||qKe,[a]),d=S.useMemo(()=>(a==null?void 0:a.filter(N=>N.type==="dataset"))||WKe,[a]);function f(N){var k;if(N.type==="dataset")return!!o&&!!N.domainId&&!!N.name;if(N.type==="model")return!!o&&!!N.id;if(p.DATABASE_ENTITY_TYPES.includes(N.type)){const _=((k=r==null?void 0:r.capabilities)==null?void 0:k.path)||[],j=_.includes("database"),I=_.includes("schema")||s;return!(!o||!N.name||j&&!N.database||I&&!N.schema)}return!1}const h=[...l,...u,...d],m=Ap({queries:h.map(N=>{let k={};return N.type==="model"?k=NT({connection_id:o,datamodel_id:N.id,database_name:"",schema_name:"",table_name:""}):N.type==="dataset"?k=NT({connection_id:N.connectionId,domain_id:N.domainId,dataset_name:N.name,database_name:N.database,schema_name:N.schema,table_name:N.table}):k=NT({connection_id:o,datamodel_id:"",database_name:N.database,schema_name:N.schema,table_name:N.name}),{queryKey:["columns",o,N,i||null],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",k),enabled:!!o&&f(N)}})}),g=m.some(N=>N.isPending&&N.fetchStatus==="fetching"),b=m.some(N=>N.isError),x=(C=m.find(N=>N.isError))==null?void 0:C.error,y=m.map((N,k)=>{var D,A;const _=h[k],j=((D=N.data)==null?void 0:D.columns)||[],I=_.type==="dataset"?(A=j.find(P=>P.entityName))==null?void 0:A.entityName:void 0,E=I||_.name,T=p.getQualifiedEntityName(_.type==="dataset"&&I?{..._,name:I}:_);return{entityId:_.id||_.name,entityType:_.type,entityName:E,label:_.label,description:_.description,qualifiedEntityName:T,columns:j.map(P=>{const R=_.type==="dataset"?P.entityName||E:_.name,H=P.qualifiedEntityName||(_.type==="dataset"&&R?p.getQualifiedEntityName({..._,name:R}):T);return{id:`${R}-${P.column_name}`,name:P.column_name,qualifiedFieldName:P.qualifiedFieldName||P.column_name,dataType:P.data_type,label:P.label||p.toLabel(P.column_name),description:P.description||"",qualifiedEntityName:H,entityId:P.entityId||_.id||_.id||R,entityName:R,entityType:P.entityType||_.type,role:P.role,expression:P.expression,calculatedFormula:P.calculatedFormula,format:p.fromSemanticFormat(P.format),aggregate:P.aggregate}})}}).filter(N=>{var k;return((k=N==null?void 0:N.columns)==null?void 0:k.length)>0})||[],w=m.flatMap(N=>{var k;return((k=N.data)==null?void 0:k.calculatedFields)||[]}).map(N=>({...N,id:p.getStableDomainCalculatedFieldId({...N}),fieldScope:"domain"}));if(w.length>0){const N=new Map;w.forEach(k=>{const _=p.getStableDomainCalculatedFieldId(k);N.has(_)||N.set(_,k)}),y.unshift({entityId:p.CALCULATED_FIELDS_GROUP_ID,entityType:"dataset",entityName:p.CALCULATED_FIELDS_GROUP_NAME,label:"Calculated Fields",description:"Domain-level calculated metrics and dimensions",qualifiedEntityName:p.CALCULATED_FIELDS_GROUP_NAME,columns:Array.from(N.values())})}const v=YKe(y);return{columnGroups:y,columns:v,isLoading:g,hasError:b,error:x,refetch:async()=>{await Promise.all(m.map(N=>N.refetch()))}}}function GKe(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 oN(e){return Array.isArray(e)?e.map(t=>oN(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]=oN(r),t),{}):e}function kT(e,t){return JSON.stringify(oN(e))===JSON.stringify(oN(t))}function KKe(){var B,V,F,q,G,X,J,fe,ue;const{open:e,frameId:t,cardId:n,closePopover:r,anchorPosition:s}=IF(),{authToken:o,tokenProps:i}=mt(),a=qr(),{updateCurrentDashboardCard:l,updateFrameCard:u}=p.useDashboardActions(),{setCard:d}=p.useEditorActions(),f=p.useDashboardStore(pe=>pe.dashboard),h=((B=f==null?void 0:f.sheets)==null?void 0:B.flatMap(pe=>pe.frames||[]).find(pe=>(pe==null?void 0:pe.id)===t))||null,m=h&&n?h.cards.find(pe=>pe.id===n):null,g=!!(h!=null&&h.visualId&&m),b=HN((h==null?void 0:h.visualId)||"",{enabled:e&&g&&!!(o!=null&&o.accessToken)&&!!(i!=null&&i.apiServiceUrl)}),x=((V=b.data)==null?void 0:V.frameObject)||((q=(F=b.data)==null?void 0:F.visual)==null?void 0:q.frameObject),y=S.useMemo(()=>GKe(x),[x]),w=((G=b.data)==null?void 0:G.lastModified)||((J=(X=b.data)==null?void 0:X.visual)==null?void 0:J.lastModified),v=S.useMemo(()=>{if(!m||!h||!y)return null;const pe=m.linkedSourceCardId&&y.cards.find(ie=>ie.id===m.linkedSourceCardId);if(pe)return pe;const ye=h.cards.findIndex(ie=>ie.id===m.id);return ye>=0&&y.cards[ye]||null},[m,h,y]),C=S.useMemo(()=>{const pe=new Map;return!h||!y||h.cards.forEach((ye,ie)=>{var se;const ae=ye.linkedSourceCardId||((se=y.cards[ie])==null?void 0:se.id);ae&&pe.set(ae,ye.id)}),pe},[h,y]),N=S.useMemo(()=>{var ye;if(!v)return[];const pe=Md((ye=v.interactionConfig)==null?void 0:ye.interactions);return a1(pe,C)},[v,C]),k=S.useMemo(()=>m?mT(N,m.linkedInteractionTargetOverrides):[],[m,N]),_=g?v:m,j=g&&!!x&&!y&&!b.isFetching;S.useEffect(()=>{if(!e)return;const pe=g&&v||m;pe&&d(pe)},[e,g,v,m,d]);const{columns:I}=G5(),E=_==null?void 0:_.config,T=I,D=(E==null?void 0:E.metricColumns)||[],A=[...(E==null?void 0:E.groupByColumns)||[],...(E==null?void 0:E.pivotByColumns)||[]],[P,R]=S.useState(((fe=_==null?void 0:_.interactionConfig)==null?void 0:fe.drillHierarchies)||[]),[H,z]=S.useState(((ue=_==null?void 0:_.interactionConfig)==null?void 0:ue.allowedDrillTargets)||[]),[U,W]=S.useState([]),[O,Z]=S.useState(!1),Y=S.useRef(null),M=S.useMemo(()=>`${e}-${t}-${n}-${g?(v==null?void 0:v.id)||"loading":(m==null?void 0:m.id)||"none"}`,[e,t,n,g,v==null?void 0:v.id,m==null?void 0:m.id]);S.useEffect(()=>{e||(Y.current=null)},[e]),S.useEffect(()=>{var pe,ye,ie;!e||!_||g&&!v||Y.current!==M&&(R(((pe=_.interactionConfig)==null?void 0:pe.drillHierarchies)||[]),z(((ye=_.interactionConfig)==null?void 0:ye.allowedDrillTargets)||[]),W(g?k:Md((ie=_.interactionConfig)==null?void 0:ie.interactions)),Y.current=M)},[e,_,M,g,v,k]);const K=async()=>{var pe,ye,ie,ae,se;if(m){Z(!0);try{const Ie=Md(p.normalizeInteractionsForSave(U));if(!g||!(h!=null&&h.visualId)||!y||!v){const ze={...m,interactionConfig:{...m.interactionConfig,drillHierarchies:P,allowedDrillTargets:H,interactions:Ie}},Ve=(ye=(pe=f==null?void 0:f.sheets)==null?void 0:pe.find(Ke=>(Ke.frames||[]).some(ke=>ke.id===(h==null?void 0:h.id))))==null?void 0:ye.id;Ve&&(h!=null&&h.id)&&u?u(Ve,h.id,ze):l(ze),d(ze),r();return}const oe=Md((ie=v.interactionConfig)==null?void 0:ie.interactions),me=Xqe(Ie,oe),we=((ae=v.interactionConfig)==null?void 0:ae.drillHierarchies)||[],ge=((se=v.interactionConfig)==null?void 0:se.allowedDrillTargets)||[],re=!kT(P,we)||!kT(H,ge)||!kT(me,oe),ne={...v,interactionConfig:{...v.interactionConfig,drillHierarchies:P,allowedDrillTargets:H,interactions:me}},he={...y,cards:y.cards.map(ze=>ze.id===v.id?ne:ze)};if(re){if(!(i!=null&&i.apiServiceUrl)||!(o!=null&&o.accessToken))throw new Error("Missing authentication context for visual update");const ze=await fetch(`${i.apiServiceUrl}/management/v1/visuals/${h.visualId}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(o==null?void 0:o.accessToken)||""}`},body:JSON.stringify({frameObject:he,expectedLastModified:w})});if(!ze.ok){const Ke=await ze.json().catch(()=>({})),ke=new Error((Ke==null?void 0:Ke.error)||"Failed to update visual");throw ke.status=ze.status,ke}const Ve=await ze.json();a.setQueryData(["resource-by-id","visual",h.visualId],Ve)}const ee=a1(Md(me),C),Ce=ee.filter(ze=>ze.id).map(ze=>ze.id),ve=i9(Qqe(Ie,ee),Ce),te=mT(ee,ve),_e={...m,linkedSourceCardId:m.linkedSourceCardId||v.id,linkedInteractionTargetOverrides:ve,interactionConfig:{...m.interactionConfig,drillHierarchies:P,allowedDrillTargets:H,interactions:te}},De=ze=>{const Ve=new Map;return ze.cards.forEach((Ke,ke)=>{var Pe;const Xe=Ke.linkedSourceCardId||((Pe=y.cards[ke])==null?void 0:Pe.id);Xe&&Ve.set(Xe,Ke.id)}),Ve},Fe=ze=>{const Ve=ze.cards.find(ke=>ke.linkedSourceCardId===v.id);if(Ve)return Ve;const Ke=y.cards.findIndex(ke=>ke.id===v.id);return Ke>=0&&ze.cards[Ke]||null},Ye=[];if((f.sheets||[]).forEach(ze=>{(ze.frames||[]).forEach(Ve=>{if(Ve.visualId!==h.visualId)return;const Ke=Fe(Ve);if(!Ke)return;const ke=De(Ve),Xe=a1(Md(me),ke),Pe=Xe.filter(Ee=>Ee.id).map(Ee=>Ee.id),He=Ve.id===h.id&&Ke.id===m.id?ve:Ke.linkedInteractionTargetOverrides,nt=i9(He,Pe),Me=mT(Xe,nt);Ye.push({sheetId:ze.id,frameId:Ve.id,isCurrentCard:Ve.id===h.id&&Ke.id===m.id,card:{...Ke,linkedSourceCardId:Ke.linkedSourceCardId||v.id,linkedInteractionTargetOverrides:nt,interactionConfig:{...Ke.interactionConfig,drillHierarchies:P,allowedDrillTargets:H,interactions:Me}}})})}),Ye.length>0&&u){Ye.forEach(Ve=>{u(Ve.sheetId,Ve.frameId,Ve.card)});const ze=Ye.find(Ve=>Ve.isCurrentCard);ze||l(_e),d((ze==null?void 0:ze.card)||_e)}else l(_e),d(_e);r()}catch(Ie){Ie.status===409?(tt.error("This saved visual was updated by another editor. Refresh and retry."),Y.current=null,await b.refetch()):tt.error(Ie.message||"Failed to save interactions")}finally{Z(!1)}}},L=()=>{Y.current=null,r()};if(!e||!t||!n||!m||!s)return null;const $={position:"fixed",left:`${s.left}px`,top:`${s.top}px`,width:`${s.width}px`,height:`${s.height}px`};return c.jsxs(p.Popover,{modal:!1,open:e,onOpenChange:pe=>!pe&&r(),children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsx("div",{style:$,className:"pointer-events-none invisible","aria-hidden":"true"})}),c.jsxs(p.PopoverContent,{onEscapeKeyDown:pe=>pe.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:[c.jsx(p.Arrow2,{className:"fill-border",width:12,height:8}),c.jsxs("div",{className:"flex flex-col border-b px-6 py-4",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("h2",{className:"text-lg font-semibold",children:"Configure Interactions"}),U.length>0&&c.jsx(rs,{variant:"default",className:"h-5 min-w-5 rounded-full px-1.5 text-xs",children:U.length})]}),c.jsxs("p",{className:"text-sm text-muted-foreground",children:["Set up drill behaviors for"," ",(m==null?void 0:m.title)||"this chart"]}),g&&c.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Logic is owned by the saved visual. Filter target routing is saved per dashboard instance."})]}),c.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:c.jsx("div",{className:"space-y-6 p-6",children:g&&!v?c.jsx("p",{className:"text-sm text-muted-foreground",children:b.isFetching?"Loading saved visual interaction config...":j?"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."}):c.jsx("div",{children:c.jsx("div",{className:"grid grid-cols-1 gap-4",children:c.jsx(HKe,{interactions:U,metrics:D,attributes:A,availableFields:T,card:{..._||m,interactionConfig:{...(_==null?void 0:_.interactionConfig)||m.interactionConfig,drillHierarchies:P}},onUpdateHierarchies:R,onChange:pe=>W(pe)})})})})}),c.jsxs("div",{className:"flex justify-end gap-2 border-t px-6 py-4",children:[c.jsx(p.Button,{variant:"outline",onClick:L,children:"Cancel"}),c.jsx(p.Button,{onClick:K,disabled:O||g&&!v,children:O?"Saving...":g?"Save to Library":"Accept"})]})]})]})}function xA(e,t){return mo.serializeLayoutsForDirtyCheck(e)!==mo.serializeLayoutsForDirtyCheck(t)}function ZKe(e,t){return t&&xA(e,t)?t:null}function XKe(e){return!!e.expression}function QKe(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function JKe(e){const t=QKe(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function yie(e){return e.fieldScope==="domain"&&e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===p.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===p.CALCULATED_FIELDS_GROUP_NAME}function eZe(e){return yie(e)}function tZe(e){return e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER||(e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card")&&JKe(e.id)&&!e.entityName}function Lu(e){return XKe(e)?eZe(e)?"domain_calculated":tZe(e)?"user_calculated":"inline_expression":"none"}function Tg(e){return Lu(e)!=="none"}function la(e){if(!Tg(e))return!1;const t=Lu(e);return t==="domain_calculated"||t==="user_calculated"?!0:e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card"}function vie(e){return la(e)&&e.fieldScope!=="card"}function wie(e,t,n){return Tg(e)?t==="editor"?!0:t==="filter"?la(e)&&e.fieldScope!=="card":la(e)&&(n==null?void 0:n.isValuePickSafe)!==!1:!1}function _T(e,t){return e.map(n=>({...n,fieldScope:t}))}function Sie(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=G5(),i=p.useEditorStore(_=>_.frame.calculatedFields),a=p.useEditorStore(_=>_.card.calculatedFields),l=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=S.useMemo(()=>e.filter(_=>Lu(_)==="domain_calculated"),[e]),b=S.useMemo(()=>e.filter(_=>Lu(_)!=="domain_calculated"),[e]),x=S.useMemo(()=>{var j;if(m)return i||[];const _=(j=u==null?void 0:u.sheets)==null?void 0:j.find(I=>I.id===f);return p.getSheetCalculatedFields(_)},[u==null?void 0:u.sheets,i,m,h,f]),y=S.useMemo(()=>{const _=d??(u==null?void 0:u.calculatedFields)??[];return _.length?_T(_,"dashboard"):[]},[u==null?void 0:u.calculatedFields,d]),w=S.useMemo(()=>x.length?_T(x,"sheet"):[],[x]),v=S.useMemo(()=>p.buildCalculatedFieldComparableKeySet([...y,...w]),[y,w]),C=S.useMemo(()=>{const _=(a||[]).filter(D=>la(D)&&D.fieldScope!=="domain"),j=((l==null?void 0:l.metricColumns)||[]).filter(D=>la(D)&&D.fieldScope!=="domain"),I=((l==null?void 0:l.groupByColumns)||[]).filter(D=>la(D)&&D.fieldScope!=="domain"),T=p.dedupeCalculatedFields([..._,...j,...I]).filter(D=>!v.has(p.getCalculatedFieldComparableKey(D)));return _T(T,"card").map(D=>({...D,id:`card-source-${D.id}`}))},[a,l==null?void 0:l.groupByColumns,l==null?void 0:l.metricColumns,v]),N=S.useMemo(()=>[...g,...y,...w,...C,...b],[C,b,y,g,w]),k=S.useMemo(()=>t.filter(_=>_.entityId!==p.CALCULATED_FIELDS_GROUP_ID),[t]);return{columns:e,columnGroups:k,rawColumnGroups:t,columnFields:b,domainCalculatedFields:g,dashboardCalculatedFields:y,sheetCalculatedFields:w,cardCalculatedFields:C,scopedFields:N,isLoading:n,hasError:r,error:s,refetch:o}}function nZe(e){const t="expression"in e&&e.expression||"",n=e.qualifiedEntityName||e.entityName||"",r=e.fieldScope||"unscoped",s=e.qualifiedFieldName||e.name;return t?["calculated",r,e.role||"field",n,s,t].join("::"):["calculated",r,e.role||"field",n,p.normalizeCalculatedFieldId(e.id)||s].join("::")}function rZe(e){return["physical",e.fieldScope||"physical",e.role||"field",e.qualifiedEntityName||"",e.qualifiedFieldName||e.name,e.name].join("::")}function lm(e){const t=new Map;return e.forEach(n=>{const r=Tg(n)?nZe(n):rZe(n);t.has(r)||t.set(r,n)}),Array.from(t.values())}function K5(e){return!nr.isCalculatedMetric(e)}function jT(e,t){return lm(e.filter(n=>wie(n,t,{isValuePickSafe:K5(n)})))}function sZe(e){return!Tg(e)||wie(e,"inline-filter",{isValuePickSafe:K5(e)})}function oZe(e){return!Tg(e)||vie(e)}function Cie(){const e=Sie(),t=S.useMemo(()=>lm(e.scopedFields),[e.scopedFields]),n=S.useMemo(()=>lm([...e.columns,...e.dashboardCalculatedFields,...e.sheetCalculatedFields]),[e.columns,e.dashboardCalculatedFields,e.sheetCalculatedFields]),r=S.useMemo(()=>lm(n.filter(oZe)),[n]),s=S.useMemo(()=>jT(t,"editor"),[t]),o=S.useMemo(()=>jT(n.filter(vie),"filter"),[n]),i=S.useMemo(()=>lm(t.filter(K5)),[t]),a=S.useMemo(()=>lm(i.filter(sZe)),[i]),l=S.useMemo(()=>jT(a,"inline-filter"),[a]);return{...e,filterableFields:t,sharedFilterableFields:n,dashboardFilterableFields:r,inlineFilterableFields:a,scopedCalculatedFields:s,sharedCalculatedFields:o,inlineCalculatedFields:l,valuePickFilterableFields:i}}const Nie=Q.forwardRef(function({icon:t,label:n,asButton:r,disabled:s,labelWrapper:o,inQuery:i,trailing:a,kebab:l,showKebab:u,onKebabClick:d,selected:f,dragging:h,disableHover:m,className:g,...b},x){const y=c.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),v=c.jsxs(c.Fragment,{children:[t,o?o(y):y,i&&c.jsx("span",{className:"sr-only",children:"In query"}),a,(l||u)&&c.jsx("button",{type:"button","aria-label":"Field actions",onClick:C=>{C.stopPropagation(),d==null||d(C)},onPointerDown:C=>C.stopPropagation(),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:opacity-100 group-focus-within/field-row:opacity-100 [@media(hover:none)]:opacity-100",children:l??c.jsx(da,{className:"h-3 w-3"})})]});return r?c.jsx("button",{ref:x,type:"button",disabled:s,"data-selected":f?"true":void 0,className:w,...b,children:v}):c.jsx("div",{ref:x,"data-selected":f?"true":void 0,className:w,...b,children:v})});function Z5(e){const{tokenProps:t,authToken:n}=mt(),r=t==null?void 0:t.apiServiceUrl;return jn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return p.getRequest(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function kie(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 _ie(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function iZe(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const aZe=new Set(["COUNT","DISTINCT"]),lZe=new Set(["running_total","moving_average","previous_period_delta"]);function cZe(e){return p.getDataType(e.dataType||"")==="number"?!0:e.aggregate?aZe.has(e.aggregate.toUpperCase()):!1}function uZe(e,t){var r,s;return!!((s=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:s.function)}function X5(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 jie({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,l;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(!cZe(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const s=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,o=e==="pivotTable"||X5(e,t);return s&&!o?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:lZe.has(r)&&(((l=t.groupByColumns)==null?void 0:l.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function dZe(e){return e.find(t=>p.getDataType(t.dataType||"")==="date")}function fZe(e){return e}function Rx({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(o=>o.id&&o.id!==n).map(o=>o.id),s=[];if(e==="pivotTable"||X5(e,t))for(const o of t.pivotByColumns||[])o.id&&s.push(o.id);return Array.from(new Set([...r,...s]))}function hZe({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const s=r||((i=dZe(n.groupByColumns||[]))==null?void 0:i.id),o=Rx({cardType:t,cardConfig:n,orderByFieldId:s});return e==="moving_average"?{function:"moving_average",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,frame:"unbounded_preceding"}}const mZe=new Set(["table","aggregateTable","pivotTable","detailTable"]);function pZe(e){return e.alias||e.label||e.name}function Eie(e,t,n){var a,l,u;if(!e)return null;const r=p.fromSemanticFormat(t.format);if(!r)return null;const s=n||{};let o=s,i=!1;if(mZe.has(e.type)){const d=p.toColumnNumberFormat(r),f=pZe(t);if(d&&!((l=(a=s.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:l[f])){const m=Vs();o={...o,tablePrefs:{...o.tablePrefs||{},columnSettingsMap:{...((u=o.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...m,type:"number",textAlign:"right",numberFormat:{...m.numberFormat,...d}}}}},i=!0}if(!s.formatNumber){const h=p.toLegacyFormatNumber(r);h&&(o={...o,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?o:null}const Iie=e=>{var L;const t=(L=e==null?void 0:e.dataSource)==null?void 0:L.semanticDomainId,{data:n}=Z5(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=p.useEditorActions(),m=p.useEditorStore($=>$.card.type),g=e==null?void 0:e.id,b=($,B)=>{if($.id)return $.id;const V=$.qualifiedEntityName||$.entityName||B;return`${B}-${V}-${$.name}`},x=S.useCallback($=>{if(!(e!=null&&e.config))return[];switch($){case"groupBy":return(e.config.groupByColumns||[]).map(B=>({...B,id:b(B,"groupBy"),label:B.label!==void 0?B.label:B.name}));case"metrics":return(e.config.metricColumns||[]).map(B=>({...B,id:b(B,"metrics"),label:B.label!==void 0?B.label:B.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map(B=>({id:b(B,"pivotBy"),name:B.name,dataType:B.dataType,label:B.label!==void 0?B.label:B.name,qualifiedEntityName:B.qualifiedEntityName,entityId:B.entityId,entityName:B.entityName,entityType:B.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(B=>({id:b(B,"sortBy"),name:B.name,dataType:B.dataType,label:B.label!==void 0?B.label:B.name,qualifiedEntityName:B.qualifiedEntityName,entityId:B.entityId,entityName:B.entityName,entityType:B.entityType,direction:B.direction}));case"detailColumns":return iZe(e.config.detailColumns,B=>b(B,"detailColumns"));case"source":return[];default:return[]}},[e]),y=S.useCallback(($,B)=>{if(g)switch($){case"groupBy":{r(g,{groupByColumns:B});break}case"metrics":{r(g,{metricColumns:B});break}case"pivotBy":{r(g,{pivotByColumns:B});break}case"sortBy":{r(g,{sortByColumns:B});break}case"detailColumns":{r(g,{detailColumns:B});break}}},[g,r]),w=S.useCallback(($,B,V)=>{if(!g)return;const F=x($),q=F[B];if(q)switch($){case"groupBy":s(g,q.id,{label:V});break;case"metrics":o(g,q.id,{label:V});break;case"pivotBy":i(g,q.id,{label:V});break;case"sortBy":a(g,q.id,{label:V});break;case"detailColumns":{const G=F.map((X,J)=>J===B?{...X,label:V}:X);r(g,{detailColumns:G});break}}},[g,x,s,o,i,a,r]),v=S.useCallback(($,B)=>{if(!g)return;const F=x("metrics")[$];F&&o(g,F.id,{aggregate:B,label:zQ(F.name,B)})},[g,x,o]),C=S.useCallback(($,B,V,F="groupBy")=>{if(!g)return;const q=x(F),G=q[$];if(!G)return;const X={dateFormat:B,customFormat:B==="custom"&&V?V:void 0};if(F==="detailColumns"){const J=q.map((fe,ue)=>ue===$?{...fe,...X}:fe);r(g,{detailColumns:J});return}s(g,G.id,X)},[g,x,r,s]),N=S.useCallback(($,B)=>{if(!g)return;const F=x("groupBy")[$];F&&s(g,F.id,{granularity:B})},[g,x,s]),k=S.useCallback(($,B)=>{if(!g)return;const F=x("metrics")[$];F&&o(g,F.id,{aliasTemplate:B})},[g,x,o]),_=S.useCallback(($,B)=>{if(console.log("handleValueAliasesChange",$,B),!g)return;console.log("handleValueAliasesChange",$,B);const F=x("metrics")[$];F&&(console.log("handleValueAliasesChange",B),o(g,F.id,{valueAliases:B}))},[g,x,o]),j=S.useCallback(($,B)=>{var q,G;if(!g)return;const F=x("metrics")[$];F&&(o(g,F.id,{format:B}),m==="kpi"&&((G=(q=e==null?void 0:e.preferences)==null?void 0:q.kpiVisualOptions)!=null&&G.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,g,m,x,h,o]),I=S.useCallback(($,B)=>{var G;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=B!=="none"&&((G=F.parameters)==null?void 0:G.windowTransform);o(g,F.id,{comparisonType:B,...B!=="target"?{targetValue:void 0}:{},...q?{parameters:{...F.parameters||{},windowTransform:void 0}}:{}})},[g,x,o]),E=S.useCallback(($,B)=>{var ue,pe,ye;if(!g||!(e!=null&&e.config))return;const F=x("metrics")[$];if(!F)return;if(B==="none"){o(g,F.id,{parameters:{...F.parameters||{},windowTransform:void 0}});return}const q=jie({cardType:m,cardConfig:e.config,metric:F,transformMode:B});if(!q.supported){tt.error(q.reason||"Metric transform is not supported here.");return}const G=new Set((e.config.groupByColumns||[]).map(ie=>ie.id)),X=(ye=(pe=(ue=F.parameters)==null?void 0:ue.windowTransform)==null?void 0:pe.orderBy)==null?void 0:ye.fieldId,J=X&&G.has(X)?X:void 0,fe=hZe({transformMode:B,cardType:m,cardConfig:e.config,fallbackOrderByFieldId:J});o(g,F.id,{comparisonType:"none",targetValue:void 0,parameters:{...F.parameters||{},windowTransform:fe}})},[e,g,m,x,o]),T=S.useCallback(($,B)=>{var fe,ue;if(!g||!(e!=null&&e.config))return;const F=x("metrics")[$];if(!F)return;const q=(fe=F.parameters)==null?void 0:fe.windowTransform;if(!q||!["running_total","moving_average","previous_period_delta"].includes(q.function))return;const G=Rx({cardType:m,cardConfig:e.config,orderByFieldId:B}),J=(q.partitionByFieldIds||G).filter(pe=>pe!==B);o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,orderBy:{fieldId:B,direction:((ue=q.orderBy)==null?void 0:ue.direction)||"asc"},partitionByFieldIds:J}}})},[e,g,m,x,o]),D=S.useCallback(($,B)=>{var G;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(G=F.parameters)==null?void 0:G.windowTransform;!q||!["running_total","moving_average","previous_period_delta"].includes(q.function)||o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,orderBy:q.orderBy?{...q.orderBy,direction:B}:q.orderBy}}})},[g,x,o]),A=S.useCallback(($,B)=>{var J,fe;if(!g||!(e!=null&&e.config))return;const F=x("metrics")[$];if(!F)return;const q=(J=F.parameters)==null?void 0:J.windowTransform;if(!q)return;const G=Rx({cardType:m,cardConfig:e.config,orderByFieldId:(fe=q.orderBy)==null?void 0:fe.fieldId}),X=new Set(q.partitionByFieldIds||G);X.has(B)?X.delete(B):X.add(B),o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,partitionByFieldIds:Array.from(X)}}})},[e,g,m,x,o]),P=S.useCallback(($,B)=>{var fe,ue;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(fe=F.parameters)==null?void 0:fe.windowTransform;if(!q||q.function!=="moving_average")return;const G=Math.max(1,Math.floor(B||1)),X=((ue=q.movingAverage)==null?void 0:ue.minPeriods)||1,J=Math.min(X,G);o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,movingAverage:{windowSize:G,minPeriods:J}}}})},[g,x,o]),R=S.useCallback(($,B)=>{var J,fe;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(J=F.parameters)==null?void 0:J.windowTransform;if(!q||q.function!=="moving_average")return;const G=((fe=q.movingAverage)==null?void 0:fe.windowSize)||7,X=Math.max(1,Math.min(Math.floor(B||1),G));o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,movingAverage:{windowSize:G,minPeriods:X}}}})},[g,x,o]),H=S.useCallback(($,B)=>{var G;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(G=F.parameters)==null?void 0:G.windowTransform;!q||q.function!=="previous_period_delta"||o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,previousPeriodDelta:{mode:B}}}})},[g,x,o]),z=S.useCallback(($,B)=>{var X;if(!g||!(e!=null&&e.config))return;const F=x("metrics")[$];if(!F)return;const q=(X=F.parameters)==null?void 0:X.windowTransform;if(!q||q.function!=="percent_of_total")return;const G=B==="grand_total"?[]:(q.partitionByFieldIds||[]).length>0?q.partitionByFieldIds||[]:Rx({cardType:m,cardConfig:e.config,orderByFieldId:void 0});o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,partitionByFieldIds:G,percentOfTotal:{...q.percentOfTotal||{},scope:B}}}})},[e,g,m,x,o]),U=S.useCallback(($,B)=>{var G;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(G=F.parameters)==null?void 0:G.windowTransform;!q||q.function!=="percent_of_total"||o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,percentOfTotal:{...q.percentOfTotal||{},output:B}}}})},[g,x,o]),W=S.useCallback($=>{g&&r(g,{showTrendline:$})},[g,r]),O=S.useCallback($=>{g&&r(g,{trendlineWindow:$})},[g,r]),Z=S.useCallback($=>{g&&r(g,{trendlineGranularity:$})},[g,r]),Y=S.useCallback(($,B)=>{if(!g)return;const F=x("metrics")[$];F&&o(g,F.id,{targetValue:B})},[g,x,o]),M=S.useCallback(async $=>{var fe;if(!g)return;const B=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy"),...x("detailColumns")],V=$,F=YMe(V,B,{joinPlan:(fe=e==null?void 0:e.config)==null?void 0:fe.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t,datasetAliases:n==null?void 0:n.datasets});if(!F.isValid){F.showError&&FQ();return}const q=sAe(V,B,m);if(!q){tt.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const G=kie(V,q,m);if(!G.isValid){tt.error("Invalid Field Type",{description:G.reason,position:"top-center",duration:3e3});return}const X=x(q);if(PQ(V,X))return;const J=BQ(V,q,X);if(J){const ue=[...X,J];if(y(q,ue),q==="metrics"){const pe=Eie(e,J,e==null?void 0:e.preferences);pe&&h(pe),_ie(m,e==null?void 0:e.config,r,g,ue)}}},[g,e,x,y,t,n,m,r,h]),K=S.useCallback(($,B)=>{if(!g)return;const F=x($)[B];if(F){if($!=="sortBy"){const q=x("sortBy"),G=q.filter(X=>!(X.name===F.name&&X.qualifiedEntityName===F.qualifiedEntityName));G.length!==q.length&&r(g,{sortByColumns:G})}switch($){case"groupBy":l(g,F.id);break;case"metrics":u(g,F.id);break;case"pivotBy":d(g,F.id);break;case"sortBy":f(g,F.id);break;case"detailColumns":{r(g,{detailColumns:(x("detailColumns")||[]).filter((q,G)=>G!==B)});break}}}},[g,x,l,u,d,f,r]);return{getFieldsForContainer:x,setFieldsForContainer:y,updateLabel:w,handleAggregationChange:v,handleDateFormatChange:C,handleGranularityChange:N,handleAliasTemplateChange:k,handleValueAliasesChange:_,handleMetricFormatChange:j,removeField:K,handleFieldClick:M,handleMetricComparisonChange:I,handleMetricWindowTransformChange:E,handleMetricWindowOrderByChange:T,handleMetricWindowDirectionChange:D,handleMetricWindowPartitionToggle:A,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:R,handleMetricPreviousPeriodDeltaModeChange:H,handleMetricPercentOfTotalScopeChange:z,handleMetricPercentOfTotalOutputChange:U,handleKpiShowTrendlineChange:W,handleKpiTrendlineWindowChange:O,handleKpiTrendlineGranularityChange:Z,handleMetricTargetValueChange:Y,cardType:m}};function Tie(e){var y;const{tokenProps:t}=mt(),n=p.useDashboardStore(w=>w.authToken)||e,r=p.useEditorStore(w=>w.selectedConnectionId),s=p.useEditorStore(w=>w.selectedDatabaseName),o=p.useEditorStore(w=>w.selectedDatamodelId),i=p.useEditorStore(w=>w.selectedSchemaName),a=p.useEditorStore(w=>w.selectedTableName),{selectedConnection:l}=Cc(),u=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:m,refetch:g}=jn({queryKey:["columns",r,s,o,i,a],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",{connection_id:r,datamodel_id:o||"",database_name:s,schema_name:i,table_name:a}),enabled:b(u)});function b(w){var _;if(!(n!=null&&n.accessToken))return!1;if(o&&o)return!0;if(!r||!w)return!1;const v=((_=l==null?void 0:l.capabilities)==null?void 0:_.path)||[],C=v.includes("database"),N=v.includes("schema"),k=v.includes("table");return!(C&&(!s||s==="NA")||N&&!i||k&&!a)}return{columns:(y=d==null?void 0:d.columns)==null?void 0:y.map(w=>({...w,data_type:w.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:m,refetchColumns:g}}function gZe(e){const t=p.useDashboardStore(g=>g.selectedLensId),n=p.useDashboardStore(g=>g.dashboard.filters),r=p.useFinalFilterGroupKey(e)||"",{cardFilterValues:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:l,queryRelevantConfig:u}=RP(e),d=fk([e],{authority:"editor",queryRelevantConfigsByCardId:{[e.id]:u}}).payload,f=j0({card:e,cardConfig:u,semanticExecutionPayload:d}),h=(e==null?void 0:e.sql)||"",{queryKey:m}=wF(e,{finalFiltersKey:r,selectedLensId:t,cardFilterValues:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:l,queryRelevantConfig:u,filters:n,resolvedPrimaryDateField:f});return{queryKey:m,sql:h,cardFilterValues:s,controlValues:o}}function q_(e,t){var te,_e,De,Fe,Ye,ze,Ve,Ke;const{tokenProps:n}=mt(),r=qr(),s=mt().authToken||e,o=p.useEditorStore(ke=>ke.selectedConnectionId),i=p.useEditorStore(ke=>ke.card),{queryKey:a}=gZe(i),l=p.useEditorStore(ke=>ke.selectedDatamodelId),u=p.useEditorStore(ke=>ke.isDevMode),d=p.useEditorStore(ke=>ke.selectedDatabaseName),f=p.useEditorStore(ke=>ke.selectedSchemaName),h=p.useEditorStore(ke=>ke.selectedTableName),m=p.useEditorStore(ke=>ke.actions.setSelectedConnectionId),g=p.useEditorStore(ke=>ke.actions.setSelectedDatamodelId),b=p.useEditorStore(ke=>ke.actions.setSelectedDatabaseName),x=p.useEditorStore(ke=>ke.actions.setSelectedSchemaName),y=p.useEditorStore(ke=>ke.actions.setSelectedTableName);p.useEditorStore(ke=>ke.actions.setCardSql);const{setQueryConfig:w}=p.useEditorActions();function v(ke){var Me;if(!o||!ke)return!1;const Xe=((Me=I==null?void 0:I.capabilities)==null?void 0:Me.path)||[],Pe=Xe.includes("database"),He=Xe.includes("schema");return!(!Xe.includes("table")||Pe&&(!d||d==="NA")||He&&!f)}function C(ke){var Xe;return!o||!ke?!1:!!((Xe=I==null?void 0:I.capabilities)!=null&&Xe.path.includes("database"))}const{refetchConnections:N,connectionsData:k,isConnectionsLoading:_,isConnectionsError:j,selectedConnection:I}=Cc(e),{refetch:E,data:T,isLoading:D,isError:A}=jn({queryKey:["models",o],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),P=I==null?void 0:I.type,R=((te=I==null?void 0:I.capabilities)==null?void 0:te.path.includes("schema"))??!1,H=((_e=I==null?void 0:I.capabilities)==null?void 0:_e.path.length)===1&&((De=I==null?void 0:I.capabilities)==null?void 0:De.path[0])==="table",z=H,{data:U,isLoading:W,isFetching:O,isError:Z,refetch:Y}=jn({queryKey:["databases",o],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:C(P)}),{data:M,isLoading:K,isFetching:L,isError:$,refetch:B}=jn({queryKey:["schemas",o,d],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&R&&d!=="NA"}),{data:V,isLoading:F,isFetching:q,isError:G,refetch:X}=jn({queryKey:["tables",o,d,f],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(P)}),{columns:J,isColumnsLoading:fe,isColumnsFetching:ue,isColumnsError:pe,refetchColumns:ye}=Tie(e);S.useEffect(()=>{H&&(b(""),x(""),g(""),P==="API"&&y("api"))},[P,y,b,x,g,H]);const ie=(I==null?void 0:I.type)==="API"?(Fe=I==null?void 0:I.type)==null?void 0:Fe.toLowerCase():h||"",ae=R&&f||"";function se(ke){y(ke),w(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ie(ke){x(ke),y("")}function oe(ke){b(ke==="none"?"":ke),x(""),y(""),ke!=="none"&&ke!==""&&g("")}function me(ke){m(ke)}function we(ke){g(ke==="none"?"":ke),ke!=="none"&&ke!==""&&b("")}U&&((Ye=U==null?void 0:U.databases)==null?void 0:Ye.length)>0,M&&((ze=M==null?void 0:M.schemas)==null?void 0:ze.length)>0;const ge=k==null?void 0:k.connections.map(ke=>({id:ke.id,name:ke.name,type:ke.type})),re=(Ve=T==null?void 0:T.datamodels)==null?void 0:Ve.map(ke=>({id:ke.id,name:ke.name})),ne=U==null?void 0:U.databases.map(ke=>({id:ke.database_name,name:ke.database_name})),he=M==null?void 0:M.schemas.map(ke=>({id:ke.schema_name,name:ke.schema_name})),ee=V==null?void 0:V.tables.map(ke=>({id:ke.table_name,name:ke.table_name})),Ce=(Ke=T==null?void 0:T.datamodels.find(ke=>ke.id===l))==null?void 0:Ke.name,ve=I!=null&&I.capabilities?p.getFormattedTableNameForQuery({schemaName:ae,tableName:ie,modelName:Ce,databaseName:d||"",capabilities:I.capabilities}):ie;return{connectionItems:ge,selectedConnectionId:o,selectedConnection:I,isConnectionsLoading:_,isConnectionsError:j,modelItems:re,selectedDatamodelId:l,selectedDatamodelName:Ce,isModelsLoading:D,isModelsError:A,selectedDatabaseName:d,databaseItems:ne,isDatabasesLoadingOrFetching:W||O,isDatabaseError:Z,schemaItems:he,selectedSchemaName:f,isSchemaLoadingOrFetching:K||L,isSchemaError:$,tableItems:ee,selectedTableName:h,isTableLoadingOrFetching:F||q,isTableError:G,columns:J,isColumnsLoadingOrFetching:fe||ue,isColumnsError:pe,isNonDbConnection:z,connectionType:P,tableName:ie,formattedTableName:ve,schemaName:ae,refetchConnections:N,refetchModels:E,refetchDatabases:Y,refetchSchemas:B,refetchTables:X,refetchColumns:ye,handleConnectionChange:me,handleDatamodelChange:we,handleDatabaseChange:oe,handleSchemaChange:Ie,handleTableChange:se}}function uS(e){return`${e}-${p.v4()}`}function M9(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 bZe(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 Q5(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 Die(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Mie(){const e=p.useEditorStore(_=>_.sqlGen),t=p.useEditorStore(_=>_.isDevMode),n=p.useEditorStore(_=>_.card.dataSource),r=p.useEditorStore(_=>{var j,I;return(I=(j=_.card)==null?void 0:j.queryConfig)==null?void 0:I.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=Q5(n),a=Die(n),l=p.useEditorStore(_=>_.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:g}=p.useEditorActions(),{modelItems:b,selectedDatamodelName:x}=q_(),{selectedConnection:y}=Cc(),w=y==null?void 0:y.capabilities,v=_=>({column_name:_.name,data_type:_.dataType,label:_.label,description:_.description});return{handleDevModeFieldClick:_=>{var I;if(!t)return;const j=v(_);if(t&&a&&s&&w){const E=p.createSqlGenConfig(j,e);m(E);const T=(I=b==null?void 0:b.find(A=>A.id===l))==null?void 0:I.name,D=p.getSql(E,o||"",s,T||"",i||"",w,_.qualifiedEntityName);D&&(f(D),h(!0))}else if(!t){if(p.isTextDataType(j.data_type))if(r&&r.length>0){const E={...j,role:"groupby",id:uS(j.column_name),name:j.column_name,type:j.data_type};d(E)}else{const E={...j,role:"metric",id:uS(j.column_name),name:j.column_name,label:M9(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(E)}if(p.isDateDataType(j.data_type)){const E={...j,role:"groupby",id:uS(j.column_name),name:j.column_name,type:j.data_type,label:bZe(j.column_name,"month"),granularity:"month"};d(E)}if(p.isNumberDataType(j.data_type)){const E={...j,role:"metric",id:uS(j.column_name),name:j.column_name,label:M9(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s||!w){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=p.getFormattedTableNameForQuery({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:w});g(!1);const I=(y==null?void 0:y.type)==="MSSQL"?`SELECT top 10 * FROM ${_}`:`SELECT * FROM ${_} LIMIT 10`;f(I),h(!0)},handleShowCount:()=>{if(!a||!s||!w){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=p.getFormattedTableNameForQuery({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:w});f(`SELECT COUNT(*) as count FROM ${_}`),h(!0)},isNumberField:_=>p.isNumberDataType(_.dataType)}}function Aie(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>p.fmt(o)).join("."),s=p.fmt(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function J5(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 eL(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 Ly(e){var t,n;return e?!!(e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function A9(e){return e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e}function Ip(e,t){var b,x,y,w,v,C,N;if(!e.fieldMeta)return e.column===t.qualifiedFieldName||e.column===t.name;const n=A9((b=e.fieldMeta)==null?void 0:b.id),r=A9(t.id),s=((x=e.fieldMeta)==null?void 0:x.qualifiedFieldName)||e.column,o=s===t.qualifiedFieldName||s===t.name,i=(y=e.fieldMeta)==null?void 0:y.qualifiedEntityName,a=!i||!t.qualifiedEntityName||i===t.qualifiedEntityName,l=(w=e.fieldMeta)==null?void 0:w.entityId,u=!l||!t.entityId||l===t.entityId,d=(v=e.fieldMeta)==null?void 0:v.fieldScope;if(d&&t.fieldScope&&d!==t.fieldScope)return!1;const f=(C=e.fieldMeta)==null?void 0:C.role;if(f&&t.role&&f!==t.role)return!1;const h=Ly(e.fieldMeta)||Ly(t);if(h&&n&&r&&n===r)return!0;if(!h&&(!a||!u))return!1;const m=(N=e.fieldMeta)==null?void 0:N.expression,g=t.expression;return m||g?o&&a&&u&&m===g:o&&a&&u}function xZe(){const e=p.useDashboardStore(l=>l.dashboard.filters)||[],t=p.useDashboardStore(l=>l.selectedSheetId),n=p.useDashboardStore(l=>l.actions.addFilter),r=p.useDashboardStore(l=>l.actions.removeFilter),{removeFilterValues:s}=p.useDashboardActions(),o=p.useEditorStore(l=>l.card.dataSource),{selectedConnection:i}=Cc();function a(l,u="sheet"){var g;const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=Aie(l);let m;if(u==="sheet"&&t){const b=Qu(e,t);m=b.find(x=>x.fieldMeta&&Ip(x,l))||T1e(b.filter(x=>!x.fieldMeta),d,f,t)}else m=e==null?void 0:e.find(b=>Ip(b,l)||!b.fieldMeta&&ap(b.column)===ap(d));if(m)s(m.id),r(m.id);else{const b=p.v4(),x=J5(l),y=eL(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),w=Ly(x),v=!!((o==null?void 0:o.mode)==="semanticDomain"&&((g=y==null?void 0:y.selectedEntities)!=null&&g.length||y!=null&&y.semanticDomainId)),C=u==="sheet"&&t?[t]:void 0,N=p.getDataType(l.dataType)==="date"?"between":"in";return n({id:b,location:u,column:d,title:l.label||l.name,dataType:l.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:N,applyToSheetIds:C,sql:w||v?"":QO(l.dataType,f,h),fieldMeta:x,semanticContext:y}),b}}return{assignFilter:a}}function yZe({column:e}){const[t,n]=S.useState(!1),r=p.useEditorStore(v=>v.isDevMode),s=p.useEditorStore(v=>v.card.dataSource),{tableName:o,schemaName:i,databaseName:a}=Q5(s),l=p.useEditorStore(v=>v.selectedDatamodelId),u=p.useEditorStore(v=>v.sqlGen),{modelItems:d,selectedConnection:f}=q_(),h=f==null?void 0:f.capabilities,m=p.useEditorStore(v=>v.actions.setSqlGen),g=p.useEditorStore(v=>v.actions.setCardSql),b=p.useEditorStore(v=>v.actions.setRunSql),x=Die(s);function y(v,C){var I,E;if(!x||!o){console.warn("Cannot generate SQL: missing table metadata");return}const N=p.createSqlGenConfig(v,u,C),k=(I=d==null?void 0:d.find(T=>T.id===l))==null?void 0:I.name;if(m(N),!h){console.warn("Cannot generate SQL: missing connection capabilities");return}const _=(E=v.qualifiedFieldName)==null?void 0:E.split(".").slice(0,-1).join("."),j=p.getSql(N,i||"",o,k||"",a||"",h,_);j&&(g(j),b(!0)),n(!1)}function w(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>y(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>y(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>y(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>y(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>y(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return!r||!x?null:c.jsxs(eg,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(tg,{asChild:!0,children:c.jsx(ch,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Iu,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:w()})]})}const R9="bg-emerald-500/90 text-white",vZe="bg-blue-500/90 text-white";function tL(e){const t=Lu(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:R9}:{label:"fx",badgeClassName:e.role==="metric"?R9:vZe}}function wZe(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),e.prefix&&t.push({label:"Prefix",value:e.prefix}),e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const s=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:s})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function SZe(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,s)=>{const o=t[Number(s)];return o?`{${o.name||o.label}}`:r}):e.expression}function CZe({field:e,fieldState:t}){const n=SZe(e),r=wZe(e.format),s=!!tL(e);return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-start gap-1.5 px-3 pt-2.5",children:[c.jsx("span",{className:"flex h-[18px] shrink-0 items-center",children:c.jsx(fv,{dataType:e.dataType,calculated:s})}),c.jsx("p",{className:"min-w-0 flex-1 break-words text-[13px] font-semibold leading-[18px] text-foreground",children:e.label||e.name})]}),c.jsx("div",{className:"px-3 pb-2 pt-0.5",children:c.jsx("code",{className:"font-mono text-[11px] text-muted-foreground",children:e.dataType})}),e.description&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[12px] leading-[1.55] text-muted-foreground",children:e.description}),n&&c.jsxs("div",{className:"border-t border-border/60 bg-muted/40 px-3 py-2",children:[c.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Expression"}),c.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-[11px] leading-[1.55] text-foreground/90",children:n})]}),r.length>0&&c.jsxs("div",{className:"border-t border-border/60 px-3 py-2",children:[c.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Format"}),c.jsx("dl",{className:"grid grid-cols-[64px_1fr] gap-x-3 gap-y-1 text-[11px]",children:r.map(o=>c.jsxs("div",{className:"contents",children:[c.jsx("dt",{className:"font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o.label}),c.jsx("dd",{className:"truncate font-mono tabular-nums text-foreground/90",children:o.value})]},`${o.label}-${o.value}`))})]}),t&&t.tooltip&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[11px] text-muted-foreground",children:t.tooltip}),c.jsx("div",{className:"border-t border-border/60 px-3 py-2",children:c.jsx("code",{className:"block break-all font-mono text-[11px] leading-[1.45] text-muted-foreground",children:e.name})})]})}function F9({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o,onHover:i}){const a=p.useEditorStore(q=>q.isDevMode),l=t==="inline-filter"||t==="document-filter",u=t==="filter"||l,d=a||u||(n==null?void 0:n.state)==="unreachable"&&!u,f=p.useDashboardStore(q=>q.dashboard.filters),h=p.useDashboardStore(q=>q.selectedSheetId),m=p.useDashboardStore(q=>q.actions.removeFilter),{removeFilterValues:g}=p.useDashboardActions(),{assignFilter:b}=xZe(),x=t==="filter"?Qu(f,h):f,y=t==="filter"?x==null?void 0:x.find(q=>{if(Ip(q,e))return!0;if(q.fieldMeta)return!1;const G=ap(q.column||""),X=ap(e.name);return G.endsWith(`.${X}`)||G===X}):void 0,w=!!y,v=l&&(s==null?void 0:s.some(q=>Ip(q,e))),C=w||v,N=y&&u?f==null?void 0:f.find(q=>q.id===y.id):void 0,k=N&&(N.applyToSheetIds&&N.applyToSheetIds.length>1||N.excludeSheetIds&&N.excludeSheetIds.length>0||!N.applyToSheetIds&&!N.excludeSheetIds&&!N.sheetId),[_,j]=S.useState(!1),[,I]=S.useState(null),{attributes:E,listeners:T,setNodeRef:D,transform:A,transition:P,isDragging:R}=Ig({id:e.id,disabled:d}),H=p.useEditorStore(q=>q.card),{handleFieldClick:z}=Iie(H),{handleDevModeFieldClick:U,isNumberField:W}=Mie(),O=()=>{N&&(console.log("[SourceField] Removing multi-sheet filter:",N.id),g(N.id),m(N.id)),I(null),j(!1)},Z=()=>{if(l&&r){r(e);return}t==="filter"?C&&k?(I(e),j(!0)):b(e,"sheet"):a?U(e):z(e)},Y={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},M={transform:di.Transform.toString(A),transition:P};function K(q){return q==="domain"?{label:"Semantic domain",Icon:Ume}:q==="sheet"?{label:"Sheet",Icon:ep}:q==="dashboard"?{label:"Dashboard",Icon:ep}:{label:"Card",Icon:NR}}const L=tL(e),$=e.fieldScope,B=$&&!L?K($):null,V=(n==null?void 0:n.state)==="unreachable",F=(n==null?void 0:n.state)==="indirect";return c.jsxs(c.Fragment,{children:[c.jsx(Nie,{ref:D,style:M,...d?{}:E,...d?{}:T,onClick:Z,onMouseEnter:q=>i==null?void 0:i(!0,q.currentTarget),onMouseLeave:()=>i==null?void 0:i(!1),title:n==null?void 0:n.tooltip,selected:w,dragging:R,disableHover:V,inQuery:!u&&!!(n!=null&&n.isSelected),icon:c.jsx(fv,{dataType:e.dataType,calculated:!!L}),label:e.label||e.name,trailing:c.jsxs(c.Fragment,{children:[a&&!u&&W(e)&&c.jsx("span",{onClick:q=>q.stopPropagation(),onPointerDown:q=>q.stopPropagation(),children:c.jsx(yZe,{column:Y})}),o?c.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:q=>q.stopPropagation(),onPointerDown:q=>q.stopPropagation(),children:o}):t==="editor"?c.jsxs(po,{children:[c.jsx(go,{asChild:!0,children:c.jsx("button",{type:"button","aria-label":"Field actions",onClick:q=>q.stopPropagation(),onPointerDown:q=>q.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:c.jsx(da,{className:"h-3 w-3"})})}),c.jsx(Ks,{align:"end",className:"w-44",children:c.jsx(bn,{onClick:q=>{q.stopPropagation(),navigator.clipboard.writeText(e.name).then(()=>{tt.success(`Copied "${e.name}"`)}).catch(()=>{tt.error("Could not copy field name")})},children:"Copy field name"})})]}):null,t==="editor"&&B&&c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx("span",{"aria-label":`${B.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:q=>q.stopPropagation(),onPointerDown:q=>q.stopPropagation(),children:c.jsx(B.Icon,{className:"h-3 w-3"})})}),c.jsxs(p.TooltipContent,{side:"top",align:"end",children:[B.label," calculated field"]})]})]}),className:p.cn((a||u)&&"cursor-pointer",!d&&!a&&!u&&"cursor-grab active:cursor-grabbing",V&&"cursor-not-allowed opacity-50",F&&"text-muted-foreground/80",v&&"bg-primary/10 hover:bg-primary/15")}),c.jsx(dh,{open:_,onOpenChange:j,children:c.jsxs(Uu,{children:[c.jsxs(qu,{children:[c.jsx(Yu,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(Gu,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(Wu,{children:[c.jsx(Zu,{children:"Cancel"}),c.jsx(Ku,{onClick:O,children:"Remove Filter"})]})]})})]})}var Na="Accordion",NZe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[nL,kZe,_Ze]=p.createCollection(Na),[W_]=p.createContextScope(Na,[_Ze,Zse]),rL=Zse(),Rie=S.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(nL.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(TZe,{...o,ref:t}):c.jsx(IZe,{...s,ref:t})})});Rie.displayName=Na;var[Fie,jZe]=W_(Na),[Pie,EZe]=W_(Na,{collapsible:!1}),IZe=S.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=p.useControllableState({prop:n,defaultProp:r??"",onChange:s,caller:Na});return c.jsx(Fie,{scope:e.__scopeAccordion,value:S.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:S.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Pie,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Oie,{...i,ref:t})})})}),TZe=S.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=p.useControllableState({prop:n,defaultProp:r??[],onChange:s,caller:Na}),l=S.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=S.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(Fie,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Pie,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Oie,{...o,ref:t})})})}),[DZe,Y_]=W_(Na),Oie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=S.useRef(null),l=p.useComposedRefs(a,t),u=kZe(n),f=p.useDirection(s)==="ltr",h=p.composeEventHandlers(e.onKeyDown,m=>{var j;if(!NZe.includes(m.key))return;const g=m.target,b=u().filter(I=>{var E;return!((E=I.ref.current)!=null&&E.disabled)}),x=b.findIndex(I=>I.ref.current===g),y=b.length;if(x===-1)return;m.preventDefault();let w=x;const v=0,C=y-1,N=()=>{w=x+1,w>C&&(w=v)},k=()=>{w=x-1,w<v&&(w=C)};switch(m.key){case"Home":w=v;break;case"End":w=C;break;case"ArrowRight":o==="horizontal"&&(f?N():k());break;case"ArrowDown":o==="vertical"&&N();break;case"ArrowLeft":o==="horizontal"&&(f?k():N());break;case"ArrowUp":o==="vertical"&&k();break}const _=w%y;(j=b[_].ref.current)==null||j.focus()});return c.jsx(DZe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(nL.Slot,{scope:n,children:c.jsx(p.Primitive.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),iN="AccordionItem",[MZe,sL]=W_(iN),Lie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=Y_(iN,n),i=jZe(iN,n),a=rL(n),l=p.useId(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(MZe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(Jse,{"data-orientation":o.orientation,"data-state":Uie(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Lie.displayName=iN;var $ie="AccordionHeader",zie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Y_(Na,n),o=sL($ie,n);return c.jsx(p.Primitive.h3,{"data-orientation":s.orientation,"data-state":Uie(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});zie.displayName=$ie;var yA="AccordionTrigger",Bie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Y_(Na,n),o=sL(yA,n),i=EZe(yA,n),a=rL(n);return c.jsx(nL.ItemSlot,{scope:n,children:c.jsx(XUe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Bie.displayName=yA;var Vie="AccordionContent",Hie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Y_(Na,n),o=sL(Vie,n),i=rL(n);return c.jsx(QUe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});Hie.displayName=Vie;function Uie(e){return e?"open":"closed"}var AZe=Rie,RZe=Lie,FZe=zie,qie=Bie,Wie=Hie;const oL=AZe,$y=Q.forwardRef(({className:e,...t},n)=>c.jsx(RZe,{ref:n,className:p.cn("border-b",e),...t}));$y.displayName="AccordionItem";const zy=Q.forwardRef(({className:e,children:t,...n},r)=>c.jsx(FZe,{className:"flex",children:c.jsxs(qie,{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,c.jsx(p.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));zy.displayName=qie.displayName;const By=Q.forwardRef(({className:e,children:t,...n},r)=>c.jsx(Wie,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:p.cn("pb-4 pt-0",e),children:t})}));By.displayName=Wie.displayName;let Yie=(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 G_=[{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}],PZe=G_.filter(e=>e.id!=="custom"&&!!e.insertTemplate),iL=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),aN=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function Gie(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),yie(n)){t.disqualified=!0;return}const s=(i=n.calculatedFormula)==null?void 0:i.inputFields;if(s!=null&&s.length){Gie(s,t);return}if(n.expression&&!(Lu(n)==="inline_expression"&&la(n)&&n.fieldScope==="domain")){t.disqualified=!0;return}if(!n.entityName||!n.entityId){t.disqualified=!0;return}const o=n.qualifiedEntityName||n.entityId||n.entityName;t.entities.has(o)||t.entities.set(o,{entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName})})}function aL(e){const t={entities:new Map,disqualified:!1,visited:new Set};if(Gie(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 P9="calculated_fields";function OZe(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function LZe(e){return e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===P9||e.qualifiedEntityName===P9||OZe(e.id)}function $Ze(e){return e.aggregate?e.aggregate:DP(e.dataType)}function zZe(e,t){const n=$Ze(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function BZe(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const s=Number(r),o=t[s];return!o||LZe(o)||typeof o.expression=="string"&&OQ(o.expression)?n:zZe(n,o)})}function VZe(e,t,n,r,s,o,i,a,l,u){if(!G_.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=iL(e),x=aL(h);return{id:i||`calc_${Yie(10)}`,name:b,label:e,alias:b,qualifiedFieldName:b,dataType:"number",role:"metric",expression:f,calculatedFormula:g,entityId:x.kind==="inline"?x.entityId:o,entityName:x.kind==="inline"?x.entityName:nr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:x.kind==="inline"?x.qualifiedEntityName:void 0,entityType:x.kind==="inline"?"dataset":"table",description:`Calculated field: ${e}`}}function HZe(e){var r,s;const t=G_.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function UZe(e,t,n,r,s,o){const i=iL(e),a=aL(n);return LQ({id:o||`calc_dim_${Yie(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(l=>l.role==="metric"?{...l,role:"metric"}:{...l,role:"groupby"})},entityId:a.kind==="inline"?a.entityId:s,entityName:a.kind==="inline"?a.entityName:nr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:a.kind==="inline"?a.qualifiedEntityName:void 0,entityType:a.kind==="inline"?"dataset":"table",description:`Calculated field: ${e.trim()}`})}function Kie(e){return e==="metric"?"Calculated Metric":"Calculated Column"}function qZe(e){return e==="inline"?"Single dataset":"Cross-entity"}function Zb(e){switch(e){case"card":return"This card";case"sheet":return"This sheet";case"dashboard":return"This dashboard";case"domain":return"Semantic domain"}}function O9(e){return e.replace(/\s+/g,"")}function WZe(e){var s;const t=e.calculatedFormula;if(!t||t.operation==="custom")return;const n=G_.find(o=>o.id===t.operation),r=(s=n==null?void 0:n.template)==null?void 0:s.call(n);if(r)return t.operation!=="scale"?r:r.replace("{constant}",String(t.constant??1))}function YZe(e){var r;const t=e.expression||"",n=WZe(e);return!n||O9(t)!==O9(n)?t:BZe(t,((r=e.calculatedFormula)==null?void 0:r.inputFields)||[])}function GZe(e){const t=new Set,n=/\{field_(\d+)\}/g;let r=n.exec(e);for(;r;)t.add(Number(r[1])),r=n.exec(e);return[...t].sort((s,o)=>s-o)}function KZe(e){var o;const t=e.expression||"",n=GZe(t);if(n.length===0)return{readOnly:!1};const r=((o=e.calculatedFormula)==null?void 0:o.inputFields)||[];return n[n.length-1]<r.length?{readOnly:!1}:{readOnly:!0,reason:"This legacy metric uses saved field tokens but is missing the input metadata needed to reopen it safely. It can be viewed, but editing is disabled to avoid changing query semantics."}}function ZZe(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function XZe(e){var r;const t=new Map;return(((r=e==null?void 0:e.calculatedFormula)==null?void 0:r.inputFields)||[]).forEach(s=>{const o=aN(s.id);o&&t.set(o,s),s.qualifiedFieldName&&t.set(s.qualifiedFieldName,s),s.name&&t.set(s.name,s)}),t}function QZe(e,t){const n=aN(e.id);return n&&t.get(n)||e.qualifiedFieldName&&t.get(e.qualifiedFieldName)||t.get(e.name)}function JZe(e){const t=DP(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 eXe(e,t){const n=XZe(t);return e.map(r=>{const s=QZe(r,n);return(s==null?void 0:s.role)==="metric"?s:JZe(r)})}function tXe({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:s,targetQualifiedEntityName:o}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=Lu(i);if(r==="inline"){const l=p.getCalculatedFieldNamespace(i),u=o||s;return a==="inline_expression"&&!!u&&l===u}return a==="domain_calculated"})}function nXe({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(l=>s.includes(l)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return c.jsx(p.Tabs,{value:a,onValueChange:l=>t(l),className:"w-fit shrink-0",children:c.jsx(p.TabsList,{size:"xs",children:o.map(l=>c.jsx(p.TabsTrigger,{value:l,disabled:i,children:Kie(l)},l))})})}const lL=Q.forwardRef(({className:e,sideOffset:t=8,...n},r)=>c.jsx(p.Portal$2,{children:c.jsx(Sg,{children:c.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})})}));lL.displayName="ValidationTooltipContent";const Zie=p.Arrow2$1;function ET(e,t){return`${e} ${t}${e===1?"":"s"}`}function rXe({result:e}){const t=e.errors.length>0,n=ET(e.tokens.length,"token"),r=e.errors.length>0?ET(e.errors.length,"error"):null,s=e.warnings.length>0?ET(e.warnings.length,"warning"):null,o=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
|
|
1223
|
+
`},gYe={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 bYe(e){let{announcements:t=gYe,container:n,hiddenTextDescribedById:r,screenReaderInstructions:s=pYe}=e;const{announce:o,announcement:i}=fYe(),a=pv("DndLiveRegion"),[l,u]=S.useState(!1);if(S.useEffect(()=>{u(!0)},[]),hYe(S.useMemo(()=>({onDragStart(f){let{active:h}=f;o(t.onDragStart({active:h}))},onDragMove(f){let{active:h,over:m}=f;t.onDragMove&&o(t.onDragMove({active:h,over:m}))},onDragOver(f){let{active:h,over:m}=f;o(t.onDragOver({active:h,over:m}))},onDragEnd(f){let{active:h,over:m}=f;o(t.onDragEnd({active:h,over:m}))},onDragCancel(f){let{active:h,over:m}=f;o(t.onDragCancel({active:h,over:m}))}}),[o,t])),!l)return null;const d=S.createElement(S.Fragment,null,S.createElement(uYe,{id:r,value:s.draggable}),S.createElement(dYe,{id:a,announcement:i}));return n?fr.createPortal(d,n):d}var ns;(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"})(ns||(ns={}));function nN(){}function Ep(e,t){return S.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function F_(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return S.useMemo(()=>[...t].filter(r=>r!=null),[...t])}const ya=Object.freeze({x:0,y:0});function Loe(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function xYe(e,t){const n=tN(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 $oe(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function yYe(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function p9(e){let{left:t,top:n,height:r,width:s}=e;return[{x:t,y:n},{x:t+s,y:n},{x:t,y:n+r},{x:t+s,y:n+r}]}function zoe(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function g9(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 gv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=g9(t,t.left,t.top),o=[];for(const i of r){const{id:a}=i,l=n.get(a);if(l){const u=Loe(g9(l),s);o.push({id:a,data:{droppableContainer:i,value:u}})}}return o.sort($oe)},vYe=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=p9(t),o=[];for(const i of r){const{id:a}=i,l=n.get(a);if(l){const u=p9(l),d=s.reduce((h,m,g)=>h+Loe(u[g],m),0),f=Number((d/4).toFixed(4));o.push({id:a,data:{droppableContainer:i,value:f}})}}return o.sort($oe)};function wYe(e,t){const n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),s=Math.min(t.left+t.width,e.left+e.width),o=Math.min(t.top+t.height,e.top+e.height),i=s-r,a=o-n;if(r<s&&n<o){const l=t.width*t.height,u=e.width*e.height,d=i*a,f=d/(l+u-d);return Number(f.toFixed(4))}return 0}const SYe=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e;const s=[];for(const o of r){const{id:i}=o,a=n.get(i);if(a){const l=wYe(a,t);l>0&&s.push({id:i,data:{droppableContainer:o,value:l}})}}return s.sort(yYe)};function CYe(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function Boe(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:ya}function NYe(e){return function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s.reduce((i,a)=>({...i,top:i.top+e*a.y,bottom:i.bottom+e*a.y,left:i.left+e*a.x,right:i.right+e*a.x}),{...n})}}const kYe=NYe(1);function Voe(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 _Ye(e,t,n){const r=Voe(t);if(!r)return e;const{scaleX:s,scaleY:o,x:i,y:a}=r,l=e.left-i-(1-s)*parseFloat(n),u=e.top-a-(1-o)*parseFloat(n.slice(n.indexOf(" ")+1)),d=s?e.width/s:e.width,f=o?e.height/o:e.height;return{width:d,height:f,top:u,right:l+d,bottom:u+f,left:l}}const jYe={ignoreTransform:!1};function _g(e,t){t===void 0&&(t=jYe);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:d}=vo(e).getComputedStyle(e);u&&(n=_Ye(n,u,d))}const{top:r,left:s,width:o,height:i,bottom:a,right:l}=n;return{top:r,left:s,width:o,height:i,bottom:a,right:l}}function b9(e){return _g(e,{ignoreTransform:!0})}function EYe(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function IYe(e,t){return t===void 0&&(t=vo(e).getComputedStyle(e)),t.position==="fixed"}function TYe(e,t){t===void 0&&(t=vo(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(s=>{const o=t[s];return typeof o=="string"?n.test(o):!1})}function P_(e,t){const n=[];function r(s){if(t!=null&&n.length>=t||!s)return n;if($5(s)&&s.scrollingElement!=null&&!n.includes(s.scrollingElement))return n.push(s.scrollingElement),n;if(!hv(s)||Foe(s)||n.includes(s))return n;const o=vo(e).getComputedStyle(s);return s!==e&&TYe(s,o)&&n.push(s),IYe(s,o)?n:r(s.parentNode)}return e?r(e):n}function Hoe(e){const[t]=P_(e,1);return t??null}function xT(e){return!M_||!e?null:Ng(e)?e:L5(e)?$5(e)||e===kg(e).scrollingElement?window:hv(e)?e:null:null}function Uoe(e){return Ng(e)?e.scrollX:e.scrollLeft}function qoe(e){return Ng(e)?e.scrollY:e.scrollTop}function hA(e){return{x:Uoe(e),y:qoe(e)}}var cs;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(cs||(cs={}));function Woe(e){return!M_||!e?!1:e===document.scrollingElement}function Yoe(e){const t={x:0,y:0},n=Woe(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},s=e.scrollTop<=t.y,o=e.scrollLeft<=t.x,i=e.scrollTop>=r.y,a=e.scrollLeft>=r.x;return{isTop:s,isLeft:o,isBottom:i,isRight:a,maxScroll:r,minScroll:t}}const DYe={x:.2,y:.2};function MYe(e,t,n,r,s){let{top:o,left:i,right:a,bottom:l}=n;r===void 0&&(r=10),s===void 0&&(s=DYe);const{isTop:u,isBottom:d,isLeft:f,isRight:h}=Yoe(e),m={x:0,y:0},g={x:0,y:0},b={height:t.height*s.y,width:t.width*s.x};return!u&&o<=t.top+b.height?(m.y=cs.Backward,g.y=r*Math.abs((t.top+b.height-o)/b.height)):!d&&l>=t.bottom-b.height&&(m.y=cs.Forward,g.y=r*Math.abs((t.bottom-b.height-l)/b.height)),!h&&a>=t.right-b.width?(m.x=cs.Forward,g.x=r*Math.abs((t.right-b.width-a)/b.width)):!f&&i<=t.left+b.width&&(m.x=cs.Backward,g.x=r*Math.abs((t.left+b.width-i)/b.width)),{direction:m,speed:g}}function AYe(e){if(e===document.scrollingElement){const{innerWidth:o,innerHeight:i}=window;return{top:0,left:0,right:o,bottom:i,width:o,height:i}}const{top:t,left:n,right:r,bottom:s}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:s,width:e.clientWidth,height:e.clientHeight}}function Goe(e){return e.reduce((t,n)=>Rm(t,hA(n)),ya)}function RYe(e){return e.reduce((t,n)=>t+Uoe(n),0)}function FYe(e){return e.reduce((t,n)=>t+qoe(n),0)}function Koe(e,t){if(t===void 0&&(t=_g),!e)return;const{top:n,left:r,bottom:s,right:o}=t(e);Hoe(e)&&(s<=0||o<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const PYe=[["x",["left","right"],RYe],["y",["top","bottom"],FYe]];class z5{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=P_(n),s=Goe(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,i,a]of PYe)for(const l of i)Object.defineProperty(this,l,{get:()=>{const u=a(r),d=s[o]-u;return this.rect[l]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Dx{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var s;(s=this.target)==null||s.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function OYe(e){const{EventTarget:t}=vo(e);return e instanceof t?e:kg(e)}function yT(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 Si;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Si||(Si={}));function x9(e){e.preventDefault()}function LYe(e){e.stopPropagation()}var yn;(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"})(yn||(yn={}));const Zoe={start:[yn.Space,yn.Enter],cancel:[yn.Esc],end:[yn.Space,yn.Enter,yn.Tab]},$Ye=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case yn.Right:return{...n,x:n.x+25};case yn.Left:return{...n,x:n.x-25};case yn.Down:return{...n,y:n.y+25};case yn.Up:return{...n,y:n.y-25}}};class bv{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 Dx(kg(n)),this.windowListeners=new Dx(vo(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Si.Resize,this.handleCancel),this.windowListeners.add(Si.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Si.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&Koe(r),n(ya)}handleKeyDown(t){if(R_(t)){const{active:n,context:r,options:s}=this.props,{keyboardCodes:o=Zoe,coordinateGetter:i=$Ye,scrollBehavior:a="smooth"}=s,{code:l}=t;if(o.end.includes(l)){this.handleEnd(t);return}if(o.cancel.includes(l)){this.handleCancel(t);return}const{collisionRect:u}=r.current,d=u?{x:u.left,y:u.top}:ya;this.referenceCoordinates||(this.referenceCoordinates=d);const f=i(t,{active:n,context:r.current,currentCoordinates:d});if(f){const h=Fy(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:v,isBottom:C,maxScroll:N,minScroll:k}=Yoe(b),_=AYe(b),j={x:Math.min(x===yn.Right?_.right-_.width/2:_.right,Math.max(x===yn.Right?_.left:_.left+_.width/2,f.x)),y:Math.min(x===yn.Down?_.bottom-_.height/2:_.bottom,Math.max(x===yn.Down?_.top:_.top+_.height/2,f.y))},I=x===yn.Right&&!w||x===yn.Left&&!v,E=x===yn.Down&&!C||x===yn.Up&&!y;if(I&&j.x!==f.x){const T=b.scrollLeft+h.x,D=x===yn.Right&&T<=N.x||x===yn.Left&&T>=k.x;if(D&&!h.y){b.scrollTo({left:T,behavior:a});return}D?m.x=b.scrollLeft-T:m.x=x===yn.Right?b.scrollLeft-N.x:b.scrollLeft-k.x,m.x&&b.scrollBy({left:-m.x,behavior:a});break}else if(E&&j.y!==f.y){const T=b.scrollTop+h.y,D=x===yn.Down&&T<=N.y||x===yn.Up&&T>=k.y;if(D&&!h.x){b.scrollTo({top:T,behavior:a});return}D?m.y=b.scrollTop-T:m.y=x===yn.Down?b.scrollTop-N.y:b.scrollTop-k.y,m.y&&b.scrollBy({top:-m.y,behavior:a});break}}this.handleMove(t,Rm(Fy(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()}}bv.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:r=Zoe,onActivation:s}=t,{active:o}=n;const{code:i}=e.nativeEvent;if(r.start.includes(i)){const a=o.activatorNode.current;return a&&e.target!==a?!1:(e.preventDefault(),s==null||s({event:e.nativeEvent}),!0)}return!1}}];function y9(e){return!!(e&&"distance"in e)}function v9(e){return!!(e&&"delay"in e)}class B5{constructor(t,n,r){var s;r===void 0&&(r=OYe(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:o}=t,{target:i}=o;this.props=t,this.events=n,this.document=kg(i),this.documentListeners=new Dx(this.document),this.listeners=new Dx(r),this.windowListeners=new Dx(vo(i)),this.initialCoordinates=(s=tN(o))!=null?s:ya,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(Si.Resize,this.handleCancel),this.windowListeners.add(Si.DragStart,x9),this.windowListeners.add(Si.VisibilityChange,this.handleCancel),this.windowListeners.add(Si.ContextMenu,x9),this.documentListeners.add(Si.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(v9(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(y9(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:s}=this.props;s(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(Si.Click,LYe,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Si.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:s,props:o}=this,{onMove:i,options:{activationConstraint:a}}=o;if(!s)return;const l=(n=tN(t))!=null?n:ya,u=Fy(s,l);if(!r&&a){if(y9(a)){if(a.tolerance!=null&&yT(u,a.tolerance))return this.handleCancel();if(yT(u,a.distance))return this.handleStart()}if(v9(a)&&yT(u,a.tolerance))return this.handleCancel();this.handlePending(a,u);return}t.cancelable&&t.preventDefault(),i(l)}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===yn.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const zYe={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class jg extends B5{constructor(t){const{event:n}=t,r=kg(n.target);super(t,zYe,r)}}jg.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 BYe={move:{name:"mousemove"},end:{name:"mouseup"}};var mA;(function(e){e[e.RightClick=2]="RightClick"})(mA||(mA={}));class VYe extends B5{constructor(t){super(t,BYe,kg(t.event.target))}}VYe.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button===mA.RightClick?!1:(r==null||r({event:n}),!0)}}];const vT={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class HYe extends B5{constructor(t){super(t,vT)}static setup(){return window.addEventListener(vT.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(vT.move.name,t)};function t(){}}}HYe.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;const{touches:s}=n;return s.length>1?!1:(r==null||r({event:n}),!0)}}];var Mx;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Mx||(Mx={}));var rN;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(rN||(rN={}));function UYe(e){let{acceleration:t,activator:n=Mx.Pointer,canScroll:r,draggingRect:s,enabled:o,interval:i=5,order:a=rN.TreeOrder,pointerCoordinates:l,scrollableAncestors:u,scrollableAncestorRects:d,delta:f,threshold:h}=e;const m=WYe({delta:f,disabled:!o}),[g,b]=oYe(),x=S.useRef({x:0,y:0}),y=S.useRef({x:0,y:0}),w=S.useMemo(()=>{switch(n){case Mx.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case Mx.DraggableRect:return s}},[n,s,l]),v=S.useRef(null),C=S.useCallback(()=>{const k=v.current;if(!k)return;const _=x.current.x*y.current.x,j=x.current.y*y.current.y;k.scrollBy(_,j)},[]),N=S.useMemo(()=>a===rN.TreeOrder?[...u].reverse():u,[a,u]);S.useEffect(()=>{if(!o||!u.length||!w){b();return}for(const k of N){if((r==null?void 0:r(k))===!1)continue;const _=u.indexOf(k),j=d[_];if(!j)continue;const{direction:I,speed:E}=MYe(k,j,w,t,h);for(const T of["x","y"])m[T][I[T]]||(E[T]=0,I[T]=0);if(E.x>0||E.y>0){b(),v.current=k,g(C,i),x.current=E,y.current=I;return}}x.current={x:0,y:0},y.current={x:0,y:0},b()},[t,C,r,b,o,i,JSON.stringify(w),JSON.stringify(m),g,u,N,d,JSON.stringify(h)])}const qYe={x:{[cs.Backward]:!1,[cs.Forward]:!1},y:{[cs.Backward]:!1,[cs.Forward]:!1}};function WYe(e){let{delta:t,disabled:n}=e;const r=eN(t);return mv(s=>{if(n||!r||!s)return qYe;const o={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[cs.Backward]:s.x[cs.Backward]||o.x===-1,[cs.Forward]:s.x[cs.Forward]||o.x===1},y:{[cs.Backward]:s.y[cs.Backward]||o.y===-1,[cs.Forward]:s.y[cs.Forward]||o.y===1}}},[n,t,r])}function YYe(e,t){const n=t!=null?e.get(t):void 0,r=n?n.node.current:null;return mv(s=>{var o;return t==null?null:(o=r??s)!=null?o:null},[r,t])}function GYe(e,t){return S.useMemo(()=>e.reduce((n,r)=>{const{sensor:s}=r,o=s.activators.map(i=>({eventName:i.eventName,handler:t(i.handler,r)}));return[...n,...o]},[]),[e,t])}var Py;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Py||(Py={}));var pA;(function(e){e.Optimized="optimized"})(pA||(pA={}));const w9=new Map;function KYe(e,t){let{dragging:n,dependencies:r,config:s}=t;const[o,i]=S.useState(null),{frequency:a,measure:l,strategy:u}=s,d=S.useRef(e),f=x(),h=Ry(f),m=S.useCallback(function(y){y===void 0&&(y=[]),!h.current&&i(w=>w===null?y:w.concat(y.filter(v=>!w.includes(v))))},[h]),g=S.useRef(null),b=mv(y=>{if(f&&!n)return w9;if(!y||y===w9||d.current!==e||o!=null){const w=new Map;for(let v of e){if(!v)continue;if(o&&o.length>0&&!o.includes(v.id)&&v.rect.current){w.set(v.id,v.rect.current);continue}const C=v.node.current,N=C?new z5(l(C),C):null;v.rect.current=N,N&&w.set(v.id,N)}return w}return y},[e,o,n,f,l]);return S.useEffect(()=>{d.current=e},[e]),S.useEffect(()=>{f||m()},[n,f]),S.useEffect(()=>{o&&o.length>0&&i(null)},[JSON.stringify(o)]),S.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:o!=null};function x(){switch(u){case Py.Always:return!1;case Py.BeforeDragging:return n;default:return!n}}}function V5(e,t){return mv(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function ZYe(e,t){return V5(e,t)}function XYe(e){let{callback:t,disabled:n}=e;const r=A_(t),s=S.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(r)},[r,n]);return S.useEffect(()=>()=>s==null?void 0:s.disconnect(),[s]),s}function O_(e){let{callback:t,disabled:n}=e;const r=A_(t),s=S.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(r)},[n]);return S.useEffect(()=>()=>s==null?void 0:s.disconnect(),[s]),s}function QYe(e){return new z5(_g(e),e)}function S9(e,t,n){t===void 0&&(t=QYe);const[r,s]=S.useState(null);function o(){s(l=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=l??n)!=null?u:null}const d=t(e);return JSON.stringify(l)===JSON.stringify(d)?l:d})}const i=XYe({callback(l){if(e)for(const u of l){const{type:d,target:f}=u;if(d==="childList"&&f instanceof HTMLElement&&f.contains(e)){o();break}}}}),a=O_({callback:o});return xa(()=>{o(),e?(a==null||a.observe(e),i==null||i.observe(document.body,{childList:!0,subtree:!0})):(a==null||a.disconnect(),i==null||i.disconnect())},[e]),r}function JYe(e){const t=V5(e);return Boe(e,t)}const C9=[];function eGe(e){const t=S.useRef(e),n=mv(r=>e?r&&r!==C9&&e&&t.current&&e.parentNode===t.current.parentNode?r:P_(e):C9,[e]);return S.useEffect(()=>{t.current=e},[e]),n}function tGe(e){const[t,n]=S.useState(null),r=S.useRef(e),s=S.useCallback(o=>{const i=xT(o.target);i&&n(a=>a?(a.set(i,hA(i)),new Map(a)):null)},[]);return S.useEffect(()=>{const o=r.current;if(e!==o){i(o);const a=e.map(l=>{const u=xT(l);return u?(u.addEventListener("scroll",s,{passive:!0}),[u,hA(u)]):null}).filter(l=>l!=null);n(a.length?new Map(a):null),r.current=e}return()=>{i(e),i(o)};function i(a){a.forEach(l=>{const u=xT(l);u==null||u.removeEventListener("scroll",s)})}},[s,e]),S.useMemo(()=>e.length?t?Array.from(t.values()).reduce((o,i)=>Rm(o,i),ya):Goe(e):ya,[e,t])}function N9(e,t){t===void 0&&(t=[]);const n=S.useRef(null);return S.useEffect(()=>{n.current=null},t),S.useEffect(()=>{const r=e!==ya;r&&!n.current&&(n.current=e),!r&&n.current&&(n.current=null)},[e]),n.current?Fy(e,n.current):ya}function nGe(e){S.useEffect(()=>{if(!M_)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 rGe(e,t){return S.useMemo(()=>e.reduce((n,r)=>{let{eventName:s,handler:o}=r;return n[s]=i=>{o(i,t)},n},{}),[e,t])}function Xoe(e){return S.useMemo(()=>e?EYe(e):null,[e])}const k9=[];function sGe(e,t){t===void 0&&(t=_g);const[n]=e,r=Xoe(n?vo(n):null),[s,o]=S.useState(k9);function i(){o(()=>e.length?e.map(l=>Woe(l)?r:new z5(t(l),l)):k9)}const a=O_({callback:i});return xa(()=>{a==null||a.disconnect(),i(),e.forEach(l=>a==null?void 0:a.observe(l))},[e]),s}function Qoe(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return hv(t)?t:e}function oGe(e){let{measure:t}=e;const[n,r]=S.useState(null),s=S.useCallback(u=>{for(const{target:d}of u)if(hv(d)){r(f=>{const h=t(d);return f?{...f,width:h.width,height:h.height}:h});break}},[t]),o=O_({callback:s}),i=S.useCallback(u=>{const d=Qoe(u);o==null||o.disconnect(),d&&(o==null||o.observe(d)),r(d?t(d):null)},[t,o]),[a,l]=JC(i);return S.useMemo(()=>({nodeRef:a,rect:n,setRef:l}),[n,a,l])}const iGe=[{sensor:jg,options:{}},{sensor:bv,options:{}}],aGe={current:{}},l1={draggable:{measure:b9},droppable:{measure:b9,strategy:Py.WhileDragging,frequency:pA.Optimized},dragOverlay:{measure:_g}};class Ax 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 lGe={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ax,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:nN},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:l1,measureDroppableContainers:nN,windowRect:null,measuringScheduled:!1},Joe={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:nN,draggableNodes:new Map,over:null,measureDroppableContainers:nN},xv=S.createContext(Joe),eie=S.createContext(lGe);function cGe(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ax}}}function uGe(e,t){switch(t.type){case ns.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case ns.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 ns.DragEnd:case ns.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ns.RegisterDroppable:{const{element:n}=t,{id:r}=n,s=new Ax(e.droppable.containers);return s.set(r,n),{...e,droppable:{...e.droppable,containers:s}}}case ns.SetDroppableDisabled:{const{id:n,key:r,disabled:s}=t,o=e.droppable.containers.get(n);if(!o||r!==o.key)return e;const i=new Ax(e.droppable.containers);return i.set(n,{...o,disabled:s}),{...e,droppable:{...e.droppable,containers:i}}}case ns.UnregisterDroppable:{const{id:n,key:r}=t,s=e.droppable.containers.get(n);if(!s||r!==s.key)return e;const o=new Ax(e.droppable.containers);return o.delete(n),{...e,droppable:{...e.droppable,containers:o}}}default:return e}}function dGe(e){let{disabled:t}=e;const{active:n,activatorEvent:r,draggableNodes:s}=S.useContext(xv),o=eN(r),i=eN(n==null?void 0:n.id);return S.useEffect(()=>{if(!t&&!r&&o&&i!=null){if(!R_(o)||document.activeElement===o.target)return;const a=s.get(i);if(!a)return;const{activatorNode:l,node:u}=a;if(!l.current&&!u.current)return;requestAnimationFrame(()=>{for(const d of[l.current,u.current]){if(!d)continue;const f=lYe(d);if(f){f.focus();break}}})}},[r,t,s,i,o]),null}function tie(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((s,o)=>o({transform:s,...r}),n):n}function fGe(e){return S.useMemo(()=>({draggable:{...l1.draggable,...e==null?void 0:e.draggable},droppable:{...l1.droppable,...e==null?void 0:e.droppable},dragOverlay:{...l1.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 hGe(e){let{activeNode:t,measure:n,initialRect:r,config:s=!0}=e;const o=S.useRef(!1),{x:i,y:a}=typeof s=="boolean"?{x:s,y:s}:s;xa(()=>{if(!i&&!a||!t){o.current=!1;return}if(o.current||!r)return;const u=t==null?void 0:t.node.current;if(!u||u.isConnected===!1)return;const d=n(u),f=Boe(d,r);if(i||(f.x=0),a||(f.y=0),o.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const h=Hoe(u);h&&h.scrollBy({top:f.y,left:f.x})}},[t,i,a,r,n])}const L_=S.createContext({...ya,scaleX:1,scaleY:1});var $c;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})($c||($c={}));const yv=S.memo(function(t){var n,r,s,o;let{id:i,accessibility:a,autoScroll:l=!0,children:u,sensors:d=iGe,collisionDetection:f=SYe,measuring:h,modifiers:m,...g}=t;const b=S.useReducer(uGe,void 0,cGe),[x,y]=b,[w,v]=mYe(),[C,N]=S.useState($c.Uninitialized),k=C===$c.Initialized,{draggable:{active:_,nodes:j,translate:I},droppable:{containers:E}}=x,T=_!=null?j.get(_):null,D=S.useRef({initial:null,translated:null}),A=S.useMemo(()=>{var Pe;return _!=null?{id:_,data:(Pe=T==null?void 0:T.data)!=null?Pe:aGe,rect:D}:null},[_,T]),P=S.useRef(null),[R,H]=S.useState(null),[z,U]=S.useState(null),W=Ry(g,Object.values(g)),O=pv("DndDescribedBy",i),Z=S.useMemo(()=>E.getEnabled(),[E]),Y=fGe(h),{droppableRects:M,measureDroppableContainers:K,measuringScheduled:L}=KYe(Z,{dragging:k,dependencies:[I.x,I.y],config:Y.droppable}),$=YYe(j,_),B=S.useMemo(()=>z?tN(z):null,[z]),V=Xe(),F=ZYe($,Y.draggable.measure);hGe({activeNode:_!=null?j.get(_):null,config:V.layoutShiftCompensation,initialRect:F,measure:Y.draggable.measure});const q=S9($,Y.draggable.measure,F),G=S9($?$.parentElement:null),X=S.useRef({activatorEvent:null,active:null,activeNode:$,collisionRect:null,collisions:null,droppableRects:M,draggableNodes:j,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),J=E.getNodeFor((n=X.current.over)==null?void 0:n.id),fe=oGe({measure:Y.dragOverlay.measure}),ue=(r=fe.nodeRef.current)!=null?r:$,pe=k?(s=fe.rect)!=null?s:q:null,ye=!!(fe.nodeRef.current&&fe.rect),ie=JYe(ye?null:q),ae=Xoe(ue?vo(ue):null),se=eGe(k?J??$:null),Ie=sGe(se),oe=tie(m,{transform:{x:I.x-ie.x,y:I.y-ie.y,scaleX:1,scaleY:1},activatorEvent:z,active:A,activeNodeRect:q,containerNodeRect:G,draggingNodeRect:pe,over:X.current.over,overlayNodeRect:fe.rect,scrollableAncestors:se,scrollableAncestorRects:Ie,windowRect:ae}),me=B?Rm(B,I):null,we=tGe(se),ge=N9(we),re=N9(we,[q]),ne=Rm(oe,ge),he=pe?kYe(pe,oe):null,ee=A&&he?f({active:A,collisionRect:he,droppableRects:M,droppableContainers:Z,pointerCoordinates:me}):null,Ce=zoe(ee,"id"),[ve,te]=S.useState(null),_e=ye?oe:Rm(oe,re),De=CYe(_e,(o=ve==null?void 0:ve.rect)!=null?o:null,q),Fe=S.useRef(null),Ye=S.useCallback((Pe,He)=>{let{sensor:nt,options:Me}=He;if(P.current==null)return;const Ee=j.get(P.current);if(!Ee)return;const We=Pe.nativeEvent,vt=new nt({active:P.current,activeNode:Ee,event:We,options:Me,context:X,onAbort(ft){if(!j.get(ft))return;const{onDragAbort:lt}=W.current,Pt={id:ft};lt==null||lt(Pt),w({type:"onDragAbort",event:Pt})},onPending(ft,Nt,lt,Pt){if(!j.get(ft))return;const{onDragPending:Ze}=W.current,Je={id:ft,constraint:Nt,initialCoordinates:lt,offset:Pt};Ze==null||Ze(Je),w({type:"onDragPending",event:Je})},onStart(ft){const Nt=P.current;if(Nt==null)return;const lt=j.get(Nt);if(!lt)return;const{onDragStart:Pt}=W.current,Te={activatorEvent:We,active:{id:Nt,data:lt.data,rect:D}};fr.unstable_batchedUpdates(()=>{Pt==null||Pt(Te),N($c.Initializing),y({type:ns.DragStart,initialCoordinates:ft,active:Nt}),w({type:"onDragStart",event:Te}),H(Fe.current),U(We)})},onMove(ft){y({type:ns.DragMove,coordinates:ft})},onEnd:yt(ns.DragEnd),onCancel:yt(ns.DragCancel)});Fe.current=vt;function yt(ft){return async function(){const{active:lt,collisions:Pt,over:Te,scrollAdjustedTranslate:Ze}=X.current;let Je=null;if(lt&&Ze){const{cancelDrop:st}=W.current;Je={activatorEvent:We,active:lt,collisions:Pt,delta:Ze,over:Te},ft===ns.DragEnd&&typeof st=="function"&&await Promise.resolve(st(Je))&&(ft=ns.DragCancel)}P.current=null,fr.unstable_batchedUpdates(()=>{y({type:ft}),N($c.Uninitialized),te(null),H(null),U(null),Fe.current=null;const st=ft===ns.DragEnd?"onDragEnd":"onDragCancel";if(Je){const pt=W.current[st];pt==null||pt(Je),w({type:st,event:Je})}})}}},[j]),ze=S.useCallback((Pe,He)=>(nt,Me)=>{const Ee=nt.nativeEvent,We=j.get(Me);if(P.current!==null||!We||Ee.dndKit||Ee.defaultPrevented)return;const vt={active:We};Pe(nt,He.options,vt)===!0&&(Ee.dndKit={capturedBy:He.sensor},P.current=Me,Ye(nt,He))},[j,Ye]),Ve=GYe(d,ze);nGe(d),xa(()=>{q&&C===$c.Initializing&&N($c.Initialized)},[q,C]),S.useEffect(()=>{const{onDragMove:Pe}=W.current,{active:He,activatorEvent:nt,collisions:Me,over:Ee}=X.current;if(!He||!nt)return;const We={active:He,activatorEvent:nt,collisions:Me,delta:{x:ne.x,y:ne.y},over:Ee};fr.unstable_batchedUpdates(()=>{Pe==null||Pe(We),w({type:"onDragMove",event:We})})},[ne.x,ne.y]),S.useEffect(()=>{const{active:Pe,activatorEvent:He,collisions:nt,droppableContainers:Me,scrollAdjustedTranslate:Ee}=X.current;if(!Pe||P.current==null||!He||!Ee)return;const{onDragOver:We}=W.current,vt=Me.get(Ce),yt=vt&&vt.rect.current?{id:vt.id,rect:vt.rect.current,data:vt.data,disabled:vt.disabled}:null,ft={active:Pe,activatorEvent:He,collisions:nt,delta:{x:Ee.x,y:Ee.y},over:yt};fr.unstable_batchedUpdates(()=>{te(yt),We==null||We(ft),w({type:"onDragOver",event:ft})})},[Ce]),xa(()=>{X.current={activatorEvent:z,active:A,activeNode:$,collisionRect:he,collisions:ee,droppableRects:M,draggableNodes:j,draggingNode:ue,draggingNodeRect:pe,droppableContainers:E,over:ve,scrollableAncestors:se,scrollAdjustedTranslate:ne},D.current={initial:pe,translated:he}},[A,$,ee,he,j,ue,pe,M,E,ve,se,ne]),UYe({...V,delta:I,draggingRect:he,pointerCoordinates:me,scrollableAncestors:se,scrollableAncestorRects:Ie});const Ke=S.useMemo(()=>({active:A,activeNode:$,activeNodeRect:q,activatorEvent:z,collisions:ee,containerNodeRect:G,dragOverlay:fe,draggableNodes:j,droppableContainers:E,droppableRects:M,over:ve,measureDroppableContainers:K,scrollableAncestors:se,scrollableAncestorRects:Ie,measuringConfiguration:Y,measuringScheduled:L,windowRect:ae}),[A,$,q,z,ee,G,fe,j,E,M,ve,K,se,Ie,Y,L,ae]),ke=S.useMemo(()=>({activatorEvent:z,activators:Ve,active:A,activeNodeRect:q,ariaDescribedById:{draggable:O},dispatch:y,draggableNodes:j,over:ve,measureDroppableContainers:K}),[z,Ve,A,q,y,O,j,ve,K]);return S.createElement(Ooe.Provider,{value:v},S.createElement(xv.Provider,{value:ke},S.createElement(eie.Provider,{value:Ke},S.createElement(L_.Provider,{value:De},u)),S.createElement(dGe,{disabled:(a==null?void 0:a.restoreFocus)===!1})),S.createElement(bYe,{...a,hiddenTextDescribedById:O}));function Xe(){const Pe=(R==null?void 0:R.autoScrollEnabled)===!1,He=typeof l=="object"?l.enabled===!1:l===!1,nt=k&&!Pe&&!He;return typeof l=="object"?{...l,enabled:nt}:{enabled:nt}}}),mGe=S.createContext(null),_9="button",pGe="Draggable";function gGe(e){let{id:t,data:n,disabled:r=!1,attributes:s}=e;const o=pv(pGe),{activators:i,activatorEvent:a,active:l,activeNodeRect:u,ariaDescribedById:d,draggableNodes:f,over:h}=S.useContext(xv),{role:m=_9,roleDescription:g="draggable",tabIndex:b=0}=s??{},x=(l==null?void 0:l.id)===t,y=S.useContext(x?L_:mGe),[w,v]=JC(),[C,N]=JC(),k=rGe(i,t),_=Ry(n);xa(()=>(f.set(t,{id:t,key:o,node:w,activatorNode:C,data:_}),()=>{const I=f.get(t);I&&I.key===o&&f.delete(t)}),[f,t]);const j=S.useMemo(()=>({role:m,tabIndex:b,"aria-disabled":r,"aria-pressed":x&&m===_9?!0:void 0,"aria-roledescription":g,"aria-describedby":d.draggable}),[r,m,b,x,g,d.draggable]);return{active:l,activatorEvent:a,activeNodeRect:u,attributes:j,isDragging:x,listeners:r?void 0:k,node:w,over:h,setNodeRef:v,setActivatorNodeRef:N,transform:y}}function nie(){return S.useContext(eie)}const bGe="Droppable",xGe={timeout:25};function rie(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:s}=e;const o=pv(bGe),{active:i,dispatch:a,over:l,measureDroppableContainers:u}=S.useContext(xv),d=S.useRef({disabled:n}),f=S.useRef(!1),h=S.useRef(null),m=S.useRef(null),{disabled:g,updateMeasurementsFor:b,timeout:x}={...xGe,...s},y=Ry(b??r),w=S.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]),v=O_({callback:w,disabled:g||!i}),C=S.useCallback((j,I)=>{v&&(I&&(v.unobserve(I),f.current=!1),j&&v.observe(j))},[v]),[N,k]=JC(C),_=Ry(t);return S.useEffect(()=>{!v||!N.current||(v.disconnect(),f.current=!1,v.observe(N.current))},[N,v]),S.useEffect(()=>(a({type:ns.RegisterDroppable,element:{id:r,key:o,disabled:n,node:N,rect:h,data:_}}),()=>a({type:ns.UnregisterDroppable,key:o,id:r})),[r]),S.useEffect(()=>{n!==d.current.disabled&&(a({type:ns.SetDroppableDisabled,id:r,key:o,disabled:n}),d.current.disabled=n)},[r,o,n,a]),{active:i,rect:h,isOver:(l==null?void 0:l.id)===r,node:N,over:l,setNodeRef:k}}function yGe(e){let{animation:t,children:n}=e;const[r,s]=S.useState(null),[o,i]=S.useState(null),a=eN(n);return!n&&!r&&a&&s(a),xa(()=>{if(!o)return;const l=r==null?void 0:r.key,u=r==null?void 0:r.props.id;if(l==null||u==null){s(null);return}Promise.resolve(t(u,o)).then(()=>{s(null)})},[t,r,o]),S.createElement(S.Fragment,null,n,r?S.cloneElement(r,{ref:i}):null)}const vGe={x:0,y:0,scaleX:1,scaleY:1};function wGe(e){let{children:t}=e;return S.createElement(xv.Provider,{value:Joe},S.createElement(L_.Provider,{value:vGe},t))}const SGe={position:"fixed",touchAction:"none"},CGe=e=>R_(e)?"transform 250ms ease":void 0,NGe=S.forwardRef((e,t)=>{let{as:n,activatorEvent:r,adjustScale:s,children:o,className:i,rect:a,style:l,transform:u,transition:d=CGe}=e;if(!a)return null;const f=s?u:{...u,scaleX:1,scaleY:1},h={...SGe,width:a.width,height:a.height,top:a.top,left:a.left,transform:di.Transform.toString(f),transformOrigin:s&&r?xYe(r,a):void 0,transition:typeof d=="function"?d(r):d,...l};return S.createElement(n,{className:i,style:h,ref:t},o)}),kGe=e=>t=>{let{active:n,dragOverlay:r}=t;const s={},{styles:o,className:i}=e;if(o!=null&&o.active)for(const[a,l]of Object.entries(o.active))l!==void 0&&(s[a]=n.node.style.getPropertyValue(a),n.node.style.setProperty(a,l));if(o!=null&&o.dragOverlay)for(const[a,l]of Object.entries(o.dragOverlay))l!==void 0&&r.node.style.setProperty(a,l);return i!=null&&i.active&&n.node.classList.add(i.active),i!=null&&i.dragOverlay&&r.node.classList.add(i.dragOverlay),function(){for(const[l,u]of Object.entries(s))n.node.style.setProperty(l,u);i!=null&&i.active&&n.node.classList.remove(i.active)}},_Ge=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:di.Transform.toString(t)},{transform:di.Transform.toString(n)}]},jGe={duration:250,easing:"ease",keyframes:_Ge,sideEffects:kGe({styles:{active:{opacity:"0"}}})};function EGe(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:s}=e;return A_((o,i)=>{if(t===null)return;const a=n.get(o);if(!a)return;const l=a.node.current;if(!l)return;const u=Qoe(i);if(!u)return;const{transform:d}=vo(i).getComputedStyle(i),f=Voe(d);if(!f)return;const h=typeof t=="function"?t:IGe(t);return Koe(l,s.draggable.measure),h({active:{id:o,data:a.data,node:l,rect:s.draggable.measure(l)},draggableNodes:n,dragOverlay:{node:i,rect:s.dragOverlay.measure(u)},droppableContainers:r,measuringConfiguration:s,transform:f})})}function IGe(e){const{duration:t,easing:n,sideEffects:r,keyframes:s}={...jGe,...e};return o=>{let{active:i,dragOverlay:a,transform:l,...u}=o;if(!t)return;const d={x:a.rect.left-i.rect.left,y:a.rect.top-i.rect.top},f={scaleX:l.scaleX!==1?i.rect.width*l.scaleX/a.rect.width:1,scaleY:l.scaleY!==1?i.rect.height*l.scaleY/a.rect.height:1},h={x:l.x-d.x,y:l.y-d.y,...f},m=s({...u,active:i,dragOverlay:a,transform:{initial:l,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 j9=0;function TGe(e){return S.useMemo(()=>{if(e!=null)return j9++,j9},[e])}const sie=S.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:s,transition:o,modifiers:i,wrapperElement:a="div",className:l,zIndex:u=999}=e;const{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:m,draggableNodes:g,droppableContainers:b,dragOverlay:x,over:y,measuringConfiguration:w,scrollableAncestors:v,scrollableAncestorRects:C,windowRect:N}=nie(),k=S.useContext(L_),_=TGe(f==null?void 0:f.id),j=tie(i,{activatorEvent:d,active:f,activeNodeRect:h,containerNodeRect:m,draggingNodeRect:x.rect,over:y,overlayNodeRect:x.rect,scrollableAncestors:v,scrollableAncestorRects:C,transform:k,windowRect:N}),I=V5(h),E=EGe({config:r,draggableNodes:g,droppableContainers:b,measuringConfiguration:w}),T=I?x.setRef:void 0;return S.createElement(wGe,null,S.createElement(yGe,{animation:E},f&&_?S.createElement(NGe,{key:_,id:f.id,ref:T,as:a,activatorEvent:d,adjustScale:t,className:l,transition:o,rect:I,style:{zIndex:u,...s},transform:j},n):null))});function Eg(e,t,n){const r=e.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function DGe(e,t){return e.reduce((n,r,s)=>{const o=t.get(r);return o&&(n[s]=o),n},Array(e.length))}function aS(e){return e!==null&&e>=0}function MGe(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 AGe(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const lS={scaleX:1,scaleY:1},H5=e=>{var t;let{rects:n,activeNodeRect:r,activeIndex:s,overIndex:o,index:i}=e;const a=(t=n[s])!=null?t:r;if(!a)return null;const l=RGe(n,i,s);if(i===s){const u=n[o];return u?{x:s<o?u.left+u.width-(a.left+a.width):u.left-a.left,y:0,...lS}:null}return i>s&&i<=o?{x:-a.width-l,y:0,...lS}:i<s&&i>=o?{x:a.width+l,y:0,...lS}:{x:0,y:0,...lS}};function RGe(e,t,n){const r=e[t],s=e[t-1],o=e[t+1];return!r||!s&&!o?0:n<t?s?r.left-(s.left+s.width):o.left-(r.left+r.width):o?o.left-(r.left+r.width):r.left-(s.left+s.width)}const oie=e=>{let{rects:t,activeIndex:n,overIndex:r,index:s}=e;const o=Eg(t,r,n),i=t[s],a=o[s];return!a||!i?null:{x:a.left-i.left,y:a.top-i.top,scaleX:a.width/i.width,scaleY:a.height/i.height}},cS={scaleX:1,scaleY:1},U5=e=>{var t;let{activeIndex:n,activeNodeRect:r,index:s,rects:o,overIndex:i}=e;const a=(t=o[n])!=null?t:r;if(!a)return null;if(s===n){const u=o[i];return u?{x:0,y:n<i?u.top+u.height-(a.top+a.height):u.top-a.top,...cS}:null}const l=FGe(o,s,n);return s>n&&s<=i?{x:0,y:-a.height-l,...cS}:s<n&&s>=i?{x:0,y:a.height+l,...cS}:{x:0,y:0,...cS}};function FGe(e,t,n){const r=e[t],s=e[t-1],o=e[t+1];return r?n<t?s?r.top-(s.top+s.height):o?o.top-(r.top+r.height):0:o?o.top-(r.top+r.height):s?r.top-(s.top+s.height):0:0}const iie="Sortable",aie=S.createContext({activeIndex:-1,containerId:iie,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:oie,disabled:{draggable:!1,droppable:!1}});function vv(e){let{children:t,id:n,items:r,strategy:s=oie,disabled:o=!1}=e;const{active:i,dragOverlay:a,droppableRects:l,over:u,measureDroppableContainers:d}=nie(),f=pv(iie,n),h=a.rect!==null,m=S.useMemo(()=>r.map(k=>typeof k=="object"&&"id"in k?k.id:k),[r]),g=i!=null,b=i?m.indexOf(i.id):-1,x=u?m.indexOf(u.id):-1,y=S.useRef(m),w=!MGe(m,y.current),v=x!==-1&&b===-1||w,C=AGe(o);xa(()=>{w&&g&&d(m)},[w,m,g,d]),S.useEffect(()=>{y.current=m},[m]);const N=S.useMemo(()=>({activeIndex:b,containerId:f,disabled:C,disableTransforms:v,items:m,overIndex:x,useDragOverlay:h,sortedRects:DGe(m,l),strategy:s}),[b,f,C.draggable,C.droppable,v,m,x,l,h,s]);return S.createElement(aie.Provider,{value:N},t)}const PGe=e=>{let{id:t,items:n,activeIndex:r,overIndex:s}=e;return Eg(n,r,s).indexOf(t)},OGe=e=>{let{containerId:t,isSorting:n,wasDragging:r,index:s,items:o,newIndex:i,previousItems:a,previousContainerId:l,transition:u}=e;return!u||!r||a!==o&&s===i?!1:n?!0:i!==s&&t===l},LGe={duration:200,easing:"ease"},lie="transform",$Ge=di.Transition.toString({property:lie,duration:0,easing:"linear"}),zGe={roleDescription:"sortable"};function BGe(e){let{disabled:t,index:n,node:r,rect:s}=e;const[o,i]=S.useState(null),a=S.useRef(n);return xa(()=>{if(!t&&n!==a.current&&r.current){const l=s.current;if(l){const u=_g(r.current,{ignoreTransform:!0}),d={x:l.left-u.left,y:l.top-u.top,scaleX:l.width/u.width,scaleY:l.height/u.height};(d.x||d.y)&&i(d)}}n!==a.current&&(a.current=n)},[t,n,r,s]),S.useEffect(()=>{o&&i(null)},[o]),o}function Ig(e){let{animateLayoutChanges:t=OGe,attributes:n,disabled:r,data:s,getNewIndex:o=PGe,id:i,strategy:a,resizeObserverConfig:l,transition:u=LGe}=e;const{items:d,containerId:f,activeIndex:h,disabled:m,disableTransforms:g,sortedRects:b,overIndex:x,useDragOverlay:y,strategy:w}=S.useContext(aie),v=VGe(r,m),C=d.indexOf(i),N=S.useMemo(()=>({sortable:{containerId:f,index:C,items:d},...s}),[f,s,C,d]),k=S.useMemo(()=>d.slice(d.indexOf(i)),[d,i]),{rect:_,node:j,isOver:I,setNodeRef:E}=rie({id:i,data:N,disabled:v.droppable,resizeObserverConfig:{updateMeasurementsFor:k,...l}}),{active:T,activatorEvent:D,activeNodeRect:A,attributes:P,setNodeRef:R,listeners:H,isDragging:z,over:U,setActivatorNodeRef:W,transform:O}=gGe({id:i,data:N,attributes:{...zGe,...n},disabled:v.draggable}),Z=sYe(E,R),Y=!!T,M=Y&&!g&&aS(h)&&aS(x),K=!y&&z,L=K&&M?O:null,B=M?L??(a??w)({rects:b,activeNodeRect:A,activeIndex:h,overIndex:x,index:C}):null,V=aS(h)&&aS(x)?o({id:i,items:d,activeIndex:h,overIndex:x}):C,F=T==null?void 0:T.id,q=S.useRef({activeId:F,items:d,newIndex:V,containerId:f}),G=d!==q.current.items,X=t({active:T,containerId:f,isDragging:z,isSorting:Y,id:i,index:C,items:d,newIndex:q.current.newIndex,previousItems:q.current.items,previousContainerId:q.current.containerId,transition:u,wasDragging:q.current.activeId!=null}),J=BGe({disabled:!X,index:C,node:j,rect:_});return S.useEffect(()=>{Y&&q.current.newIndex!==V&&(q.current.newIndex=V),f!==q.current.containerId&&(q.current.containerId=f),d!==q.current.items&&(q.current.items=d)},[Y,V,f,d]),S.useEffect(()=>{if(F===q.current.activeId)return;if(F!=null&&q.current.activeId==null){q.current.activeId=F;return}const ue=setTimeout(()=>{q.current.activeId=F},50);return()=>clearTimeout(ue)},[F]),{active:T,activeIndex:h,attributes:P,data:N,rect:_,index:C,newIndex:V,items:d,isOver:I,isSorting:Y,isDragging:z,listeners:H,node:j,overIndex:x,over:U,setNodeRef:Z,setActivatorNodeRef:W,setDroppableNodeRef:E,setDraggableNodeRef:R,transform:J??B,transition:fe()};function fe(){if(J||G&&q.current.newIndex===C)return $Ge;if(!(K&&!R_(D)||!u)&&(Y||X))return di.Transition.toString({...u,property:lie})}}function VGe(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 sN(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 HGe=[yn.Down,yn.Right,yn.Up,yn.Left],q5=(e,t)=>{let{context:{active:n,collisionRect:r,droppableRects:s,droppableContainers:o,over:i,scrollableAncestors:a}}=t;if(HGe.includes(e.code)){if(e.preventDefault(),!n||!r)return;const l=[];o.getEnabled().forEach(f=>{if(!f||f!=null&&f.disabled)return;const h=s.get(f.id);if(h)switch(e.code){case yn.Down:r.top<h.top&&l.push(f);break;case yn.Up:r.top>h.top&&l.push(f);break;case yn.Left:r.left>h.left&&l.push(f);break;case yn.Right:r.left<h.left&&l.push(f);break}});const u=vYe({collisionRect:r,droppableRects:s,droppableContainers:l});let d=zoe(u,"id");if(d===(i==null?void 0:i.id)&&u.length>1&&(d=u[1].id),d!=null){const f=o.get(n.id),h=o.get(d),m=h?s.get(h.id):null,g=h==null?void 0:h.node.current;if(g&&m&&f&&h){const x=P_(g).some((k,_)=>a[_]!==k),y=cie(f,h),w=UGe(f,h),v=x||!y?{x:0,y:0}:{x:w?r.width-m.width:0,y:w?r.height-m.height:0},C={x:m.left,y:m.top};return v.x&&v.y?C:Fy(C,v)}}}};function cie(e,t){return!sN(e)||!sN(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function UGe(e,t){return!sN(e)||!sN(t)||!cie(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function qGe(e,t,n){const[r,s]=S.useState(null),[o,i]=S.useState(""),a=()=>{const g={id:`hierarchy_${Date.now()}`,label:o||"New Hierarchy",type:"static",steps:[],default:!1};t([...e,g]),i(""),s(g.id)},l=g=>{t(e.filter(b=>b.id!==g))},u=(g,b)=>{t(e.map(x=>x.id===g?{...x,...b}:x))};return{editingHierarchy:r,setEditingHierarchy:s,newHierarchyName:o,setNewHierarchyName:i,createNewHierarchy:a,deleteHierarchy:l,updateHierarchy:u,addStepToHierarchy:(g,b)=>{const x=n.find(v=>v.id===b);if(!x)return;const y={field:x,mode:"drillDown",label:`Drill to ${x.label}`,retainFilters:!0,preferredChartType:"bar"},w=e.find(v=>v.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((v,C)=>C===b?{...v,...x}:v);u(g,{steps:w})}},setDefaultHierarchy:g=>{t(e.map(b=>({...b,default:b.id===g})))}}}function WGe({step:e,hierarchyId:t,stepIndex:n,onUpdateStep:r,open:s,onOpenChange:o,trigger:i}){return c.jsxs(p.Popover,{open:s,onOpenChange:o,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:i}),c.jsx(p.PopoverContent,{className:"z-50 w-80",align:"start",children:c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{children:[c.jsx(p.Label,{className:"mb-1 block text-xs font-medium",children:"Chart Type"}),c.jsxs(p.Select,{value:e.preferredChartType||"bar",onValueChange:a=>{r(t,n,{preferredChartType:a})},children:[c.jsx(p.SelectTrigger,{className:"h-8",children:c.jsx(p.SelectValue,{})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"bar",children:"Bar Chart"}),c.jsx(p.SelectItem,{value:"pie",children:"Pie Chart"}),c.jsx(p.SelectItem,{value:"line",children:"Line Chart"}),c.jsx(p.SelectItem,{value:"donut",children:"Donut Chart"}),c.jsx(p.SelectItem,{value:"table",children:"Table"}),c.jsx(p.SelectItem,{value:"metric",children:"Metric"})]})]})]}),c.jsxs("div",{children:[c.jsx(p.Label,{className:"mb-1 block text-xs font-medium",children:"Step Label"}),c.jsx(p.Input,{value:e.label||"",onChange:a=>r(t,n,{label:a.target.value}),placeholder:"Custom drill label",className:"h-8"})]}),c.jsxs("div",{children:[c.jsx(p.Label,{className:"mb-1 block text-xs font-medium",children:"Breadcrumb Label Template"}),c.jsx(p.Input,{value:e.breadcrumbLabelTemplate||"",onChange:a=>r(t,n,{breadcrumbLabelTemplate:a.target.value}),placeholder:"e.g., 'Region: {{value}}'",className:"h-8"})]}),c.jsx("div",{className:"flex items-center gap-4",children:c.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[c.jsx("input",{type:"checkbox",checked:e.retainFilters!==!1,onChange:a=>r(t,n,{retainFilters:a.target.checked}),className:"rounded"}),"Retain filters when drilling"]})}),c.jsx("div",{className:"flex justify-end",children:c.jsx(p.Button,{size:"sm",variant:"outline",onClick:()=>o(!1),children:"Done"})})]})})]})}function YGe({field:e,step:t,stepIndex:n,hierarchyId:r,onUpdateStep:s,onRemoveStep:o}){const[i,a]=S.useState(!1),{attributes:l,listeners:u,setNodeRef:d,transform:f,transition:h,isDragging:m}=Ig({id:`${r}-${e.id}-${n}`,disabled:!1}),g={transform:di.Transform.toString(f),transition:h,opacity:m?.8:1,zIndex:m?1e3:1};return c.jsx("div",{ref:d,style:g,className:`relative ${i?"z-[9998]":""}`,...l,children:c.jsx(WGe,{step:t,hierarchyId:r,stepIndex:n,onUpdateStep:s,open:i,onOpenChange:a,trigger:c.jsxs("div",{className:`flex cursor-pointer items-center gap-2 rounded-lg border bg-muted px-3 py-2 transition-colors hover:bg-muted/50 ${m?"shadow-lg ring-2 ring-primary":""}`,...u,onClick:b=>{b.stopPropagation(),a(x=>!x)},children:[c.jsxs("div",{className:"pointer-events-none flex items-center gap-2",children:[c.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:e.label}),t.preferredChartType&&t.preferredChartType!=="bar"&&c.jsx("span",{className:"whitespace-nowrap rounded bg-purple-100 px-1 py-0.5 text-xs text-purple-700 dark:bg-purple-900/50 dark:text-purple-300",children:t.preferredChartType}),t.linkedInsightId&&c.jsx("span",{className:"whitespace-nowrap rounded bg-green-100 px-1 py-0.5 text-xs text-green-700 dark:bg-green-900/50 dark:text-green-300",children:"📊"})]}),c.jsx("button",{className:"pointer-events-auto ml-1 text-xs text-muted-foreground hover:text-red-800 dark:hover:text-red-400",onClick:b=>{b.stopPropagation(),o(r,n)},children:c.jsx(p.X,{className:"h-3 w-3"})})]})})})}function GGe(e){return{sensors:F_(Ep(jg,{activationConstraint:{distance:5}}),Ep(bv,{coordinateGetter:q5})),handleStepDragEnd:(r,s)=>{const{active:o,over:i}=r;if(!i||o.id===i.id)return;const a=o.id.replace(`${s.id}-`,""),l=i.id.replace(`${s.id}-`,""),u=s.steps.findIndex(f=>f.field.id===a),d=s.steps.findIndex(f=>f.field.id===l);if(u!==-1&&d!==-1&&u!==d){const f=Eg(s.steps,u,d);e(s.id,{steps:f})}}}}function KGe({hierarchy:e,onUpdateStep:t,onRemoveStep:n,onUpdateHierarchy:r}){const{sensors:s}=GGe(r),[o,i]=S.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?c.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:c.jsx("div",{className:"rounded-lg border bg-muted/50 p-2 text-sm text-muted-foreground",children:"No drill steps configured. Add steps to create a drill hierarchy."})}):c.jsx("div",{className:"steps-container",onPointerDown:h=>h.stopPropagation(),children:c.jsxs(yv,{sensors:s,collisionDetection:gv,onDragStart:d,onDragEnd:f,children:[c.jsx(vv,{items:u,strategy:H5,children:c.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(c.jsx(vr,{className:"pointer-events-none h-4 w-4 text-gray-400"},`arrow-${m}`));const b=m===0,x=m===a.length-1;return g.push(c.jsx(YGe,{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"&&fr.createPortal(c.jsx(Sg,{children:c.jsx(sie,{style:{zIndex:9999},children:o?c.jsx("div",{className:"flex items-center gap-2 rounded-lg border-2 border-blue-300 bg-blue-200 p-2 shadow-lg dark:border-blue-600 dark:bg-blue-900/70",children:c.jsx("span",{className:"whitespace-nowrap text-sm font-medium",children:o.label})}):null})}),document.body)]})})}var E9=1,ZGe=.9,XGe=.8,QGe=.17,wT=.1,ST=.999,JGe=.9999,eKe=.99,tKe=/[\\\/_+.#"@\[\(\{&]/,nKe=/[\\\/_+.#"@\[\(\{&]/g,rKe=/[\s-]/,uie=/[\s-]/g;function gA(e,t,n,r,s,o,i){if(o===t.length)return s===e.length?E9:eKe;var a=`${s},${o}`;if(i[a]!==void 0)return i[a];for(var l=r.charAt(o),u=n.indexOf(l,s),d=0,f,h,m,g;u>=0;)f=gA(e,t,n,r,u+1,o+1,i),f>d&&(u===s?f*=E9:tKe.test(e.charAt(u-1))?(f*=XGe,m=e.slice(s,u-1).match(nKe),m&&s>0&&(f*=Math.pow(ST,m.length))):rKe.test(e.charAt(u-1))?(f*=ZGe,g=e.slice(s,u-1).match(uie),g&&s>0&&(f*=Math.pow(ST,g.length))):(f*=QGe,s>0&&(f*=Math.pow(ST,u-s))),e.charAt(u)!==t.charAt(o)&&(f*=JGe)),(f<wT&&n.charAt(u-1)===r.charAt(o+1)||r.charAt(o+1)===r.charAt(o)&&n.charAt(u-1)!==r.charAt(o))&&(h=gA(e,t,n,r,u+1,o+2,i),h*wT>f&&(f=h*wT)),f>d&&(d=f),u=n.indexOf(l,u+1);return i[a]=d,d}function I9(e){return e.toLowerCase().replace(uie," ")}function sKe(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,gA(e,t,I9(e),I9(t),0,0,{})}var xb='[cmdk-group=""]',CT='[cmdk-group-items=""]',oKe='[cmdk-group-heading=""]',die='[cmdk-item=""]',T9=`${die}:not([aria-disabled="true"])`,bA="cmdk-item-select",im="data-value",iKe=(e,t,n)=>sKe(e,t,n),fie=Q.createContext(void 0),wv=()=>Q.useContext(fie),hie=Q.createContext(void 0),W5=()=>Q.useContext(hie),mie=Q.createContext(void 0),pie=Q.forwardRef((e,t)=>{let n=am(()=>{var Y,M;return{search:"",value:(M=(Y=e.value)!=null?Y:e.defaultValue)!=null?M:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=am(()=>new Set),s=am(()=>new Map),o=am(()=>new Map),i=am(()=>new Set),a=gie(e),{label:l,children:u,value:d,onValueChange:f,filter:h,shouldFilter:m,loop:g,disablePointerSelection:b=!1,vimBindings:x=!0,...y}=e,w=p.useId(),v=p.useId(),C=p.useId(),N=Q.useRef(null),k=bKe();rh(()=>{if(d!==void 0){let Y=d.trim();n.current.value=Y,_.emit()}},[d]),rh(()=>{k(6,A)},[]);let _=Q.useMemo(()=>({subscribe:Y=>(i.current.add(Y),()=>i.current.delete(Y)),snapshot:()=>n.current,setState:(Y,M,K)=>{var L,$,B,V;if(!Object.is(n.current[Y],M)){if(n.current[Y]=M,Y==="search")D(),E(),k(1,T);else if(Y==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let F=document.getElementById(C);F?F.focus():(L=document.getElementById(w))==null||L.focus()}if(k(7,()=>{var F;n.current.selectedItemId=(F=P())==null?void 0:F.id,_.emit()}),K||k(5,A),(($=a.current)==null?void 0:$.value)!==void 0){let F=M??"";(V=(B=a.current).onValueChange)==null||V.call(B,F);return}}_.emit()}},emit:()=>{i.current.forEach(Y=>Y())}}),[]),j=Q.useMemo(()=>({value:(Y,M,K)=>{var L;M!==((L=o.current.get(Y))==null?void 0:L.value)&&(o.current.set(Y,{value:M,keywords:K}),n.current.filtered.items.set(Y,I(M,K)),k(2,()=>{E(),_.emit()}))},item:(Y,M)=>(r.current.add(Y),M&&(s.current.has(M)?s.current.get(M).add(Y):s.current.set(M,new Set([Y]))),k(3,()=>{D(),E(),n.current.value||T(),_.emit()}),()=>{o.current.delete(Y),r.current.delete(Y),n.current.filtered.items.delete(Y);let K=P();k(4,()=>{D(),(K==null?void 0:K.getAttribute("id"))===Y&&T(),_.emit()})}),group:Y=>(s.current.has(Y)||s.current.set(Y,new Set),()=>{o.current.delete(Y),s.current.delete(Y)}),filter:()=>a.current.shouldFilter,label:l||e["aria-label"],getDisablePointerSelection:()=>a.current.disablePointerSelection,listId:w,inputId:C,labelId:v,listInnerRef:N}),[]);function I(Y,M){var K,L;let $=(L=(K=a.current)==null?void 0:K.filter)!=null?L:iKe;return Y?$(Y,n.current.search,M):0}function E(){if(!n.current.search||a.current.shouldFilter===!1)return;let Y=n.current.filtered.items,M=[];n.current.filtered.groups.forEach(L=>{let $=s.current.get(L),B=0;$.forEach(V=>{let F=Y.get(V);B=Math.max(F,B)}),M.push([L,B])});let K=N.current;R().sort((L,$)=>{var B,V;let F=L.getAttribute("id"),q=$.getAttribute("id");return((B=Y.get(q))!=null?B:0)-((V=Y.get(F))!=null?V:0)}).forEach(L=>{let $=L.closest(CT);$?$.appendChild(L.parentElement===$?L:L.closest(`${CT} > *`)):K.appendChild(L.parentElement===K?L:L.closest(`${CT} > *`))}),M.sort((L,$)=>$[1]-L[1]).forEach(L=>{var $;let B=($=N.current)==null?void 0:$.querySelector(`${xb}[${im}="${encodeURIComponent(L[0])}"]`);B==null||B.parentElement.appendChild(B)})}function T(){let Y=R().find(K=>K.getAttribute("aria-disabled")!=="true"),M=Y==null?void 0:Y.getAttribute(im);_.setState("value",M||void 0)}function D(){var Y,M,K,L;if(!n.current.search||a.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let $=0;for(let B of r.current){let V=(M=(Y=o.current.get(B))==null?void 0:Y.value)!=null?M:"",F=(L=(K=o.current.get(B))==null?void 0:K.keywords)!=null?L:[],q=I(V,F);n.current.filtered.items.set(B,q),q>0&&$++}for(let[B,V]of s.current)for(let F of V)if(n.current.filtered.items.get(F)>0){n.current.filtered.groups.add(B);break}n.current.filtered.count=$}function A(){var Y,M,K;let L=P();L&&(((Y=L.parentElement)==null?void 0:Y.firstChild)===L&&((K=(M=L.closest(xb))==null?void 0:M.querySelector(oKe))==null||K.scrollIntoView({block:"nearest"})),L.scrollIntoView({block:"nearest"}))}function P(){var Y;return(Y=N.current)==null?void 0:Y.querySelector(`${die}[aria-selected="true"]`)}function R(){var Y;return Array.from(((Y=N.current)==null?void 0:Y.querySelectorAll(T9))||[])}function H(Y){let M=R()[Y];M&&_.setState("value",M.getAttribute(im))}function z(Y){var M;let K=P(),L=R(),$=L.findIndex(V=>V===K),B=L[$+Y];(M=a.current)!=null&&M.loop&&(B=$+Y<0?L[L.length-1]:$+Y===L.length?L[0]:L[$+Y]),B&&_.setState("value",B.getAttribute(im))}function U(Y){let M=P(),K=M==null?void 0:M.closest(xb),L;for(;K&&!L;)K=Y>0?pKe(K,xb):gKe(K,xb),L=K==null?void 0:K.querySelector(T9);L?_.setState("value",L.getAttribute(im)):z(Y)}let W=()=>H(R().length-1),O=Y=>{Y.preventDefault(),Y.metaKey?W():Y.altKey?U(1):z(1)},Z=Y=>{Y.preventDefault(),Y.metaKey?H(0):Y.altKey?U(-1):z(-1)};return Q.createElement(p.Primitive.div,{ref:t,tabIndex:-1,...y,"cmdk-root":"",onKeyDown:Y=>{var M;(M=y.onKeyDown)==null||M.call(y,Y);let K=Y.nativeEvent.isComposing||Y.keyCode===229;if(!(Y.defaultPrevented||K))switch(Y.key){case"n":case"j":{x&&Y.ctrlKey&&O(Y);break}case"ArrowDown":{O(Y);break}case"p":case"k":{x&&Y.ctrlKey&&Z(Y);break}case"ArrowUp":{Z(Y);break}case"Home":{Y.preventDefault(),H(0);break}case"End":{Y.preventDefault(),W();break}case"Enter":{Y.preventDefault();let L=P();if(L){let $=new Event(bA);L.dispatchEvent($)}}}}},Q.createElement("label",{"cmdk-label":"",htmlFor:j.inputId,id:j.labelId,style:yKe},l),$_(e,Y=>Q.createElement(hie.Provider,{value:_},Q.createElement(fie.Provider,{value:j},Y))))}),aKe=Q.forwardRef((e,t)=>{var n,r;let s=p.useId(),o=Q.useRef(null),i=Q.useContext(mie),a=wv(),l=gie(e),u=(r=(n=l.current)==null?void 0:n.forceMount)!=null?r:i==null?void 0:i.forceMount;rh(()=>{if(!u)return a.item(s,i==null?void 0:i.id)},[u]);let d=bie(s,o,[e.value,e.children,o],e.keywords),f=W5(),h=Ou(k=>k.value&&k.value===d.current),m=Ou(k=>u||a.filter()===!1?!0:k.search?k.filtered.items.get(s)>0:!0);Q.useEffect(()=>{let k=o.current;if(!(!k||e.disabled))return k.addEventListener(bA,g),()=>k.removeEventListener(bA,g)},[m,e.onSelect,e.disabled]);function g(){var k,_;b(),(_=(k=l.current).onSelect)==null||_.call(k,d.current)}function b(){f.setState("value",d.current,!0)}if(!m)return null;let{disabled:x,value:y,onSelect:w,forceMount:v,keywords:C,...N}=e;return Q.createElement(p.Primitive.div,{ref:p.composeRefs(o,t),...N,id:s,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!h,"data-disabled":!!x,"data-selected":!!h,onPointerMove:x||a.getDisablePointerSelection()?void 0:b,onClick:x?void 0:g},e.children)}),lKe=Q.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:s,...o}=e,i=p.useId(),a=Q.useRef(null),l=Q.useRef(null),u=p.useId(),d=wv(),f=Ou(m=>s||d.filter()===!1?!0:m.search?m.filtered.groups.has(i):!0);rh(()=>d.group(i),[]),bie(i,a,[e.value,e.heading,l]);let h=Q.useMemo(()=>({id:i,forceMount:s}),[s]);return Q.createElement(p.Primitive.div,{ref:p.composeRefs(a,t),...o,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&Q.createElement("div",{ref:l,"cmdk-group-heading":"","aria-hidden":!0,id:u},n),$_(e,m=>Q.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?u:void 0},Q.createElement(mie.Provider,{value:h},m))))}),cKe=Q.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,s=Q.useRef(null),o=Ou(i=>!i.search);return!n&&!o?null:Q.createElement(p.Primitive.div,{ref:p.composeRefs(s,t),...r,"cmdk-separator":"",role:"separator"})}),uKe=Q.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,s=e.value!=null,o=W5(),i=Ou(u=>u.search),a=Ou(u=>u.selectedItemId),l=wv();return Q.useEffect(()=>{e.value!=null&&o.setState("search",e.value)},[e.value]),Q.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":l.listId,"aria-labelledby":l.labelId,"aria-activedescendant":a,id:l.inputId,type:"text",value:s?e.value:i,onChange:u=>{s||o.setState("search",u.target.value),n==null||n(u.target.value)}})}),dKe=Q.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...s}=e,o=Q.useRef(null),i=Q.useRef(null),a=Ou(u=>u.selectedItemId),l=wv();return Q.useEffect(()=>{if(i.current&&o.current){let u=i.current,d=o.current,f,h=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=u.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return h.observe(u),()=>{cancelAnimationFrame(f),h.unobserve(u)}}},[]),Q.createElement(p.Primitive.div,{ref:p.composeRefs(o,t),...s,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":a,"aria-label":r,id:l.listId},$_(e,u=>Q.createElement("div",{ref:p.composeRefs(i,l.listInnerRef),"cmdk-list-sizer":""},u)))}),fKe=Q.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:s,contentClassName:o,container:i,...a}=e;return Q.createElement(WN,{open:n,onOpenChange:r},Q.createElement(YN,{container:i},Q.createElement(Op,{"cmdk-overlay":"",className:s}),Q.createElement(Lp,{"aria-label":e.label,"cmdk-dialog":"",className:o},Q.createElement(pie,{ref:t,...a}))))}),hKe=Q.forwardRef((e,t)=>Ou(n=>n.filtered.count===0)?Q.createElement(p.Primitive.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),mKe=Q.forwardRef((e,t)=>{let{progress:n,children:r,label:s="Loading...",...o}=e;return Q.createElement(p.Primitive.div,{ref:t,...o,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":s},$_(e,i=>Q.createElement("div",{"aria-hidden":!0},i)))}),wo=Object.assign(pie,{List:dKe,Item:aKe,Input:uKe,Group:lKe,Separator:cKe,Dialog:fKe,Empty:hKe,Loading:mKe});function pKe(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function gKe(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function gie(e){let t=Q.useRef(e);return rh(()=>{t.current=e}),t}var rh=typeof window>"u"?Q.useEffect:Q.useLayoutEffect;function am(e){let t=Q.useRef();return t.current===void 0&&(t.current=e()),t}function Ou(e){let t=W5(),n=()=>e(t.snapshot());return Q.useSyncExternalStore(t.subscribe,n,n)}function bie(e,t,n,r=[]){let s=Q.useRef(),o=wv();return rh(()=>{var i;let a=(()=>{var u;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(u=d.current.textContent)==null?void 0:u.trim():s.current}})(),l=r.map(u=>u.trim());o.value(e,a,l),(i=t.current)==null||i.setAttribute(im,a),s.current=a}),s}var bKe=()=>{let[e,t]=Q.useState(),n=am(()=>new Map);return rh(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,s)=>{n.current.set(r,s),t({})}};function xKe(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function $_({asChild:e,children:t},n){return e&&Q.isValidElement(t)?Q.cloneElement(xKe(t),{ref:t.ref},n(t.props.children)):n(t)}var yKe={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const z_=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo,{ref:n,className:p.cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t}));z_.displayName=wo.displayName;const Y5=Q.forwardRef(({className:e,...t},n)=>c.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[c.jsx(Xs,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),c.jsx(wo.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})]}));Y5.displayName=wo.Input.displayName;const B_=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo.List,{ref:n,className:p.cn("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));B_.displayName=wo.List.displayName;const V_=Q.forwardRef((e,t)=>c.jsx(wo.Empty,{ref:t,className:"py-6 text-center text-sm",...e}));V_.displayName=wo.Empty.displayName;const H_=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo.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}));H_.displayName=wo.Group.displayName;const xie=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo.Separator,{ref:n,className:p.cn("-mx-1 h-px bg-border",e),...t}));xie.displayName=wo.Separator.displayName;const U_=Q.forwardRef(({className:e,...t},n)=>c.jsx(wo.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}));U_.displayName=wo.Item.displayName;function vKe({hierarchy:e,sampleFieldReferences:t,onUpdateHierarchy:n,onDeleteHierarchy:r,onUpdateStep:s,onRemoveStep:o,onAddStep:i}){const[a,l]=S.useState(!1),{attributes:u,listeners:d,setNodeRef:f,transform:h,transition:m}=Ig({id:e.id,disabled:!1}),g={transform:di.Transform.toString(h),transition:m},b=e.steps.filter(x=>x.field).map(x=>x.field.id);return c.jsxs("div",{ref:f,style:g,className:"hierarchy-container relative rounded-lg border bg-background p-3 transition-shadow hover:shadow-md",children:[c.jsxs("div",{className:"mb-3 flex cursor-move items-center justify-between",...u,...d,children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("div",{onPointerDown:x=>x.stopPropagation(),onClick:x=>x.stopPropagation(),onKeyDown:x=>x.stopPropagation(),children:c.jsx(Oo,{value:e.label||"",onSave:x=>{n(e.id,{label:x})},placeholder:"Hierarchy Name",displayClassName:"font-medium",inputClassName:"font-medium"})})}),c.jsx("div",{className:"flex items-center gap-1",children:c.jsx(p.Button,{size:"sm",variant:"ghost",onClick:x=>{x.stopPropagation(),r(e.id)},onPointerDown:x=>x.stopPropagation(),children:c.jsx(rl,{className:"h-3 w-3"})})})]}),c.jsx(KGe,{hierarchy:e,onUpdateStep:s,onRemoveStep:o,onUpdateHierarchy:n}),c.jsx("div",{className:"mt-3 border-t pt-3","data-hierarchy-editing":!0,children:a?c.jsxs(z_,{className:"rounded-lg border",children:[c.jsx(Y5,{placeholder:"Search fields..."}),c.jsxs(B_,{children:[c.jsx(V_,{children:"No field found."}),c.jsx(H_,{children:t.filter(x=>!b.includes(x.id)).map(x=>c.jsx(U_,{value:x.label,onSelect:()=>{i(e.id,x.id),l(!1)},children:x.label},x.id))})]})]}):c.jsxs(p.Button,{type:"button",variant:"outline",size:"sm",onClick:x=>{x.preventDefault(),x.stopPropagation(),l(!0)},children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Add Step"]})})]})}function wKe({open:e,onOpenChange:t,drillHierarchies:n,onUpdateHierarchies:r,availableFields:s}){const[o,i]=S.useState(n);S.useEffect(()=>{e&&i(n)},[e,n]);const a=S.useMemo(()=>s.filter(w=>p.getDataType(w.dataType)==="string"),[s]),l=F_(Ep(jg),Ep(bv,{coordinateGetter:q5})),{createNewHierarchy:u,deleteHierarchy:d,updateHierarchy:f,addStepToHierarchy:h,removeStepFromHierarchy:m,updateStep:g,setDefaultHierarchy:b}=qGe(o,i,a),x=w=>{const{active:v,over:C}=w;if(v.id!==(C==null?void 0:C.id)){const N=o.findIndex(_=>_.id===v.id),k=o.findIndex(_=>_.id===(C==null?void 0:C.id));i(Eg(o,N,k))}},y=w=>{w||r(o),t(w)};return c.jsx(yo,{modal:!0,open:e,onOpenChange:y,children:c.jsx(Js,{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden p-0",onInteractOutside:w=>w.preventDefault(),onEscapeKeyDown:w=>w.preventDefault(),children:c.jsx(p.FocusScope,{trapped:!1,children:c.jsxs("div",{className:"flex max-h-[85vh] max-w-3xl flex-col overflow-hidden",children:[c.jsxs(Bi,{className:"border-b px-6 pb-4 pt-6",children:[c.jsx(eo,{children:"Manage Drill Hierarchies"}),c.jsx(Bo,{children:"Create multiple drill paths for different analysis scenarios. Define step-by-step navigation through your dimensions."})]}),c.jsx(p.ScrollArea,{className:"flex-1 px-6",children:c.jsxs("div",{className:"space-y-4 py-4",children:[o.length>0&&c.jsx("div",{className:"flex justify-end",children:c.jsxs(p.Button,{type:"button",size:"sm",onClick:w=>{w.preventDefault(),w.stopPropagation(),u()},children:[c.jsx(wr,{className:"mr-1 h-4 w-4"}),"Add Hierarchy"]})}),o.length>0?c.jsx(yv,{sensors:l,collisionDetection:gv,onDragEnd:x,children:c.jsx(vv,{items:o.map(w=>w.id),strategy:U5,children:c.jsx("div",{className:"space-y-4",children:o.map(w=>c.jsx(vKe,{hierarchy:w,sampleFieldReferences:a,onUpdateHierarchy:f,onDeleteHierarchy:d,onSetDefaultHierarchy:b,onUpdateStep:g,onRemoveStep:m,onAddStep:h},w.id))})})}):c.jsxs("div",{className:"rounded-lg border border-dashed p-8 text-center",children:[c.jsx("p",{className:"mb-2 text-sm text-muted-foreground",children:"No hierarchies configured yet"}),c.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:"Create your first hierarchy to enable drill-down interactions"}),c.jsxs(p.Button,{type:"button",size:"sm",variant:"outline",onClick:w=>{w.preventDefault(),w.stopPropagation(),u()},children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Create First Hierarchy"]})]})]})}),c.jsx("div",{className:"flex justify-end gap-2 border-t px-6 py-4",children:c.jsx(p.Button,{variant:"outline",onClick:()=>y(!1),children:"Done"})})]})})})})}function Oy(e){switch(e){case"day":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];case"week":return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"Week of MMM DD, YYYY",label:"Week of Jan 15, 2024"},{value:"Week of MMMM DD, YYYY",label:"Week of January 15, 2024"},{value:"YYYY-WW",label:"2024-W03 (YYYY-WW)"},{value:"custom",label:"Custom Format..."}];case"month":return[{value:"MMM YYYY",label:"Jan 2024 (MMM YYYY)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MM/YYYY",label:"01/2024 (MM/YYYY)"},{value:"YYYY MMM",label:"2024 Jan (YYYY MMM)"},{value:"custom",label:"Custom Format..."}];case"quarter":return[{value:"Q1 YYYY",label:"Q1 2024 (Q1 YYYY)"},{value:"YYYY Q1",label:"2024 Q1 (YYYY Q1)"},{value:"1st Quarter YYYY",label:"1st Quarter 2024"},{value:"YYYY-Q1",label:"2024-Q1 (YYYY-Q1)"},{value:"Quarter 1, YYYY",label:"Quarter 1, 2024"},{value:"custom",label:"Custom Format..."}];case"year":return[{value:"YYYY",label:"2024 (YYYY)"},{value:"YY",label:"24 (YY)"},{value:"custom",label:"Custom Format..."}];case"hour":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:00 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:00 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"minute":return[{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:00 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"custom",label:"Custom Format..."}];case"second":return[{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"custom",label:"Custom Format..."}];default:return[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM-DD HH:mm",label:"2024-01-15 14:30 (YYYY-MM-DD HH:mm)"},{value:"YYYY-MM-DD HH:mm:ss",label:"2024-01-15 14:30:45 (YYYY-MM-DD HH:mm:ss)"},{value:"YYYY-MM-DD HH:mm Z",label:"2024-01-15 14:30 +00:00 (YYYY-MM-DD HH:mm Z)"},{value:"YYYY-MM-DD HH:mm:ss Z",label:"2024-01-15 14:30:45 +00:00 (YYYY-MM-DD HH:mm:ss Z)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}]}}function SKe({interaction:e,onUpdate:t,card:n,availableFields:r,onUpdateHierarchies:s,onManageHierarchies:o}){var T;const[i,a]=S.useState(!1),[l,u]=S.useState(!1),[d,f]=S.useState(null),[h,m]=S.useState(!1),[g,b]=S.useState({}),x=S.useMemo(()=>{var D;return((D=n.interactionConfig)==null?void 0:D.drillHierarchies)||[]},[(T=n.interactionConfig)==null?void 0:T.drillHierarchies]),y=S.useMemo(()=>{var R,H;const D=[],A=e.trigger;if(!A)return D;let P;if(A.type==="attribute"){const z=r.find(W=>W.id===A.field.id);z&&(z.dataType==="date"||z.dataType==="timestamp")&&(P=z)}else if(A.type==="metric"){const z=(H=(R=n.config)==null?void 0:R.groupByColumns)==null?void 0:H.find(U=>U.dataType==="date"||U.dataType==="timestamp");z&&(P=z)}if(P&&p.shouldAutoGenerateDateHierarchy(P,x)){const z=p.generateDateHierarchy(P);D.push(z)}return D},[r,x,e.trigger,n.config]),w=S.useMemo(()=>[...x,...y],[x,y]),v=w.find(D=>D.id===e.hierarchyId);Q.useEffect(()=>{i&&v&&v.type==="date"?f(v.id):i||f(null)},[i,v]);const C=D=>{if(y.some(P=>P.id===D)&&s){const P=y.find(R=>R.id===D);P&&s([...x,P])}t({...e,hierarchyId:D}),a(!1)},N=()=>{a(!1),u(!0),o&&o()},k=D=>{s&&s(D)},_=D=>D.steps.map(P=>P.field.label||P.field.name).join(" → "),j=D=>D&&D.charAt(0).toUpperCase()+D.slice(1),I=(D,A,P)=>{const R=[...D.steps];R[A]={...R[A],field:{...R[A].field,dateFormat:P,customFormat:P==="custom"?g[A]||"":void 0}};const H={...D,steps:R};if(s){const z=x.findIndex(U=>U.id===D.id);if(z>=0){const U=[...x];U[z]=H,s(U)}else s([...x,H])}},E=(D,A,P)=>{b(z=>({...z,[A]:P}));const R=[...D.steps];R[A]={...R[A],field:{...R[A].field,dateFormat:"custom",customFormat:P}};const H={...D,steps:R};if(s){const z=x.findIndex(U=>U.id===D.id);if(z>=0){const U=[...x];U[z]=H,s(U)}else s([...x,H])}};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Choose hierarchy"}),c.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Select which hierarchy to drill through when this interaction triggers"}),w.length>0?c.jsxs(c.Fragment,{children:[c.jsxs(p.Popover,{open:i,onOpenChange:a,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsxs(p.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[c.jsx("div",{className:"flex flex-1 flex-col items-start text-left",children:v?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{className:"font-medium",children:v.label||"Unnamed Hierarchy"})}),c.jsx("span",{className:"text-xs text-muted-foreground",children:_(v)})]}):c.jsx("span",{className:"text-muted-foreground",children:"Select hierarchy..."})}),c.jsxs("div",{className:"flex items-center gap-2",children:[v&&v.type==="date"&&c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:D=>{D.stopPropagation(),m(!h)},children:c.jsx(SR,{className:"h-3 w-3"})}),c.jsx(vr,{className:"h-4 w-4 shrink-0 opacity-50"})]})]})}),c.jsxs(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:[c.jsxs("div",{className:"flex items-center justify-between border-b p-3",children:[c.jsx("span",{className:"text-sm font-medium",children:"Select Hierarchy"}),c.jsxs(p.Button,{variant:"ghost",size:"sm",onClick:N,children:[c.jsx(wr,{className:"mr-1.5 h-3.5 w-3.5"}),"Create new"]})]}),c.jsxs("div",{className:"p-2",children:[y.length>0&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-3 py-2",children:c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"AUTO-GENERATED"})}),y.map(D=>c.jsx("div",{className:`cursor-pointer rounded-md p-3 hover:bg-muted ${e.hierarchyId===D.id?"bg-muted":""}`,onClick:()=>C(D.id),children:c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{className:"text-sm font-medium",children:D.label||"Unnamed Hierarchy"})}),c.jsx("div",{className:"text-xs text-muted-foreground",children:_(D)})]})},D.id))]}),x.length>0&&c.jsxs(c.Fragment,{children:[y.length>0&&c.jsx("div",{className:"my-2 border-t"}),x.map(D=>c.jsx("div",{className:`cursor-pointer rounded-md p-3 hover:bg-muted ${e.hierarchyId===D.id?"bg-muted":""}`,onClick:()=>C(D.id),children:c.jsxs("div",{className:"space-y-1",children:[c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{className:"text-sm font-medium",children:D.label||"Unnamed Hierarchy"})}),c.jsx("div",{className:"text-xs text-muted-foreground",children:_(D)})]})},D.id))]})]})]})]}),v&&v.type==="date"&&h&&c.jsxs("div",{className:"mt-3 space-y-3 rounded-md border border-border p-3",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Customize Date Formats"}),c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-6 text-xs",onClick:()=>m(!1),children:"Close"})]}),v.steps.map((D,A)=>{var z;const P=D.field.granularity;if(!P)return null;const R=Oy(P),H=D.field.dateFormat||((z=R[0])==null?void 0:z.value);return c.jsxs("div",{className:"space-y-1",children:[c.jsx(p.Label,{className:"text-xs font-medium text-muted-foreground",children:D.field.label||j(P)}),c.jsxs(p.Select,{value:H,onValueChange:U=>{I(v,A,U)},children:[c.jsx(p.SelectTrigger,{className:"h-8 text-xs",children:c.jsx(p.SelectValue,{})}),c.jsx(p.SelectContent,{children:R.map(U=>c.jsx(p.SelectItem,{value:U.value,className:"text-xs",children:U.label},U.value))})]}),H==="custom"&&c.jsxs("div",{className:"mt-2 space-y-1",children:[c.jsx(p.Input,{placeholder:"Enter custom format (e.g., YYYY-MM-DD)",value:D.field.customFormat||g[A]||"",onChange:U=>{E(v,A,U.target.value)},className:"h-8 text-xs"}),c.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Common tokens: YYYY (year), MM (month), DD (day), HH (hour), mm (minute)"})]})]},A)})]})]}):c.jsxs("div",{className:"rounded-md border border-dashed p-6 text-center",children:[c.jsx("p",{className:"mb-2 text-sm text-muted-foreground",children:"No hierarchies configured"}),c.jsx("p",{className:"mb-4 text-xs text-muted-foreground",children:"Create a hierarchy to define your drill path"}),c.jsxs(p.Button,{variant:"outline",size:"sm",onClick:N,children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Create hierarchy"]})]})]}),c.jsx(wKe,{open:l,onOpenChange:u,drillHierarchies:x,onUpdateHierarchies:k,availableFields:r})]})}function CKe({fields:e,selectedFieldIds:t,onSelectionChange:n,searchPlaceholder:r="Search fields...",className:s=""}){const[o,i]=S.useState(""),a=e.filter(d=>d.label.toLowerCase().includes(o.toLowerCase())||d.qualifiedEntityName&&d.qualifiedEntityName.toLowerCase().includes(o.toLowerCase())),l=()=>{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 c.jsxs("div",{className:`space-y-2 ${s}`,children:[c.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[c.jsx(p.Input,{placeholder:r,value:o,onChange:d=>i(d.target.value),className:"flex-1"}),c.jsxs("span",{className:"text-xs text-muted-foreground",children:[a.length," fields"]})]}),c.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[c.jsx(p.Button,{size:"sm",variant:"outline",onClick:l,children:"Select All"}),c.jsx(p.Button,{size:"sm",variant:"outline",onClick:u,children:"Deselect All"}),c.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," selected"]})]}),c.jsx("div",{className:"grid max-h-32 grid-cols-2 gap-2 overflow-y-auto rounded border p-2",children:a.map(d=>c.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded p-2 text-xs hover:bg-muted/50",children:[c.jsx(En,{checked:t.includes(d.id),onCheckedChange:f=>{n(f?[...t,d.id]:t.filter(h=>h!==d.id))}}),c.jsx("span",{className:"font-medium",children:d.label})]},d.id))}),o&&a.length===0&&c.jsxs("div",{className:"py-4 text-center text-sm text-muted-foreground",children:['No fields found matching "',o,'"']})]})}const NKe=e=>["string","boolean"].includes(p.getDataType(e.dataType));function kKe({interaction:e,availableFields:t,onUpdate:n}){var i;const r=t.filter(NKe),s=((i=e.availableFields)==null?void 0:i.map(a=>a.id))||[],o=a=>{const l=r.filter(u=>a.includes(u.id));n({...e,availableFields:l})};return c.jsx("div",{className:"space-y-4",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{children:"Available dimensions"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose which fields users can explore dynamically"}),c.jsx(CKe,{fields:r,selectedFieldIds:s,onSelectionChange:o,searchPlaceholder:"Search fields..."}),s.length===0&&c.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ Please select at least one field"})]})})}function _Ke({value:e,onChange:t}){const[n,r]=S.useState(!1),[s,o]=S.useState(""),[i,a]=S.useState("all"),{currentUser:l}=zi(),{data:u,isLoading:d}=LR($r.DASHBOARD,s),f=(u==null?void 0:u.dashboards)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(l==null?void 0:l.id):!0),m=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),o("")};return c.jsxs(p.Popover,{open:n,onOpenChange:r,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsx(p.Button,{variant:"outline",className:p.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:m?c.jsx("span",{className:"truncate",children:m.title}):"Choose dashboard..."})}),c.jsx(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:c.jsxs(p.Tabs,{value:i,onValueChange:b=>a(b),children:[c.jsx("div",{className:"p-3 border-b",children:c.jsxs("div",{className:"relative",children:[c.jsx(Xs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(p.Input,{placeholder:"Search all dashboards...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]})}),c.jsxs(p.TabsList,{className:"w-full justify-start rounded-none border-b bg-transparent p-0",children:[c.jsx(p.TabsTrigger,{value:"me",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"created by me"}),c.jsx(p.TabsTrigger,{value:"all",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"all"})]}),c.jsx(p.TabsContent,{value:i,className:"mt-0",children:c.jsx(p.ScrollArea,{className:"h-[300px]",children:d?c.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading dashboards..."}):h.length===0?c.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:s?`No dashboards found matching "${s}"`:i==="me"?"No dashboards created by you":"No dashboards available"}):c.jsx("div",{className:"p-2",children:h.map(b=>c.jsxs("button",{onClick:()=>g(b),className:p.cn("w-full flex items-start gap-3 p-3 rounded-md hover:bg-muted/50 transition-colors text-left",e===b.id&&"bg-muted"),children:[c.jsx(ep,{className:"h-5 w-5 mt-0.5 text-muted-foreground flex-shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"font-medium text-sm truncate",children:b.title}),c.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:jKe(b.createdAt)})]})]},b.id))})})})]})})]})}function jKe(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(),l=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${l}`}const s=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),o=t.getDate();return`${s} ${o}`}function EKe({interaction:e,onUpdate:t}){return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Target dashboard"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select which dashboard to navigate to when this interaction triggers"}),c.jsx(_Ke,{value:e.targetDashboardId,onChange:(n,r)=>{const s={...e,targetDashboardId:n};!e.label&&r&&(s.label=r),t(s)}})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Propagate Filters"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose what filters to pass to the target dashboard"}),c.jsxs(p.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsxs(p.SelectValue,{placeholder:"Choose context mode...",children:[e.contextMode==="interactionFilters"&&"Interaction Filters",(e.contextMode==="full"||!e.contextMode)&&"All Filters",e.contextMode==="none"&&"None"]})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"interactionFilters",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"Interaction Filters"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass only the clicked element as a filter"})]})}),c.jsx(p.SelectItem,{value:"full",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"All Filters"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass current dashboard filters + clicked element"})]})}),c.jsx(p.SelectItem,{value:"none",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"None"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Navigate without passing any filters"})]})})]})]})]}),!e.targetDashboardId&&c.jsx("div",{className:"rounded-md bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3",children:c.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"⚠ Please select a target dashboard to complete this configuration"})}),e.targetDashboardId&&c.jsx("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:c.jsx("p",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Dashboard drill-through configured successfully"})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(p.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:jh(e.mode)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function IKe({value:e,onChange:t}){const[n,r]=S.useState(!1),[s,o]=S.useState(""),[i,a]=S.useState("all"),{currentUser:l}=zi(),{data:u,isLoading:d}=LR($r.VISUAL,s),f=(u==null?void 0:u.visuals)||[],h=f.filter(b=>i==="me"?b.ownership.createdBy.userId===(l==null?void 0:l.id):!0),m=f.find(b=>b.id===e),g=b=>{t(b.id,b.title),r(!1),o("")};return c.jsxs(p.Popover,{open:n,onOpenChange:r,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsx(p.Button,{variant:"outline",className:p.cn("w-full justify-start text-left font-normal",!e&&"text-muted-foreground"),children:m?c.jsx("span",{className:"truncate",children:m.title}):"Choose insight..."})}),c.jsx(p.PopoverContent,{className:"w-[500px] p-0",align:"start",children:c.jsxs(p.Tabs,{value:i,onValueChange:b=>a(b),children:[c.jsx("div",{className:"p-3 border-b",children:c.jsxs("div",{className:"relative",children:[c.jsx(Xs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),c.jsx(p.Input,{placeholder:"Search all insights...",value:s,onChange:b=>o(b.target.value),className:"pl-9"})]})}),c.jsxs(p.TabsList,{className:"w-full justify-start rounded-none border-b bg-transparent p-0",children:[c.jsx(p.TabsTrigger,{value:"me",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"created by me"}),c.jsx(p.TabsTrigger,{value:"all",className:"rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent",children:"all"})]}),c.jsx(p.TabsContent,{value:i,className:"mt-0",children:c.jsx(p.ScrollArea,{className:"h-[300px]",children:d?c.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"Loading insights..."}):h.length===0?c.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:s?`No insights found matching "${s}"`:i==="me"?"No insights created by you":"No insights available"}):c.jsx("div",{className:"p-2",children:h.map(b=>c.jsxs("button",{onClick:()=>g(b),className:p.cn("w-full flex items-start gap-3 p-3 rounded-md hover:bg-muted/50 transition-colors text-left",e===b.id&&"bg-muted"),children:[c.jsx(p.ChartColumn,{className:"h-5 w-5 mt-0.5 text-muted-foreground flex-shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"font-medium text-sm truncate",children:b.title}),c.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:TKe(b.createdAt)})]})]},b.id))})})})]})})]})}function TKe(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(),l=i>=12?"PM":"AM",u=i%12||12,d=a.toString().padStart(2,"0");return`TODAY AT ${u}:${d} ${l}`}const s=t.toLocaleString("en-US",{month:"short"}).toUpperCase(),o=t.getDate();return`${s} ${o}`}function DKe({interaction:e,onUpdate:t}){return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Target insight"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select the saved insight to navigate to"}),c.jsx(IKe,{value:e.targetInsightId,onChange:(n,r)=>{const s={...e,targetInsightId:n};!e.label&&r&&(s.label=r),t(s)}})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Propagate Filters"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose what filters to pass to the insight"}),c.jsxs(p.Select,{value:e.contextMode||"full",onValueChange:n=>t({...e,contextMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsxs(p.SelectValue,{placeholder:"Choose context mode...",children:[e.contextMode==="interactionFilters"&&"Interaction Filters",(e.contextMode==="full"||!e.contextMode)&&"All Filters",e.contextMode==="none"&&"None"]})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"interactionFilters",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"Interaction Filters"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass only the clicked element as a filter"})]})}),c.jsx(p.SelectItem,{value:"full",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"All Filters"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Pass all current filters and selections"})]})}),c.jsx(p.SelectItem,{value:"none",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"None"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Open insight without any filters"})]})})]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Display mode"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose how the insight should be displayed"}),c.jsxs(p.Select,{value:e.displayMode||"modal",onValueChange:n=>t({...e,displayMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsx(p.SelectValue,{placeholder:"Choose display mode..."})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"modal",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"Open in modal"})})}),c.jsx(p.SelectItem,{value:"replace-card",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"Replace the card"})})})]})]})]}),!e.targetInsightId&&c.jsx("div",{className:"rounded-md bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 p-3",children:c.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"⚠ Please enter a target insight ID to complete this configuration"})}),e.targetInsightId&&c.jsx("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:c.jsx("p",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Insight drill-through configured successfully"})}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(p.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:jh(e.mode)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function MKe(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 AKe(){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 RKe(e,t){const n=`{{${t}}}`;return e.includes(n)}function FKe(e,t){return t.filter(n=>RKe(e,n.id))}function PKe(e,t,n){const r=`{{${t}}}`,s=e.slice(0,n)+r+e.slice(n),o=n+r.length;return{newTemplate:s,newCursorPosition:o}}function OKe(e,t){let n=e;return t.forEach(r=>{const s=`{{${r.id}}}`;let o;if(r.category==="identifier")o=`${r.id.toUpperCase()}-abc123`;else{const i=r.label.toLowerCase();i.includes("name")?o="Example Name":i.includes("region")||i.includes("location")?o="California":i.includes("id")?o="ID-12345":i.includes("category")?o="Category A":o="Sample Value"}n=n.replace(new RegExp(s,"g"),o)}),n}function LKe({open:e,onOpenChange:t,interaction:n,availableFields:r,onSave:s}){const[o,i]=S.useState(n.urlTemplate||""),[a,l]=S.useState(0),[u,d]=S.useState(n.encodeParameters!==!1),[f,h]=S.useState(n.label||""),m=S.useRef(null);S.useEffect(()=>{e&&(i(n.urlTemplate||""),d(n.encodeParameters!==!1),h(n.label||""),l(0))},[e,n.urlTemplate,n.encodeParameters,n.label]);const g=MKe(r),b=AKe(),x=[...g,...b],y=FKe(o,x),w=p.validateURLTemplate(o),v=o&&w.valid?OKe(o,y):"",C=E=>{i(E.target.value),l(E.target.selectionStart)},N=E=>{const T=E.target;l(T.selectionStart)},k=E=>{const T=E.target;l(T.selectionStart)},_=E=>{const{newTemplate:T,newCursorPosition:D}=PKe(o,E.id,a);i(T),l(D),m.current&&(m.current.focus(),setTimeout(()=>{m.current&&m.current.setSelectionRange(D,D)},0))},j=()=>{w.valid&&(s({...n,urlTemplate:o,parameters:y,encodeParameters:u,label:f}),t(!1))},I=()=>{t(!1)};return c.jsx(yo,{open:e,onOpenChange:t,children:c.jsxs(Js,{className:"max-h-[90vh] max-w-5xl overflow-y-auto",onOpenAutoFocus:E=>{E.preventDefault(),setTimeout(()=>{var T;(T=m.current)==null||T.focus()},0)},children:[c.jsxs(Bi,{children:[c.jsx(eo,{children:"Configure Drill to URL"}),c.jsx(Bo,{children:"Build a custom URL with dynamic parameters that will open when users click on chart elements."})]}),c.jsxs("div",{className:"flex flex-col gap-6 py-4",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-6",children:[c.jsxs("div",{className:"flex flex-col gap-4",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(p.Label,{htmlFor:"url-template",children:"URL"}),c.jsx(p.TooltipProvider,{children:c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx(p.Info,{className:"h-4 w-4 text-muted-foreground"})}),c.jsx(p.TooltipContent,{children:c.jsx("p",{className:"max-w-xs text-xs",children:"Enter your URL and click parameters from the right panel to insert them. Parameters will be replaced with actual values when the URL is opened."})})]})})]}),c.jsx(hh,{ref:m,id:"url-template",value:o,onChange:C,onClick:N,onKeyUp:k,placeholder:"https://example.com/product/{{product_id}}?region={{region}}",className:"min-h-[200px] font-mono text-sm"}),!w.valid&&o&&c.jsx("div",{className:"rounded-lg border border-destructive bg-destructive/10 p-3",children:c.jsx("div",{className:"text-sm text-destructive",children:w.errors.map((E,T)=>c.jsx("div",{children:E},T))})}),v&&c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-xs text-muted-foreground",children:"Preview:"}),c.jsx("div",{className:"rounded-md bg-muted p-3",children:c.jsx("p",{className:"break-all font-mono text-xs",children:v})})]})]}),c.jsxs("div",{className:"flex flex-col gap-4",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(p.Label,{children:"Parameters"}),c.jsx(p.TooltipProvider,{children:c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx(p.Info,{className:"h-4 w-4 text-muted-foreground"})}),c.jsx(p.TooltipContent,{children:c.jsx("p",{className:"max-w-xs text-xs",children:"Click any parameter to insert it into your URL at the cursor position. Attributes come from your chart data, Identifiers are system values."})})]})})]}),c.jsxs("div",{className:"flex flex-col gap-6 rounded-lg border p-4",children:[c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Attributes"}),c.jsxs("div",{className:"space-y-1",children:[g.map(E=>c.jsx(D9,{parameter:E,isUsed:y.some(T=>T.id===E.id),onClick:()=>_(E)},E.id)),g.length===0&&c.jsx("p",{className:"text-sm text-muted-foreground",children:"No attributes available"})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Identifiers"}),c.jsx("div",{className:"space-y-1",children:b.map(E=>c.jsx(D9,{parameter:E,isUsed:y.some(T=>T.id===E.id),onClick:()=>_(E)},E.id))})]})]})]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(En,{id:"encode-params",checked:u,onCheckedChange:E=>d(E===!0)}),c.jsx(p.Label,{htmlFor:"encode-params",className:"cursor-pointer text-sm font-normal",children:"URL encode parameters"}),c.jsx(p.TooltipProvider,{children:c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx(p.Info,{className:"h-4 w-4 text-muted-foreground"})}),c.jsx(p.TooltipContent,{children:c.jsx("p",{className:"max-w-xs text-xs",children:"Recommended. Encodes special characters in parameter values to ensure valid URLs (e.g., spaces become %20)."})})]})})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(p.TooltipProvider,{children:c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx(p.Info,{className:"h-4 w-4 text-muted-foreground"})}),c.jsx(p.TooltipContent,{children:c.jsx("p",{className:"max-w-xs text-xs",children:"How this interaction appears when multiple actions are available"})})]})})]}),c.jsx(p.Input,{value:f,onChange:E=>h(E.target.value),placeholder:jh("drillToURL")})]}),c.jsxs("div",{className:"flex items-start gap-2 rounded-lg border bg-muted/50 p-3",children:[c.jsx(p.Info,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"URLs will always open in a new browser tab when clicked."})]})]}),c.jsxs(vc,{children:[c.jsx(p.Button,{variant:"outline",onClick:I,children:"Cancel"}),c.jsx(p.Button,{onClick:j,disabled:!w.valid,children:"Save"})]})]})})}function D9({parameter:e,isUsed:t,onClick:n}){var o,i;const r=e.category==="attribute"?"🏷️":"#",s=((o=e.field)==null?void 0:o.qualifiedFieldName)||((i=e.field)==null?void 0:i.name);return c.jsxs(p.Button,{type:"button",variant:"ghost",className:"h-auto w-full justify-start gap-2 px-3 py-2 font-normal hover:bg-accent",onClick:n,children:[c.jsx("span",{className:"text-base",children:r}),c.jsxs("div",{className:"flex flex-1 flex-col items-start gap-0.5",children:[c.jsx("span",{className:"text-sm",children:e.label}),s&&c.jsx("span",{className:"text-xs text-muted-foreground",children:s})]}),t&&c.jsx(rs,{variant:"secondary",className:"ml-auto gap-1",children:c.jsx(p.Check,{className:"h-3 w-3"})})]})}function $Ke({interaction:e,availableFields:t,onUpdate:n}){const[r,s]=S.useState(!1),o=!!e.urlTemplate;return c.jsxs("div",{className:"flex flex-col gap-4",children:[o?c.jsxs("div",{className:"flex flex-col gap-3 rounded-lg border p-4",children:[c.jsxs("div",{className:"flex items-start justify-between gap-4",children:[c.jsxs("div",{className:"flex-1 space-y-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(Jm,{className:"h-4 w-4 text-muted-foreground"}),c.jsx("span",{className:"text-sm font-medium",children:"URL Template"})]}),c.jsx("div",{className:"rounded-md bg-muted p-3",children:c.jsx("p",{className:"break-all font-mono text-xs",children:e.urlTemplate})})]}),c.jsxs(p.Button,{variant:"outline",size:"sm",onClick:()=>s(!0),children:[c.jsx(CR,{className:"mr-2 h-4 w-4"}),"Edit"]})]}),e.parameters&&e.parameters.length>0&&c.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.parameters.length," parameter",e.parameters.length!==1?"s":""," configured"]}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:["URL encoding:"," ",e.encodeParameters!==!1?"enabled":"disabled"]})]}):c.jsxs("div",{className:"flex flex-col items-center gap-3 rounded-lg border border-dashed p-8",children:[c.jsx(Jm,{className:"h-8 w-8 text-muted-foreground"}),c.jsx("p",{className:"text-sm text-muted-foreground",children:"No URL configured"}),c.jsx(p.Button,{variant:"outline",size:"sm",onClick:()=>s(!0),children:"Add Custom URL"})]}),c.jsx(LKe,{open:r,onOpenChange:s,interaction:e,availableFields:t,onSave:n})]})}function zKe({interaction:e,onUpdate:t}){return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Fetch mode"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose when to load the detailed data"}),c.jsxs(p.Select,{value:e.fetchMode||"lazy",onValueChange:n=>t({...e,fetchMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsx(p.SelectValue,{placeholder:"Choose fetch mode..."})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"lazy",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"Lazy loading"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Fetch data only when user clicks"})]})}),c.jsx(p.SelectItem,{value:"preloaded",children:c.jsxs("div",{className:"flex flex-col items-start gap-1 py-1",children:[c.jsx("span",{className:"font-medium",children:"Preloaded"}),c.jsx("span",{className:"text-xs text-muted-foreground",children:"Fetch all data when dashboard loads"})]})})]})]}),c.jsxs("div",{className:"rounded-md bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 p-3 flex gap-2",children:[c.jsx(p.Info,{className:"h-4 w-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0"}),c.jsx("div",{className:"text-xs text-blue-800 dark:text-blue-200",children:e.fetchMode==="lazy"?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"font-medium",children:"Lazy loading"}),c.jsx("div",{className:"mt-1",children:"Data is fetched on-demand when the user clicks. Best for large datasets or when detailed data isn't always needed."})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"font-medium",children:"Preloaded"}),c.jsx("div",{className:"mt-1",children:"Data is fetched when the dashboard loads. Best for small datasets or when instant drill-down is required."})]})})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Record limit"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Maximum number of detailed records to show (0 for unlimited)"}),c.jsx(p.Input,{type:"number",min:"0",placeholder:"100",value:e.inlineLimit??100,onChange:n=>{const r=parseInt(n.target.value)||0;t({...e,inlineLimit:r})}})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Display mode"}),c.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"How to display the detailed records"}),c.jsxs(p.Select,{value:e.displayMode||"table",onValueChange:n=>t({...e,displayMode:n}),children:[c.jsx(p.SelectTrigger,{children:c.jsx(p.SelectValue,{placeholder:"Choose display mode..."})}),c.jsxs(p.SelectContent,{children:[c.jsx(p.SelectItem,{value:"table",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"Table view"})})}),c.jsx(p.SelectItem,{value:"list",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"List view"})})}),c.jsx(p.SelectItem,{value:"cards",children:c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("span",{children:"Card view"})})})]})]})]}),c.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 bg-background",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Show in modal"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Display detailed records in a modal overlay"})]}),c.jsx(p.Switch,{checked:e.showInModal??!1,onCheckedChange:n=>t({...e,showInModal:n})})]}),c.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3 bg-background",children:[c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Allow export"}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"Enable users to export the detailed records"})]}),c.jsx(p.Switch,{checked:e.allowExport??!0,onCheckedChange:n=>t({...e,allowExport:n})})]}),c.jsxs("div",{className:"rounded-md bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-3",children:[c.jsx("div",{className:"text-xs text-green-800 dark:text-green-200",children:"✓ Inline drill configured successfully"}),c.jsxs("div",{className:"mt-2 space-y-1 text-xs text-green-700 dark:text-green-300",children:[c.jsxs("div",{children:["Mode: ",e.fetchMode==="lazy"?"Lazy loading":"Preloaded"]}),c.jsxs("div",{children:["Limit: ",e.inlineLimit===0?"Unlimited":`${e.inlineLimit} records`]}),c.jsxs("div",{children:["Display: ",e.displayMode==="table"?"Table view":e.displayMode==="list"?"List view":"Card view"]})]})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-sm font-medium",children:"Menu label"}),c.jsx(p.Input,{value:e.label||"",onChange:n=>t({...e,label:n.target.value}),placeholder:jh(e.mode)}),c.jsx("p",{className:"text-xs text-muted-foreground",children:"How this interaction appears when multiple actions are available"})]})]})}function BKe({interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i,onRemove:a}){const l=e.trigger!==void 0,u=e.mode!==void 0,d=l&&u,[f,h]=S.useState(!d),m=()=>{var y;if(!l)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||jh(e.mode);return`${b} → ${x}`},g=u?XC(e.mode):null;return c.jsxs(Xm,{className:"relative p-0",children:[c.jsx(p.Button,{variant:"ghost",size:"sm",className:"absolute right-2 top-2 z-10 h-8 w-8 p-0",onClick:a,"aria-label":"Remove interaction",children:c.jsx(p.X,{className:"h-3 w-3"})}),c.jsxs(mc,{open:f,onOpenChange:h,children:[c.jsx(pc,{asChild:!0,children:c.jsxs(p.Button,{variant:"ghost",className:"h-auto w-full justify-between p-4 pr-12 hover:bg-muted/50",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[g&&c.jsx(g,{className:"h-4 w-4 flex-shrink-0"}),c.jsx("span",{className:"text-left text-sm font-medium",children:m()})]}),f?c.jsx(wR,{className:"h-3 w-3 flex-shrink-0"}):c.jsx(PN,{className:"h-3 w-3 flex-shrink-0"})]})}),c.jsx(gc,{children:c.jsxs("div",{className:"space-y-6 border-t p-6",children:[c.jsx("div",{className:"space-y-3",children:l?c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"text-sm font-medium",children:["When I click on"," ",c.jsx("span",{className:"text-muted-foreground",children:"(value of)"})]}),e.trigger&&c.jsxs("div",{className:"inline-flex cursor-pointer items-center gap-2 rounded-md border bg-background px-3 py-2 hover:bg-muted/50",onClick:()=>{i({...e,trigger:void 0})},children:[QC(e.trigger.field.dataType),c.jsx("span",{className:"text-sm font-medium",children:e.trigger.field.label})]})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-sm font-medium",children:"When I click on"}),c.jsx(tYe,{value:e.trigger,onChange:b=>{i({...e,trigger:b})},metrics:t,attributes:n})]})}),l&&c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-sm font-medium",children:"I want to"}),c.jsx(nYe,{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}}})]})}),l&&u&&c.jsxs(c.Fragment,{children:[c.jsx(p.Separator,{}),c.jsx(VKe,{interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i})]})]})})]})]})}function VKe({interaction:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:i}){switch(e.mode){case"clickFilter":return c.jsx(rYe,{interaction:e,onUpdate:a=>i(a)});case"drillDown":return c.jsx(SKe,{interaction:e,onUpdate:a=>i(a),card:s,availableFields:r,onUpdateHierarchies:o});case"dynamicDrill":return c.jsx(kKe,{interaction:e,onUpdate:a=>i(a),availableFields:r});case"drillThrough":return c.jsx(EKe,{interaction:e,onUpdate:a=>i(a)});case"drillToDetail":return c.jsx(DKe,{interaction:e,onUpdate:a=>i(a)});case"drillToURL":return c.jsx($Ke,{interaction:e,availableFields:[...t,...n],onUpdate:a=>i(a)});case"inlineDrill":return c.jsx(zKe,{interaction:e,onUpdate:a=>i(a)});default:return c.jsx("div",{className:"text-sm text-muted-foreground",children:"Unknown interaction type"})}}function HKe({interactions:e,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onChange:i}){const[a,l]=S.useState(null),u=()=>{const h=Jqe().id,m={id:h};i([...e,m]),l(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)&&l(null)};return c.jsxs("div",{className:"space-y-4",children:[e.length>0?c.jsx("div",{className:"space-y-3",children:e.map((h,m)=>c.jsx(BKe,{interaction:h,metrics:t,attributes:n,availableFields:r,card:s,onUpdateHierarchies:o,onUpdate:g=>d(m,g),onRemove:()=>f(m)},h.id||m))}):c.jsx("div",{className:"border rounded-lg p-8 text-center bg-muted/30",children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-sm font-medium",children:"No interactions configured"}),c.jsx("div",{className:"text-xs text-muted-foreground",children:'Click "Add Interaction" to create your first interaction'}),c.jsx("div",{className:"pt-2",children:c.jsxs(p.Button,{onClick:u,size:"sm",variant:"outline",children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Add First Interaction"]})})]})}),e.length>0&&c.jsx("div",{className:"flex justify-start pt-2",children:c.jsxs(p.Button,{onClick:u,size:"sm",variant:"outline",children:[c.jsx(wr,{className:"mr-2 h-4 w-4"}),"Add Interaction"]})})]})}const UKe=[],qKe=[],WKe=[];function NT(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}function YKe(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 G5(e){var C;const{tokenProps:t}=mt(),n=p.useDashboardStore(N=>N.authToken)||e,{selectedConnection:r,hasSchemaSupport:s}=gK(e),o=p.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.connectionId}),i=p.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.semanticDomainId}),a=p.useEditorStore(N=>{var k;return(k=N.card.dataSource)==null?void 0:k.selectedEntities}),l=S.useMemo(()=>(a==null?void 0:a.filter(N=>N.type==="model"))||UKe,[a]),u=S.useMemo(()=>(a==null?void 0:a.filter(N=>p.DATABASE_ENTITY_TYPES.includes(N.type)))||qKe,[a]),d=S.useMemo(()=>(a==null?void 0:a.filter(N=>N.type==="dataset"))||WKe,[a]);function f(N){var k;if(N.type==="dataset")return!!o&&!!N.domainId&&!!N.name;if(N.type==="model")return!!o&&!!N.id;if(p.DATABASE_ENTITY_TYPES.includes(N.type)){const _=((k=r==null?void 0:r.capabilities)==null?void 0:k.path)||[],j=_.includes("database"),I=_.includes("schema")||s;return!(!o||!N.name||j&&!N.database||I&&!N.schema)}return!1}const h=[...l,...u,...d],m=Ap({queries:h.map(N=>{let k={};return N.type==="model"?k=NT({connection_id:o,datamodel_id:N.id,database_name:"",schema_name:"",table_name:""}):N.type==="dataset"?k=NT({connection_id:N.connectionId,domain_id:N.domainId,dataset_name:N.name,database_name:N.database,schema_name:N.schema,table_name:N.table}):k=NT({connection_id:o,datamodel_id:"",database_name:N.database,schema_name:N.schema,table_name:N.name}),{queryKey:["columns",o,N,i||null],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",k),enabled:!!o&&f(N)}})}),g=m.some(N=>N.isPending&&N.fetchStatus==="fetching"),b=m.some(N=>N.isError),x=(C=m.find(N=>N.isError))==null?void 0:C.error,y=m.map((N,k)=>{var D,A;const _=h[k],j=((D=N.data)==null?void 0:D.columns)||[],I=_.type==="dataset"?(A=j.find(P=>P.entityName))==null?void 0:A.entityName:void 0,E=I||_.name,T=p.getQualifiedEntityName(_.type==="dataset"&&I?{..._,name:I}:_);return{entityId:_.id||_.name,entityType:_.type,entityName:E,label:_.label,description:_.description,qualifiedEntityName:T,columns:j.map(P=>{const R=_.type==="dataset"?P.entityName||E:_.name,H=P.qualifiedEntityName||(_.type==="dataset"&&R?p.getQualifiedEntityName({..._,name:R}):T);return{id:`${R}-${P.column_name}`,name:P.column_name,qualifiedFieldName:P.qualifiedFieldName||P.column_name,dataType:P.data_type,label:P.label||p.toLabel(P.column_name),description:P.description||"",qualifiedEntityName:H,entityId:P.entityId||_.id||_.id||R,entityName:R,entityType:P.entityType||_.type,role:P.role,expression:P.expression,calculatedFormula:P.calculatedFormula,derivedField:P.derivedField,format:p.fromSemanticFormat(P.format),aggregate:P.aggregate}})}}).filter(N=>{var k;return((k=N==null?void 0:N.columns)==null?void 0:k.length)>0})||[],w=m.flatMap(N=>{var k;return((k=N.data)==null?void 0:k.calculatedFields)||[]}).map(N=>({...N,id:p.getStableDomainCalculatedFieldId({...N}),fieldScope:"domain"}));if(w.length>0){const N=new Map;w.forEach(k=>{const _=p.getStableDomainCalculatedFieldId(k);N.has(_)||N.set(_,k)}),y.unshift({entityId:p.CALCULATED_FIELDS_GROUP_ID,entityType:"dataset",entityName:p.CALCULATED_FIELDS_GROUP_NAME,label:"Calculated Fields",description:"Domain-level calculated metrics and dimensions",qualifiedEntityName:p.CALCULATED_FIELDS_GROUP_NAME,columns:Array.from(N.values())})}const v=YKe(y);return{columnGroups:y,columns:v,isLoading:g,hasError:b,error:x,refetch:async()=>{await Promise.all(m.map(N=>N.refetch()))}}}function GKe(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 oN(e){return Array.isArray(e)?e.map(t=>oN(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]=oN(r),t),{}):e}function kT(e,t){return JSON.stringify(oN(e))===JSON.stringify(oN(t))}function KKe(){var B,V,F,q,G,X,J,fe,ue;const{open:e,frameId:t,cardId:n,closePopover:r,anchorPosition:s}=IF(),{authToken:o,tokenProps:i}=mt(),a=qr(),{updateCurrentDashboardCard:l,updateFrameCard:u}=p.useDashboardActions(),{setCard:d}=p.useEditorActions(),f=p.useDashboardStore(pe=>pe.dashboard),h=((B=f==null?void 0:f.sheets)==null?void 0:B.flatMap(pe=>pe.frames||[]).find(pe=>(pe==null?void 0:pe.id)===t))||null,m=h&&n?h.cards.find(pe=>pe.id===n):null,g=!!(h!=null&&h.visualId&&m),b=HN((h==null?void 0:h.visualId)||"",{enabled:e&&g&&!!(o!=null&&o.accessToken)&&!!(i!=null&&i.apiServiceUrl)}),x=((V=b.data)==null?void 0:V.frameObject)||((q=(F=b.data)==null?void 0:F.visual)==null?void 0:q.frameObject),y=S.useMemo(()=>GKe(x),[x]),w=((G=b.data)==null?void 0:G.lastModified)||((J=(X=b.data)==null?void 0:X.visual)==null?void 0:J.lastModified),v=S.useMemo(()=>{if(!m||!h||!y)return null;const pe=m.linkedSourceCardId&&y.cards.find(ie=>ie.id===m.linkedSourceCardId);if(pe)return pe;const ye=h.cards.findIndex(ie=>ie.id===m.id);return ye>=0&&y.cards[ye]||null},[m,h,y]),C=S.useMemo(()=>{const pe=new Map;return!h||!y||h.cards.forEach((ye,ie)=>{var se;const ae=ye.linkedSourceCardId||((se=y.cards[ie])==null?void 0:se.id);ae&&pe.set(ae,ye.id)}),pe},[h,y]),N=S.useMemo(()=>{var ye;if(!v)return[];const pe=Md((ye=v.interactionConfig)==null?void 0:ye.interactions);return a1(pe,C)},[v,C]),k=S.useMemo(()=>m?mT(N,m.linkedInteractionTargetOverrides):[],[m,N]),_=g?v:m,j=g&&!!x&&!y&&!b.isFetching;S.useEffect(()=>{if(!e)return;const pe=g&&v||m;pe&&d(pe)},[e,g,v,m,d]);const{columns:I}=G5(),E=_==null?void 0:_.config,T=I,D=(E==null?void 0:E.metricColumns)||[],A=[...(E==null?void 0:E.groupByColumns)||[],...(E==null?void 0:E.pivotByColumns)||[]],[P,R]=S.useState(((fe=_==null?void 0:_.interactionConfig)==null?void 0:fe.drillHierarchies)||[]),[H,z]=S.useState(((ue=_==null?void 0:_.interactionConfig)==null?void 0:ue.allowedDrillTargets)||[]),[U,W]=S.useState([]),[O,Z]=S.useState(!1),Y=S.useRef(null),M=S.useMemo(()=>`${e}-${t}-${n}-${g?(v==null?void 0:v.id)||"loading":(m==null?void 0:m.id)||"none"}`,[e,t,n,g,v==null?void 0:v.id,m==null?void 0:m.id]);S.useEffect(()=>{e||(Y.current=null)},[e]),S.useEffect(()=>{var pe,ye,ie;!e||!_||g&&!v||Y.current!==M&&(R(((pe=_.interactionConfig)==null?void 0:pe.drillHierarchies)||[]),z(((ye=_.interactionConfig)==null?void 0:ye.allowedDrillTargets)||[]),W(g?k:Md((ie=_.interactionConfig)==null?void 0:ie.interactions)),Y.current=M)},[e,_,M,g,v,k]);const K=async()=>{var pe,ye,ie,ae,se;if(m){Z(!0);try{const Ie=Md(p.normalizeInteractionsForSave(U));if(!g||!(h!=null&&h.visualId)||!y||!v){const ze={...m,interactionConfig:{...m.interactionConfig,drillHierarchies:P,allowedDrillTargets:H,interactions:Ie}},Ve=(ye=(pe=f==null?void 0:f.sheets)==null?void 0:pe.find(Ke=>(Ke.frames||[]).some(ke=>ke.id===(h==null?void 0:h.id))))==null?void 0:ye.id;Ve&&(h!=null&&h.id)&&u?u(Ve,h.id,ze):l(ze),d(ze),r();return}const oe=Md((ie=v.interactionConfig)==null?void 0:ie.interactions),me=Xqe(Ie,oe),we=((ae=v.interactionConfig)==null?void 0:ae.drillHierarchies)||[],ge=((se=v.interactionConfig)==null?void 0:se.allowedDrillTargets)||[],re=!kT(P,we)||!kT(H,ge)||!kT(me,oe),ne={...v,interactionConfig:{...v.interactionConfig,drillHierarchies:P,allowedDrillTargets:H,interactions:me}},he={...y,cards:y.cards.map(ze=>ze.id===v.id?ne:ze)};if(re){if(!(i!=null&&i.apiServiceUrl)||!(o!=null&&o.accessToken))throw new Error("Missing authentication context for visual update");const ze=await fetch(`${i.apiServiceUrl}/management/v1/visuals/${h.visualId}`,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:`Bearer ${(o==null?void 0:o.accessToken)||""}`},body:JSON.stringify({frameObject:he,expectedLastModified:w})});if(!ze.ok){const Ke=await ze.json().catch(()=>({})),ke=new Error((Ke==null?void 0:Ke.error)||"Failed to update visual");throw ke.status=ze.status,ke}const Ve=await ze.json();a.setQueryData(["resource-by-id","visual",h.visualId],Ve)}const ee=a1(Md(me),C),Ce=ee.filter(ze=>ze.id).map(ze=>ze.id),ve=i9(Qqe(Ie,ee),Ce),te=mT(ee,ve),_e={...m,linkedSourceCardId:m.linkedSourceCardId||v.id,linkedInteractionTargetOverrides:ve,interactionConfig:{...m.interactionConfig,drillHierarchies:P,allowedDrillTargets:H,interactions:te}},De=ze=>{const Ve=new Map;return ze.cards.forEach((Ke,ke)=>{var Pe;const Xe=Ke.linkedSourceCardId||((Pe=y.cards[ke])==null?void 0:Pe.id);Xe&&Ve.set(Xe,Ke.id)}),Ve},Fe=ze=>{const Ve=ze.cards.find(ke=>ke.linkedSourceCardId===v.id);if(Ve)return Ve;const Ke=y.cards.findIndex(ke=>ke.id===v.id);return Ke>=0&&ze.cards[Ke]||null},Ye=[];if((f.sheets||[]).forEach(ze=>{(ze.frames||[]).forEach(Ve=>{if(Ve.visualId!==h.visualId)return;const Ke=Fe(Ve);if(!Ke)return;const ke=De(Ve),Xe=a1(Md(me),ke),Pe=Xe.filter(Ee=>Ee.id).map(Ee=>Ee.id),He=Ve.id===h.id&&Ke.id===m.id?ve:Ke.linkedInteractionTargetOverrides,nt=i9(He,Pe),Me=mT(Xe,nt);Ye.push({sheetId:ze.id,frameId:Ve.id,isCurrentCard:Ve.id===h.id&&Ke.id===m.id,card:{...Ke,linkedSourceCardId:Ke.linkedSourceCardId||v.id,linkedInteractionTargetOverrides:nt,interactionConfig:{...Ke.interactionConfig,drillHierarchies:P,allowedDrillTargets:H,interactions:Me}}})})}),Ye.length>0&&u){Ye.forEach(Ve=>{u(Ve.sheetId,Ve.frameId,Ve.card)});const ze=Ye.find(Ve=>Ve.isCurrentCard);ze||l(_e),d((ze==null?void 0:ze.card)||_e)}else l(_e),d(_e);r()}catch(Ie){Ie.status===409?(tt.error("This saved visual was updated by another editor. Refresh and retry."),Y.current=null,await b.refetch()):tt.error(Ie.message||"Failed to save interactions")}finally{Z(!1)}}},L=()=>{Y.current=null,r()};if(!e||!t||!n||!m||!s)return null;const $={position:"fixed",left:`${s.left}px`,top:`${s.top}px`,width:`${s.width}px`,height:`${s.height}px`};return c.jsxs(p.Popover,{modal:!1,open:e,onOpenChange:pe=>!pe&&r(),children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsx("div",{style:$,className:"pointer-events-none invisible","aria-hidden":"true"})}),c.jsxs(p.PopoverContent,{onEscapeKeyDown:pe=>pe.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:[c.jsx(p.Arrow2,{className:"fill-border",width:12,height:8}),c.jsxs("div",{className:"flex flex-col border-b px-6 py-4",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("h2",{className:"text-lg font-semibold",children:"Configure Interactions"}),U.length>0&&c.jsx(rs,{variant:"default",className:"h-5 min-w-5 rounded-full px-1.5 text-xs",children:U.length})]}),c.jsxs("p",{className:"text-sm text-muted-foreground",children:["Set up drill behaviors for"," ",(m==null?void 0:m.title)||"this chart"]}),g&&c.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Logic is owned by the saved visual. Filter target routing is saved per dashboard instance."})]}),c.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:c.jsx("div",{className:"space-y-6 p-6",children:g&&!v?c.jsx("p",{className:"text-sm text-muted-foreground",children:b.isFetching?"Loading saved visual interaction config...":j?"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."}):c.jsx("div",{children:c.jsx("div",{className:"grid grid-cols-1 gap-4",children:c.jsx(HKe,{interactions:U,metrics:D,attributes:A,availableFields:T,card:{..._||m,interactionConfig:{...(_==null?void 0:_.interactionConfig)||m.interactionConfig,drillHierarchies:P}},onUpdateHierarchies:R,onChange:pe=>W(pe)})})})})}),c.jsxs("div",{className:"flex justify-end gap-2 border-t px-6 py-4",children:[c.jsx(p.Button,{variant:"outline",onClick:L,children:"Cancel"}),c.jsx(p.Button,{onClick:K,disabled:O||g&&!v,children:O?"Saving...":g?"Save to Library":"Accept"})]})]})]})}function xA(e,t){return mo.serializeLayoutsForDirtyCheck(e)!==mo.serializeLayoutsForDirtyCheck(t)}function ZKe(e,t){return t&&xA(e,t)?t:null}function XKe(e){return!!e.expression}function QKe(e){if(e)return e.startsWith("card-source-")?e.replace("card-source-",""):e}function JKe(e){const t=QKe(e);return t?t.startsWith("calc_")||t.startsWith("calc_dim_"):!1}function yie(e){return e.fieldScope==="domain"&&e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===p.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===p.CALCULATED_FIELDS_GROUP_NAME}function eZe(e){return yie(e)}function tZe(e){return e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER||(e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card")&&JKe(e.id)&&!e.entityName}function Lu(e){return XKe(e)?eZe(e)?"domain_calculated":tZe(e)?"user_calculated":"inline_expression":"none"}function Tg(e){return Lu(e)!=="none"}function la(e){if(!Tg(e))return!1;const t=Lu(e);return t==="domain_calculated"||t==="user_calculated"?!0:e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="sheet"||e.fieldScope==="card"}function vie(e){return la(e)&&e.fieldScope!=="card"}function wie(e,t,n){return Tg(e)?t==="editor"?!0:t==="filter"?la(e)&&e.fieldScope!=="card":la(e)&&(n==null?void 0:n.isValuePickSafe)!==!1:!1}function _T(e,t){return e.map(n=>({...n,fieldScope:t}))}function Sie(){const{columns:e,columnGroups:t,isLoading:n,hasError:r,error:s,refetch:o}=G5(),i=p.useEditorStore(_=>_.frame.calculatedFields),a=p.useEditorStore(_=>_.card.calculatedFields),l=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=S.useMemo(()=>e.filter(_=>Lu(_)==="domain_calculated"),[e]),b=S.useMemo(()=>e.filter(_=>Lu(_)!=="domain_calculated"),[e]),x=S.useMemo(()=>{var j;if(m)return i||[];const _=(j=u==null?void 0:u.sheets)==null?void 0:j.find(I=>I.id===f);return p.getSheetCalculatedFields(_)},[u==null?void 0:u.sheets,i,m,h,f]),y=S.useMemo(()=>{const _=d??(u==null?void 0:u.calculatedFields)??[];return _.length?_T(_,"dashboard"):[]},[u==null?void 0:u.calculatedFields,d]),w=S.useMemo(()=>x.length?_T(x,"sheet"):[],[x]),v=S.useMemo(()=>p.buildCalculatedFieldComparableKeySet([...y,...w]),[y,w]),C=S.useMemo(()=>{const _=(a||[]).filter(D=>la(D)&&D.fieldScope!=="domain"),j=((l==null?void 0:l.metricColumns)||[]).filter(D=>la(D)&&D.fieldScope!=="domain"),I=((l==null?void 0:l.groupByColumns)||[]).filter(D=>la(D)&&D.fieldScope!=="domain"),T=p.dedupeCalculatedFields([..._,...j,...I]).filter(D=>!v.has(p.getCalculatedFieldComparableKey(D)));return _T(T,"card").map(D=>({...D,id:`card-source-${D.id}`}))},[a,l==null?void 0:l.groupByColumns,l==null?void 0:l.metricColumns,v]),N=S.useMemo(()=>[...g,...y,...w,...C,...b],[C,b,y,g,w]),k=S.useMemo(()=>t.filter(_=>_.entityId!==p.CALCULATED_FIELDS_GROUP_ID),[t]);return{columns:e,columnGroups:k,rawColumnGroups:t,columnFields:b,domainCalculatedFields:g,dashboardCalculatedFields:y,sheetCalculatedFields:w,cardCalculatedFields:C,scopedFields:N,isLoading:n,hasError:r,error:s,refetch:o}}function nZe(e){const t="expression"in e&&e.expression||"",n=e.qualifiedEntityName||e.entityName||"",r=e.fieldScope||"unscoped",s=e.qualifiedFieldName||e.name;return t?["calculated",r,e.role||"field",n,s,t].join("::"):["calculated",r,e.role||"field",n,p.normalizeCalculatedFieldId(e.id)||s].join("::")}function rZe(e){return["physical",e.fieldScope||"physical",e.role||"field",e.qualifiedEntityName||"",e.qualifiedFieldName||e.name,e.name].join("::")}function lm(e){const t=new Map;return e.forEach(n=>{const r=Tg(n)?nZe(n):rZe(n);t.has(r)||t.set(r,n)}),Array.from(t.values())}function K5(e){return!nr.isCalculatedMetric(e)}function jT(e,t){return lm(e.filter(n=>wie(n,t,{isValuePickSafe:K5(n)})))}function sZe(e){return!Tg(e)||wie(e,"inline-filter",{isValuePickSafe:K5(e)})}function oZe(e){return!Tg(e)||vie(e)}function Cie(){const e=Sie(),t=S.useMemo(()=>lm(e.scopedFields),[e.scopedFields]),n=S.useMemo(()=>lm([...e.columns,...e.dashboardCalculatedFields,...e.sheetCalculatedFields]),[e.columns,e.dashboardCalculatedFields,e.sheetCalculatedFields]),r=S.useMemo(()=>lm(n.filter(oZe)),[n]),s=S.useMemo(()=>jT(t,"editor"),[t]),o=S.useMemo(()=>jT(n.filter(vie),"filter"),[n]),i=S.useMemo(()=>lm(t.filter(K5)),[t]),a=S.useMemo(()=>lm(i.filter(sZe)),[i]),l=S.useMemo(()=>jT(a,"inline-filter"),[a]);return{...e,filterableFields:t,sharedFilterableFields:n,dashboardFilterableFields:r,inlineFilterableFields:a,scopedCalculatedFields:s,sharedCalculatedFields:o,inlineCalculatedFields:l,valuePickFilterableFields:i}}const Nie=Q.forwardRef(function({icon:t,label:n,asButton:r,disabled:s,labelWrapper:o,inQuery:i,trailing:a,kebab:l,showKebab:u,onKebabClick:d,selected:f,dragging:h,disableHover:m,className:g,...b},x){const y=c.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),v=c.jsxs(c.Fragment,{children:[t,o?o(y):y,i&&c.jsx("span",{className:"sr-only",children:"In query"}),a,(l||u)&&c.jsx("button",{type:"button","aria-label":"Field actions",onClick:C=>{C.stopPropagation(),d==null||d(C)},onPointerDown:C=>C.stopPropagation(),className:"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-[3px] text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover/field-row:opacity-100 group-focus-within/field-row:opacity-100 [@media(hover:none)]:opacity-100",children:l??c.jsx(da,{className:"h-3 w-3"})})]});return r?c.jsx("button",{ref:x,type:"button",disabled:s,"data-selected":f?"true":void 0,className:w,...b,children:v}):c.jsx("div",{ref:x,"data-selected":f?"true":void 0,className:w,...b,children:v})});function Z5(e){const{tokenProps:t,authToken:n}=mt(),r=t==null?void 0:t.apiServiceUrl;return jn({queryKey:["joinability-map",e],queryFn:async()=>{if(!e||!(n!=null&&n.accessToken))return null;const s=`${r}/v1/domains/${e}/joinability`;return p.getRequest(s,n.accessToken)},enabled:!!e&&!!(n!=null&&n.accessToken)&&!!r,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:s=>Math.min(1e3*2**s,3e4)})}function kie(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 _ie(e,t,n,r,s){if(e!=="kpi"||s.length<3)return;const o=(t==null?void 0:t.groupByColumns)&&t.groupByColumns.length>0,i=s.some(a=>a.comparisonType&&a.comparisonType!=="none");!o&&!i||n(r,{groupByColumns:[],metricColumns:s.map(a=>({...a,comparisonType:"none",targetValue:void 0}))})}function iZe(e,t){return(e||[]).map(n=>({...n,id:t(n),label:n.label!==void 0?n.label:n.name}))}const aZe=new Set(["COUNT","DISTINCT"]),lZe=new Set(["running_total","moving_average","previous_period_delta"]);function cZe(e){return p.getDataType(e.dataType||"")==="number"?!0:e.aggregate?aZe.has(e.aggregate.toUpperCase()):!1}function uZe(e,t){var r,s;return!!((s=(r=e.parameters)==null?void 0:r.windowTransform)==null?void 0:s.function)}function X5(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 jie({cardType:e,cardConfig:t,metric:n,transformMode:r}){var i,a,l;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(!cZe(n))return{supported:!1,reason:"Metric transforms are only available for numeric metrics."};const s=(((a=t.pivotByColumns)==null?void 0:a.length)??0)>0,o=e==="pivotTable"||X5(e,t);return s&&!o?{supported:!1,reason:"Metric transforms with pivot dimensions are only supported for pivotTable and subtotal-enabled aggregateTable in V1."}:lZe.has(r)&&(((l=t.groupByColumns)==null?void 0:l.length)??0)===0?{supported:!1,reason:"This transform requires grouped dimensions for ordering."}:{supported:!0}}function dZe(e){return e.find(t=>p.getDataType(t.dataType||"")==="date")}function fZe(e){return e}function Rx({cardType:e,cardConfig:t,orderByFieldId:n}){const r=(t.groupByColumns||[]).filter(o=>o.id&&o.id!==n).map(o=>o.id),s=[];if(e==="pivotTable"||X5(e,t))for(const o of t.pivotByColumns||[])o.id&&s.push(o.id);return Array.from(new Set([...r,...s]))}function hZe({transformMode:e,cardType:t,cardConfig:n,fallbackOrderByFieldId:r}){var i;const s=r||((i=dZe(n.groupByColumns||[]))==null?void 0:i.id),o=Rx({cardType:t,cardConfig:n,orderByFieldId:s});return e==="moving_average"?{function:"moving_average",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,movingAverage:{windowSize:7,minPeriods:1}}:e==="previous_period_delta"?{function:"previous_period_delta",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,previousPeriodDelta:{mode:"absolute"}}:e==="percent_of_total"?{function:"percent_of_total",percentOfTotal:{scope:"grand_total",output:"percent"},partitionByFieldIds:[]}:{function:"running_total",...s?{orderBy:{fieldId:s,direction:"asc"}}:{},partitionByFieldIds:o,frame:"unbounded_preceding"}}const mZe=new Set(["table","aggregateTable","pivotTable","detailTable"]);function pZe(e){return e.alias||e.label||e.name}function Eie(e,t,n){var a,l,u;if(!e)return null;const r=p.fromSemanticFormat(t.format);if(!r)return null;const s=n||{};let o=s,i=!1;if(mZe.has(e.type)){const d=p.toColumnNumberFormat(r),f=pZe(t);if(d&&!((l=(a=s.tablePrefs)==null?void 0:a.columnSettingsMap)==null?void 0:l[f])){const m=Vs();o={...o,tablePrefs:{...o.tablePrefs||{},columnSettingsMap:{...((u=o.tablePrefs)==null?void 0:u.columnSettingsMap)||{},[f]:{...m,type:"number",textAlign:"right",numberFormat:{...m.numberFormat,...d}}}}},i=!0}if(!s.formatNumber){const h=p.toLegacyFormatNumber(r);h&&(o={...o,formatNumber:{decimalPlaces:h.decimalPlaces,minimumFractionDigits:h.minimumFractionDigits,maximumFractionDigits:h.maximumFractionDigits,currency:h.currency,locale:h.locale,prefix:h.prefix,suffix:h.suffix,useGrouping:h.useGrouping,percentValueMode:h.percentValueMode,enabled:!0}},i=!0)}}return i?o:null}const Iie=e=>{var L;const t=(L=e==null?void 0:e.dataSource)==null?void 0:L.semanticDomainId,{data:n}=Z5(t),{updateCardConfig:r,updateGroupByColumn:s,updateMetricColumn:o,updatePivotByColumn:i,updateSortByColumn:a,removeGroupByColumn:l,removeMetricColumn:u,removePivotByColumn:d,removeSortByColumn:f,setCardPreferences:h}=p.useEditorActions(),m=p.useEditorStore($=>$.card.type),g=e==null?void 0:e.id,b=($,B)=>{if($.id)return $.id;const V=$.qualifiedEntityName||$.entityName||B;return`${B}-${V}-${$.name}`},x=S.useCallback($=>{if(!(e!=null&&e.config))return[];switch($){case"groupBy":return(e.config.groupByColumns||[]).map(B=>({...B,id:b(B,"groupBy"),label:B.label!==void 0?B.label:B.name}));case"metrics":return(e.config.metricColumns||[]).map(B=>({...B,id:b(B,"metrics"),label:B.label!==void 0?B.label:B.name}));case"pivotBy":return(e.config.pivotByColumns||[]).map(B=>({id:b(B,"pivotBy"),name:B.name,dataType:B.dataType,label:B.label!==void 0?B.label:B.name,qualifiedEntityName:B.qualifiedEntityName,entityId:B.entityId,entityName:B.entityName,entityType:B.entityType}));case"sortBy":return(e.config.sortByColumns||[]).map(B=>({id:b(B,"sortBy"),name:B.name,dataType:B.dataType,label:B.label!==void 0?B.label:B.name,qualifiedEntityName:B.qualifiedEntityName,entityId:B.entityId,entityName:B.entityName,entityType:B.entityType,direction:B.direction}));case"detailColumns":return iZe(e.config.detailColumns,B=>b(B,"detailColumns"));case"source":return[];default:return[]}},[e]),y=S.useCallback(($,B)=>{if(g)switch($){case"groupBy":{r(g,{groupByColumns:B});break}case"metrics":{r(g,{metricColumns:B});break}case"pivotBy":{r(g,{pivotByColumns:B});break}case"sortBy":{r(g,{sortByColumns:B});break}case"detailColumns":{r(g,{detailColumns:B});break}}},[g,r]),w=S.useCallback(($,B,V)=>{if(!g)return;const F=x($),q=F[B];if(q)switch($){case"groupBy":s(g,q.id,{label:V});break;case"metrics":o(g,q.id,{label:V});break;case"pivotBy":i(g,q.id,{label:V});break;case"sortBy":a(g,q.id,{label:V});break;case"detailColumns":{const G=F.map((X,J)=>J===B?{...X,label:V}:X);r(g,{detailColumns:G});break}}},[g,x,s,o,i,a,r]),v=S.useCallback(($,B)=>{if(!g)return;const F=x("metrics")[$];F&&o(g,F.id,{aggregate:B,label:zQ(F.name,B)})},[g,x,o]),C=S.useCallback(($,B,V,F="groupBy")=>{if(!g)return;const q=x(F),G=q[$];if(!G)return;const X={dateFormat:B,customFormat:B==="custom"&&V?V:void 0};if(F==="detailColumns"){const J=q.map((fe,ue)=>ue===$?{...fe,...X}:fe);r(g,{detailColumns:J});return}s(g,G.id,X)},[g,x,r,s]),N=S.useCallback(($,B)=>{if(!g)return;const F=x("groupBy")[$];F&&s(g,F.id,{granularity:B})},[g,x,s]),k=S.useCallback(($,B)=>{if(!g)return;const F=x("metrics")[$];F&&o(g,F.id,{aliasTemplate:B})},[g,x,o]),_=S.useCallback(($,B)=>{if(console.log("handleValueAliasesChange",$,B),!g)return;console.log("handleValueAliasesChange",$,B);const F=x("metrics")[$];F&&(console.log("handleValueAliasesChange",B),o(g,F.id,{valueAliases:B}))},[g,x,o]),j=S.useCallback(($,B)=>{var q,G;if(!g)return;const F=x("metrics")[$];F&&(o(g,F.id,{format:B}),m==="kpi"&&((G=(q=e==null?void 0:e.preferences)==null?void 0:q.kpiVisualOptions)!=null&&G.formatOptions)&&h({...e.preferences,kpiVisualOptions:{...e.preferences.kpiVisualOptions,formatOptions:void 0}}))},[e,g,m,x,h,o]),I=S.useCallback(($,B)=>{var G;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=B!=="none"&&((G=F.parameters)==null?void 0:G.windowTransform);o(g,F.id,{comparisonType:B,...B!=="target"?{targetValue:void 0}:{},...q?{parameters:{...F.parameters||{},windowTransform:void 0}}:{}})},[g,x,o]),E=S.useCallback(($,B)=>{var ue,pe,ye;if(!g||!(e!=null&&e.config))return;const F=x("metrics")[$];if(!F)return;if(B==="none"){o(g,F.id,{parameters:{...F.parameters||{},windowTransform:void 0}});return}const q=jie({cardType:m,cardConfig:e.config,metric:F,transformMode:B});if(!q.supported){tt.error(q.reason||"Metric transform is not supported here.");return}const G=new Set((e.config.groupByColumns||[]).map(ie=>ie.id)),X=(ye=(pe=(ue=F.parameters)==null?void 0:ue.windowTransform)==null?void 0:pe.orderBy)==null?void 0:ye.fieldId,J=X&&G.has(X)?X:void 0,fe=hZe({transformMode:B,cardType:m,cardConfig:e.config,fallbackOrderByFieldId:J});o(g,F.id,{comparisonType:"none",targetValue:void 0,parameters:{...F.parameters||{},windowTransform:fe}})},[e,g,m,x,o]),T=S.useCallback(($,B)=>{var fe,ue;if(!g||!(e!=null&&e.config))return;const F=x("metrics")[$];if(!F)return;const q=(fe=F.parameters)==null?void 0:fe.windowTransform;if(!q||!["running_total","moving_average","previous_period_delta"].includes(q.function))return;const G=Rx({cardType:m,cardConfig:e.config,orderByFieldId:B}),J=(q.partitionByFieldIds||G).filter(pe=>pe!==B);o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,orderBy:{fieldId:B,direction:((ue=q.orderBy)==null?void 0:ue.direction)||"asc"},partitionByFieldIds:J}}})},[e,g,m,x,o]),D=S.useCallback(($,B)=>{var G;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(G=F.parameters)==null?void 0:G.windowTransform;!q||!["running_total","moving_average","previous_period_delta"].includes(q.function)||o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,orderBy:q.orderBy?{...q.orderBy,direction:B}:q.orderBy}}})},[g,x,o]),A=S.useCallback(($,B)=>{var J,fe;if(!g||!(e!=null&&e.config))return;const F=x("metrics")[$];if(!F)return;const q=(J=F.parameters)==null?void 0:J.windowTransform;if(!q)return;const G=Rx({cardType:m,cardConfig:e.config,orderByFieldId:(fe=q.orderBy)==null?void 0:fe.fieldId}),X=new Set(q.partitionByFieldIds||G);X.has(B)?X.delete(B):X.add(B),o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,partitionByFieldIds:Array.from(X)}}})},[e,g,m,x,o]),P=S.useCallback(($,B)=>{var fe,ue;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(fe=F.parameters)==null?void 0:fe.windowTransform;if(!q||q.function!=="moving_average")return;const G=Math.max(1,Math.floor(B||1)),X=((ue=q.movingAverage)==null?void 0:ue.minPeriods)||1,J=Math.min(X,G);o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,movingAverage:{windowSize:G,minPeriods:J}}}})},[g,x,o]),R=S.useCallback(($,B)=>{var J,fe;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(J=F.parameters)==null?void 0:J.windowTransform;if(!q||q.function!=="moving_average")return;const G=((fe=q.movingAverage)==null?void 0:fe.windowSize)||7,X=Math.max(1,Math.min(Math.floor(B||1),G));o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,movingAverage:{windowSize:G,minPeriods:X}}}})},[g,x,o]),H=S.useCallback(($,B)=>{var G;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(G=F.parameters)==null?void 0:G.windowTransform;!q||q.function!=="previous_period_delta"||o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,previousPeriodDelta:{mode:B}}}})},[g,x,o]),z=S.useCallback(($,B)=>{var X;if(!g||!(e!=null&&e.config))return;const F=x("metrics")[$];if(!F)return;const q=(X=F.parameters)==null?void 0:X.windowTransform;if(!q||q.function!=="percent_of_total")return;const G=B==="grand_total"?[]:(q.partitionByFieldIds||[]).length>0?q.partitionByFieldIds||[]:Rx({cardType:m,cardConfig:e.config,orderByFieldId:void 0});o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,partitionByFieldIds:G,percentOfTotal:{...q.percentOfTotal||{},scope:B}}}})},[e,g,m,x,o]),U=S.useCallback(($,B)=>{var G;if(!g)return;const F=x("metrics")[$];if(!F)return;const q=(G=F.parameters)==null?void 0:G.windowTransform;!q||q.function!=="percent_of_total"||o(g,F.id,{parameters:{...F.parameters||{},windowTransform:{...q,percentOfTotal:{...q.percentOfTotal||{},output:B}}}})},[g,x,o]),W=S.useCallback($=>{g&&r(g,{showTrendline:$})},[g,r]),O=S.useCallback($=>{g&&r(g,{trendlineWindow:$})},[g,r]),Z=S.useCallback($=>{g&&r(g,{trendlineGranularity:$})},[g,r]),Y=S.useCallback(($,B)=>{if(!g)return;const F=x("metrics")[$];F&&o(g,F.id,{targetValue:B})},[g,x,o]),M=S.useCallback(async $=>{var fe;if(!g)return;const B=[...x("groupBy"),...x("pivotBy"),...x("metrics"),...x("sortBy"),...x("detailColumns")],V=$,F=YMe(V,B,{joinPlan:(fe=e==null?void 0:e.config)==null?void 0:fe.joinPlan,joinabilityMap:n==null?void 0:n.joinabilityMap,semanticDomainId:t,datasetAliases:n==null?void 0:n.datasets});if(!F.isValid){F.showError&&FQ();return}const q=sAe(V,B,m);if(!q){tt.error("Invalid Field",{description:"This field cannot be added to any container",position:"top-center",duration:3e3});return}const G=kie(V,q,m);if(!G.isValid){tt.error("Invalid Field Type",{description:G.reason,position:"top-center",duration:3e3});return}const X=x(q);if(PQ(V,X))return;const J=BQ(V,q,X);if(J){const ue=[...X,J];if(y(q,ue),q==="metrics"){const pe=Eie(e,J,e==null?void 0:e.preferences);pe&&h(pe),_ie(m,e==null?void 0:e.config,r,g,ue)}}},[g,e,x,y,t,n,m,r,h]),K=S.useCallback(($,B)=>{if(!g)return;const F=x($)[B];if(F){if($!=="sortBy"){const q=x("sortBy"),G=q.filter(X=>!(X.name===F.name&&X.qualifiedEntityName===F.qualifiedEntityName));G.length!==q.length&&r(g,{sortByColumns:G})}switch($){case"groupBy":l(g,F.id);break;case"metrics":u(g,F.id);break;case"pivotBy":d(g,F.id);break;case"sortBy":f(g,F.id);break;case"detailColumns":{r(g,{detailColumns:(x("detailColumns")||[]).filter((q,G)=>G!==B)});break}}}},[g,x,l,u,d,f,r]);return{getFieldsForContainer:x,setFieldsForContainer:y,updateLabel:w,handleAggregationChange:v,handleDateFormatChange:C,handleGranularityChange:N,handleAliasTemplateChange:k,handleValueAliasesChange:_,handleMetricFormatChange:j,removeField:K,handleFieldClick:M,handleMetricComparisonChange:I,handleMetricWindowTransformChange:E,handleMetricWindowOrderByChange:T,handleMetricWindowDirectionChange:D,handleMetricWindowPartitionToggle:A,handleMetricMovingAverageWindowSizeChange:P,handleMetricMovingAverageMinPeriodsChange:R,handleMetricPreviousPeriodDeltaModeChange:H,handleMetricPercentOfTotalScopeChange:z,handleMetricPercentOfTotalOutputChange:U,handleKpiShowTrendlineChange:W,handleKpiTrendlineWindowChange:O,handleKpiTrendlineGranularityChange:Z,handleMetricTargetValueChange:Y,cardType:m}};function Tie(e){var y;const{tokenProps:t}=mt(),n=p.useDashboardStore(w=>w.authToken)||e,r=p.useEditorStore(w=>w.selectedConnectionId),s=p.useEditorStore(w=>w.selectedDatabaseName),o=p.useEditorStore(w=>w.selectedDatamodelId),i=p.useEditorStore(w=>w.selectedSchemaName),a=p.useEditorStore(w=>w.selectedTableName),{selectedConnection:l}=Cc(),u=l==null?void 0:l.type,{data:d,isLoading:f,isFetching:h,isError:m,refetch:g}=jn({queryKey:["columns",r,s,o,i,a],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",{connection_id:r,datamodel_id:o||"",database_name:s,schema_name:i,table_name:a}),enabled:b(u)});function b(w){var _;if(!(n!=null&&n.accessToken))return!1;if(o&&o)return!0;if(!r||!w)return!1;const v=((_=l==null?void 0:l.capabilities)==null?void 0:_.path)||[],C=v.includes("database"),N=v.includes("schema"),k=v.includes("table");return!(C&&(!s||s==="NA")||N&&!i||k&&!a)}return{columns:(y=d==null?void 0:d.columns)==null?void 0:y.map(w=>({...w,data_type:w.data_type.toLowerCase()})),isColumnsLoading:f,isColumnsFetching:h,isColumnsError:m,refetchColumns:g}}function gZe(e){const t=p.useDashboardStore(g=>g.selectedLensId),n=p.useDashboardStore(g=>g.dashboard.filters),r=p.useFinalFilterGroupKey(e)||"",{cardFilterValues:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:l,queryRelevantConfig:u}=RP(e),d=fk([e],{authority:"editor",queryRelevantConfigsByCardId:{[e.id]:u}}).payload,f=j0({card:e,cardConfig:u,semanticExecutionPayload:d}),h=(e==null?void 0:e.sql)||"",{queryKey:m}=wF(e,{finalFiltersKey:r,selectedLensId:t,cardFilterValues:s,controlValues:o,controlDefinitions:i,cardControlDefinitions:a,controlBindings:l,queryRelevantConfig:u,filters:n,resolvedPrimaryDateField:f});return{queryKey:m,sql:h,cardFilterValues:s,controlValues:o}}function q_(e,t){var te,_e,De,Fe,Ye,ze,Ve,Ke;const{tokenProps:n}=mt(),r=qr(),s=mt().authToken||e,o=p.useEditorStore(ke=>ke.selectedConnectionId),i=p.useEditorStore(ke=>ke.card),{queryKey:a}=gZe(i),l=p.useEditorStore(ke=>ke.selectedDatamodelId),u=p.useEditorStore(ke=>ke.isDevMode),d=p.useEditorStore(ke=>ke.selectedDatabaseName),f=p.useEditorStore(ke=>ke.selectedSchemaName),h=p.useEditorStore(ke=>ke.selectedTableName),m=p.useEditorStore(ke=>ke.actions.setSelectedConnectionId),g=p.useEditorStore(ke=>ke.actions.setSelectedDatamodelId),b=p.useEditorStore(ke=>ke.actions.setSelectedDatabaseName),x=p.useEditorStore(ke=>ke.actions.setSelectedSchemaName),y=p.useEditorStore(ke=>ke.actions.setSelectedTableName);p.useEditorStore(ke=>ke.actions.setCardSql);const{setQueryConfig:w}=p.useEditorActions();function v(ke){var Me;if(!o||!ke)return!1;const Xe=((Me=I==null?void 0:I.capabilities)==null?void 0:Me.path)||[],Pe=Xe.includes("database"),He=Xe.includes("schema");return!(!Xe.includes("table")||Pe&&(!d||d==="NA")||He&&!f)}function C(ke){var Xe;return!o||!ke?!1:!!((Xe=I==null?void 0:I.capabilities)!=null&&Xe.path.includes("database"))}const{refetchConnections:N,connectionsData:k,isConnectionsLoading:_,isConnectionsError:j,selectedConnection:I}=Cc(e),{refetch:E,data:T,isLoading:D,isError:A}=jn({queryKey:["models",o],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/datamodels`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:!!(s!=null&&s.accessToken)&&!!o}),P=I==null?void 0:I.type,R=((te=I==null?void 0:I.capabilities)==null?void 0:te.path.includes("schema"))??!1,H=((_e=I==null?void 0:I.capabilities)==null?void 0:_e.path.length)===1&&((De=I==null?void 0:I.capabilities)==null?void 0:De.path[0])==="table",z=H,{data:U,isLoading:W,isFetching:O,isError:Z,refetch:Y}=jn({queryKey:["databases",o],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/databases`,(s==null?void 0:s.accessToken)||"",{connection_id:o}),enabled:C(P)}),{data:M,isLoading:K,isFetching:L,isError:$,refetch:B}=jn({queryKey:["schemas",o,d],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/schemas`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d}),enabled:!!o&&!!d&&R&&d!=="NA"}),{data:V,isLoading:F,isFetching:q,isError:G,refetch:X}=jn({queryKey:["tables",o,d,f],queryFn:()=>p.getRequest(`${n.apiServiceUrl}/v1/tables`,(s==null?void 0:s.accessToken)||"",{connection_id:o,database_name:d,schema_name:f}),enabled:v(P)}),{columns:J,isColumnsLoading:fe,isColumnsFetching:ue,isColumnsError:pe,refetchColumns:ye}=Tie(e);S.useEffect(()=>{H&&(b(""),x(""),g(""),P==="API"&&y("api"))},[P,y,b,x,g,H]);const ie=(I==null?void 0:I.type)==="API"?(Fe=I==null?void 0:I.type)==null?void 0:Fe.toLowerCase():h||"",ae=R&&f||"";function se(ke){y(ke),w(void 0),u||(r.setQueryData(a,null),r.removeQueries({queryKey:a,exact:!0}))}function Ie(ke){x(ke),y("")}function oe(ke){b(ke==="none"?"":ke),x(""),y(""),ke!=="none"&&ke!==""&&g("")}function me(ke){m(ke)}function we(ke){g(ke==="none"?"":ke),ke!=="none"&&ke!==""&&b("")}U&&((Ye=U==null?void 0:U.databases)==null?void 0:Ye.length)>0,M&&((ze=M==null?void 0:M.schemas)==null?void 0:ze.length)>0;const ge=k==null?void 0:k.connections.map(ke=>({id:ke.id,name:ke.name,type:ke.type})),re=(Ve=T==null?void 0:T.datamodels)==null?void 0:Ve.map(ke=>({id:ke.id,name:ke.name})),ne=U==null?void 0:U.databases.map(ke=>({id:ke.database_name,name:ke.database_name})),he=M==null?void 0:M.schemas.map(ke=>({id:ke.schema_name,name:ke.schema_name})),ee=V==null?void 0:V.tables.map(ke=>({id:ke.table_name,name:ke.table_name})),Ce=(Ke=T==null?void 0:T.datamodels.find(ke=>ke.id===l))==null?void 0:Ke.name,ve=I!=null&&I.capabilities?p.getFormattedTableNameForQuery({schemaName:ae,tableName:ie,modelName:Ce,databaseName:d||"",capabilities:I.capabilities}):ie;return{connectionItems:ge,selectedConnectionId:o,selectedConnection:I,isConnectionsLoading:_,isConnectionsError:j,modelItems:re,selectedDatamodelId:l,selectedDatamodelName:Ce,isModelsLoading:D,isModelsError:A,selectedDatabaseName:d,databaseItems:ne,isDatabasesLoadingOrFetching:W||O,isDatabaseError:Z,schemaItems:he,selectedSchemaName:f,isSchemaLoadingOrFetching:K||L,isSchemaError:$,tableItems:ee,selectedTableName:h,isTableLoadingOrFetching:F||q,isTableError:G,columns:J,isColumnsLoadingOrFetching:fe||ue,isColumnsError:pe,isNonDbConnection:z,connectionType:P,tableName:ie,formattedTableName:ve,schemaName:ae,refetchConnections:N,refetchModels:E,refetchDatabases:Y,refetchSchemas:B,refetchTables:X,refetchColumns:ye,handleConnectionChange:me,handleDatamodelChange:we,handleDatabaseChange:oe,handleSchemaChange:Ie,handleTableChange:se}}function uS(e){return`${e}-${p.v4()}`}function M9(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 bZe(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 Q5(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 Die(e){if(!e||!e.selectedEntities||e.selectedEntities.length===0)return!1;const t=e.selectedEntities[0];return!!(t!=null&&t.name)}function Mie(){const e=p.useEditorStore(_=>_.sqlGen),t=p.useEditorStore(_=>_.isDevMode),n=p.useEditorStore(_=>_.card.dataSource),r=p.useEditorStore(_=>{var j,I;return(I=(j=_.card)==null?void 0:j.queryConfig)==null?void 0:I.metricColumns}),{tableName:s,schemaName:o,databaseName:i}=Q5(n),a=Die(n),l=p.useEditorStore(_=>_.selectedDatamodelId),{addColumnToMetricColumns:u,addColumnToGroupBy:d,setCardSql:f,setRunSql:h,setSqlGen:m,setIsShowingVisual:g}=p.useEditorActions(),{modelItems:b,selectedDatamodelName:x}=q_(),{selectedConnection:y}=Cc(),w=y==null?void 0:y.capabilities,v=_=>({column_name:_.name,data_type:_.dataType,label:_.label,description:_.description});return{handleDevModeFieldClick:_=>{var I;if(!t)return;const j=v(_);if(t&&a&&s&&w){const E=p.createSqlGenConfig(j,e);m(E);const T=(I=b==null?void 0:b.find(A=>A.id===l))==null?void 0:I.name,D=p.getSql(E,o||"",s,T||"",i||"",w,_.qualifiedEntityName);D&&(f(D),h(!0))}else if(!t){if(p.isTextDataType(j.data_type))if(r&&r.length>0){const E={...j,role:"groupby",id:uS(j.column_name),name:j.column_name,type:j.data_type};d(E)}else{const E={...j,role:"metric",id:uS(j.column_name),name:j.column_name,label:M9(j.column_name,"COUNT"),type:j.data_type,aggregate:"COUNT"};u(E)}if(p.isDateDataType(j.data_type)){const E={...j,role:"groupby",id:uS(j.column_name),name:j.column_name,type:j.data_type,label:bZe(j.column_name,"month"),granularity:"month"};d(E)}if(p.isNumberDataType(j.data_type)){const E={...j,role:"metric",id:uS(j.column_name),name:j.column_name,label:M9(j.column_name,"SUM"),type:j.data_type,aggregate:"SUM"};u(E)}}},handleShowSample:()=>{if(!a||!s||!w){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=p.getFormattedTableNameForQuery({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:w});g(!1);const I=(y==null?void 0:y.type)==="MSSQL"?`SELECT top 10 * FROM ${_}`:`SELECT * FROM ${_} LIMIT 10`;f(I),h(!0)},handleShowCount:()=>{if(!a||!s||!w){console.warn("Cannot generate SQL: missing table metadata or capabilities");return}const _=p.getFormattedTableNameForQuery({schemaName:o||"",tableName:s,modelName:x,databaseName:i||"",capabilities:w});f(`SELECT COUNT(*) as count FROM ${_}`),h(!0)},isNumberField:_=>p.isNumberDataType(_.dataType)}}function Aie(e){const t=e.qualifiedFieldName,r=(e.qualifiedEntityName||e.qualifiedFieldName.split(".").slice(0,-1).join(".")).split(".").map(o=>p.fmt(o)).join("."),s=p.fmt(e.name);return{qualifiedColumnName:t,qualifiedTableName:r,formattedColumnName:s}}function J5(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 eL(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 Ly(e){var t,n;return e?!!(e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER||e.expression||(n=(t=e.calculatedFormula)==null?void 0:t.inputFields)!=null&&n.length):!1}function A9(e){return e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e}function Ip(e,t){var b,x,y,w,v,C,N;if(!e.fieldMeta)return e.column===t.qualifiedFieldName||e.column===t.name;const n=A9((b=e.fieldMeta)==null?void 0:b.id),r=A9(t.id),s=((x=e.fieldMeta)==null?void 0:x.qualifiedFieldName)||e.column,o=s===t.qualifiedFieldName||s===t.name,i=(y=e.fieldMeta)==null?void 0:y.qualifiedEntityName,a=!i||!t.qualifiedEntityName||i===t.qualifiedEntityName,l=(w=e.fieldMeta)==null?void 0:w.entityId,u=!l||!t.entityId||l===t.entityId,d=(v=e.fieldMeta)==null?void 0:v.fieldScope;if(d&&t.fieldScope&&d!==t.fieldScope)return!1;const f=(C=e.fieldMeta)==null?void 0:C.role;if(f&&t.role&&f!==t.role)return!1;const h=Ly(e.fieldMeta)||Ly(t);if(h&&n&&r&&n===r)return!0;if(!h&&(!a||!u))return!1;const m=(N=e.fieldMeta)==null?void 0:N.expression,g=t.expression;return m||g?o&&a&&u&&m===g:o&&a&&u}function xZe(){const e=p.useDashboardStore(l=>l.dashboard.filters)||[],t=p.useDashboardStore(l=>l.selectedSheetId),n=p.useDashboardStore(l=>l.actions.addFilter),r=p.useDashboardStore(l=>l.actions.removeFilter),{removeFilterValues:s}=p.useDashboardActions(),o=p.useEditorStore(l=>l.card.dataSource),{selectedConnection:i}=Cc();function a(l,u="sheet"){var g;const{qualifiedColumnName:d,qualifiedTableName:f,formattedColumnName:h}=Aie(l);let m;if(u==="sheet"&&t){const b=Qu(e,t);m=b.find(x=>x.fieldMeta&&Ip(x,l))||T1e(b.filter(x=>!x.fieldMeta),d,f,t)}else m=e==null?void 0:e.find(b=>Ip(b,l)||!b.fieldMeta&&ap(b.column)===ap(d));if(m)s(m.id),r(m.id);else{const b=p.v4(),x=J5(l),y=eL(o,{connectionId:i==null?void 0:i.id,connectionType:i==null?void 0:i.type}),w=Ly(x),v=!!((o==null?void 0:o.mode)==="semanticDomain"&&((g=y==null?void 0:y.selectedEntities)!=null&&g.length||y!=null&&y.semanticDomainId)),C=u==="sheet"&&t?[t]:void 0,N=p.getDataType(l.dataType)==="date"?"between":"in";return n({id:b,location:u,column:d,title:l.label||l.name,dataType:l.dataType,qualifiedTableName:f,connectionId:(i==null?void 0:i.id)||"",operation:N,applyToSheetIds:C,sql:w||v?"":QO(l.dataType,f,h),fieldMeta:x,semanticContext:y}),b}}return{assignFilter:a}}function yZe({column:e}){const[t,n]=S.useState(!1),r=p.useEditorStore(v=>v.isDevMode),s=p.useEditorStore(v=>v.card.dataSource),{tableName:o,schemaName:i,databaseName:a}=Q5(s),l=p.useEditorStore(v=>v.selectedDatamodelId),u=p.useEditorStore(v=>v.sqlGen),{modelItems:d,selectedConnection:f}=q_(),h=f==null?void 0:f.capabilities,m=p.useEditorStore(v=>v.actions.setSqlGen),g=p.useEditorStore(v=>v.actions.setCardSql),b=p.useEditorStore(v=>v.actions.setRunSql),x=Die(s);function y(v,C){var I,E;if(!x||!o){console.warn("Cannot generate SQL: missing table metadata");return}const N=p.createSqlGenConfig(v,u,C),k=(I=d==null?void 0:d.find(T=>T.id===l))==null?void 0:I.name;if(m(N),!h){console.warn("Cannot generate SQL: missing connection capabilities");return}const _=(E=v.qualifiedFieldName)==null?void 0:E.split(".").slice(0,-1).join("."),j=p.getSql(N,i||"",o,k||"",a||"",h,_);j&&(g(j),b(!0)),n(!1)}function w(){return c.jsxs("ul",{className:"text-xs",children:[c.jsx("li",{onClick:()=>y(e,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),c.jsx("li",{onClick:()=>y(e,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),c.jsx("li",{onClick:()=>y(e,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),c.jsx("li",{onClick:()=>y(e,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),c.jsx("li",{onClick:()=>y(e,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return!r||!x?null:c.jsxs(eg,{openDelay:0,open:t,onOpenChange:n,children:[c.jsx(tg,{asChild:!0,children:c.jsx(ch,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover/container:visible"})}),c.jsx(Iu,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:w()})]})}const R9="bg-emerald-500/90 text-white",vZe="bg-blue-500/90 text-white";function tL(e){const t=Lu(e);return t==="none"?null:t==="inline_expression"?{label:"{}",badgeClassName:R9}:{label:"fx",badgeClassName:e.role==="metric"?R9:vZe}}function wZe(e){if(!e)return[];const t=[{label:"Type",value:e.type}];if("locale"in e&&e.locale&&t.push({label:"Locale",value:e.locale}),e.prefix&&t.push({label:"Prefix",value:e.prefix}),e.suffix&&t.push({label:"Suffix",value:e.suffix}),e.type==="date")return e.pattern&&t.push({label:"Pattern",value:e.pattern}),e.timezone&&t.push({label:"Timezone",value:e.timezone}),e.sourceTimezone&&t.push({label:"Source TZ",value:e.sourceTimezone}),e.relative!==void 0&&t.push({label:"Relative",value:e.relative?"On":"Off"}),t;if("minimumFractionDigits"in e||"maximumFractionDigits"in e){const n=e.minimumFractionDigits,r=e.maximumFractionDigits;if(n!==void 0||r!==void 0){const s=n!==void 0&&r!==void 0?n===r?`${n}`:`${n}-${r}`:`${n??"auto"}-${r??"auto"}`;t.push({label:"Decimals",value:s})}}return"useGrouping"in e&&e.useGrouping!==void 0&&t.push({label:"Grouping",value:e.useGrouping?"On":"Off"}),"currency"in e&&e.currency&&t.push({label:"Currency",value:e.currency}),"percentValueMode"in e&&e.percentValueMode&&t.push({label:"Percent Input",value:e.percentValueMode}),"negativeStyle"in e&&e.negativeStyle&&t.push({label:"Negative Style",value:e.negativeStyle}),"compact"in e&&e.compact!==void 0&&t.push({label:"Compact",value:e.compact?"On":"Off"}),"scale"in e&&e.scale!==void 0&&t.push({label:"Scale",value:String(e.scale)}),t}function SZe(e){var n;if(!e.expression)return null;const t=((n=e.calculatedFormula)==null?void 0:n.inputFields)||[];return t.length?e.expression.replace(/\{field_(\d+)\}/g,(r,s)=>{const o=t[Number(s)];return o?`{${o.name||o.label}}`:r}):e.expression}function CZe({field:e,fieldState:t}){const n=SZe(e),r=wZe(e.format),s=!!tL(e);return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-start gap-1.5 px-3 pt-2.5",children:[c.jsx("span",{className:"flex h-[18px] shrink-0 items-center",children:c.jsx(fv,{dataType:e.dataType,calculated:s})}),c.jsx("p",{className:"min-w-0 flex-1 break-words text-[13px] font-semibold leading-[18px] text-foreground",children:e.label||e.name})]}),c.jsx("div",{className:"px-3 pb-2 pt-0.5",children:c.jsx("code",{className:"font-mono text-[11px] text-muted-foreground",children:e.dataType})}),e.description&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[12px] leading-[1.55] text-muted-foreground",children:e.description}),n&&c.jsxs("div",{className:"border-t border-border/60 bg-muted/40 px-3 py-2",children:[c.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Expression"}),c.jsx("code",{className:"block whitespace-pre-wrap break-all font-mono text-[11px] leading-[1.55] text-foreground/90",children:n})]}),r.length>0&&c.jsxs("div",{className:"border-t border-border/60 px-3 py-2",children:[c.jsx("p",{className:"mb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Format"}),c.jsx("dl",{className:"grid grid-cols-[64px_1fr] gap-x-3 gap-y-1 text-[11px]",children:r.map(o=>c.jsxs("div",{className:"contents",children:[c.jsx("dt",{className:"font-medium uppercase tracking-[0.08em] text-muted-foreground",children:o.label}),c.jsx("dd",{className:"truncate font-mono tabular-nums text-foreground/90",children:o.value})]},`${o.label}-${o.value}`))})]}),t&&t.tooltip&&c.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-[11px] text-muted-foreground",children:t.tooltip}),c.jsx("div",{className:"border-t border-border/60 px-3 py-2",children:c.jsx("code",{className:"block break-all font-mono text-[11px] leading-[1.45] text-muted-foreground",children:e.name})})]})}function F9({field:e,context:t="editor",fieldState:n,onFieldSelect:r,inlineFilters:s,actions:o,onHover:i}){const a=p.useEditorStore(q=>q.isDevMode),l=t==="inline-filter"||t==="document-filter",u=t==="filter"||l,d=a||u||(n==null?void 0:n.state)==="unreachable"&&!u,f=p.useDashboardStore(q=>q.dashboard.filters),h=p.useDashboardStore(q=>q.selectedSheetId),m=p.useDashboardStore(q=>q.actions.removeFilter),{removeFilterValues:g}=p.useDashboardActions(),{assignFilter:b}=xZe(),x=t==="filter"?Qu(f,h):f,y=t==="filter"?x==null?void 0:x.find(q=>{if(Ip(q,e))return!0;if(q.fieldMeta)return!1;const G=ap(q.column||""),X=ap(e.name);return G.endsWith(`.${X}`)||G===X}):void 0,w=!!y,v=l&&(s==null?void 0:s.some(q=>Ip(q,e))),C=w||v,N=y&&u?f==null?void 0:f.find(q=>q.id===y.id):void 0,k=N&&(N.applyToSheetIds&&N.applyToSheetIds.length>1||N.excludeSheetIds&&N.excludeSheetIds.length>0||!N.applyToSheetIds&&!N.excludeSheetIds&&!N.sheetId),[_,j]=S.useState(!1),[,I]=S.useState(null),{attributes:E,listeners:T,setNodeRef:D,transform:A,transition:P,isDragging:R}=Ig({id:e.id,disabled:d}),H=p.useEditorStore(q=>q.card),{handleFieldClick:z}=Iie(H),{handleDevModeFieldClick:U,isNumberField:W}=Mie(),O=()=>{N&&(console.log("[SourceField] Removing multi-sheet filter:",N.id),g(N.id),m(N.id)),I(null),j(!1)},Z=()=>{if(l&&r){r(e);return}t==="filter"?C&&k?(I(e),j(!0)):b(e,"sheet"):a?U(e):z(e)},Y={column_name:e.name,data_type:e.dataType,label:e.label,description:e.description},M={transform:di.Transform.toString(A),transition:P};function K(q){return q==="domain"?{label:"Semantic domain",Icon:Ume}:q==="sheet"?{label:"Sheet",Icon:ep}:q==="dashboard"?{label:"Dashboard",Icon:ep}:{label:"Card",Icon:NR}}const L=tL(e),$=e.fieldScope,B=$&&!L?K($):null,V=(n==null?void 0:n.state)==="unreachable",F=(n==null?void 0:n.state)==="indirect";return c.jsxs(c.Fragment,{children:[c.jsx(Nie,{ref:D,style:M,...d?{}:E,...d?{}:T,onClick:Z,onMouseEnter:q=>i==null?void 0:i(!0,q.currentTarget),onMouseLeave:()=>i==null?void 0:i(!1),title:n==null?void 0:n.tooltip,selected:w,dragging:R,disableHover:V,inQuery:!u&&!!(n!=null&&n.isSelected),icon:c.jsx(fv,{dataType:e.dataType,calculated:!!L}),label:e.label||e.name,trailing:c.jsxs(c.Fragment,{children:[a&&!u&&W(e)&&c.jsx("span",{onClick:q=>q.stopPropagation(),onPointerDown:q=>q.stopPropagation(),children:c.jsx(yZe,{column:Y})}),o?c.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:q=>q.stopPropagation(),onPointerDown:q=>q.stopPropagation(),children:o}):t==="editor"?c.jsxs(po,{children:[c.jsx(go,{asChild:!0,children:c.jsx("button",{type:"button","aria-label":"Field actions",onClick:q=>q.stopPropagation(),onPointerDown:q=>q.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:c.jsx(da,{className:"h-3 w-3"})})}),c.jsx(Ks,{align:"end",className:"w-44",children:c.jsx(bn,{onClick:q=>{q.stopPropagation(),navigator.clipboard.writeText(e.name).then(()=>{tt.success(`Copied "${e.name}"`)}).catch(()=>{tt.error("Could not copy field name")})},children:"Copy field name"})})]}):null,t==="editor"&&B&&c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.jsx("span",{"aria-label":`${B.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:q=>q.stopPropagation(),onPointerDown:q=>q.stopPropagation(),children:c.jsx(B.Icon,{className:"h-3 w-3"})})}),c.jsxs(p.TooltipContent,{side:"top",align:"end",children:[B.label," calculated field"]})]})]}),className:p.cn((a||u)&&"cursor-pointer",!d&&!a&&!u&&"cursor-grab active:cursor-grabbing",V&&"cursor-not-allowed opacity-50",F&&"text-muted-foreground/80",v&&"bg-primary/10 hover:bg-primary/15")}),c.jsx(dh,{open:_,onOpenChange:j,children:c.jsxs(Uu,{children:[c.jsxs(qu,{children:[c.jsx(Yu,{children:"Remove Filter from Multiple Sheets?"}),c.jsx(Gu,{children:"This filter is currently applied to multiple sheets. Removing it will affect all sheets where it's applied."})]}),c.jsxs(Wu,{children:[c.jsx(Zu,{children:"Cancel"}),c.jsx(Ku,{onClick:O,children:"Remove Filter"})]})]})})]})}var Na="Accordion",NZe=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[nL,kZe,_Ze]=p.createCollection(Na),[W_]=p.createContextScope(Na,[_Ze,Zse]),rL=Zse(),Rie=S.forwardRef((e,t)=>{const{type:n,...r}=e,s=r,o=r;return c.jsx(nL.Provider,{scope:e.__scopeAccordion,children:n==="multiple"?c.jsx(TZe,{...o,ref:t}):c.jsx(IZe,{...s,ref:t})})});Rie.displayName=Na;var[Fie,jZe]=W_(Na),[Pie,EZe]=W_(Na,{collapsible:!1}),IZe=S.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},collapsible:o=!1,...i}=e,[a,l]=p.useControllableState({prop:n,defaultProp:r??"",onChange:s,caller:Na});return c.jsx(Fie,{scope:e.__scopeAccordion,value:S.useMemo(()=>a?[a]:[],[a]),onItemOpen:l,onItemClose:S.useCallback(()=>o&&l(""),[o,l]),children:c.jsx(Pie,{scope:e.__scopeAccordion,collapsible:o,children:c.jsx(Oie,{...i,ref:t})})})}),TZe=S.forwardRef((e,t)=>{const{value:n,defaultValue:r,onValueChange:s=()=>{},...o}=e,[i,a]=p.useControllableState({prop:n,defaultProp:r??[],onChange:s,caller:Na}),l=S.useCallback(d=>a((f=[])=>[...f,d]),[a]),u=S.useCallback(d=>a((f=[])=>f.filter(h=>h!==d)),[a]);return c.jsx(Fie,{scope:e.__scopeAccordion,value:i,onItemOpen:l,onItemClose:u,children:c.jsx(Pie,{scope:e.__scopeAccordion,collapsible:!0,children:c.jsx(Oie,{...o,ref:t})})})}),[DZe,Y_]=W_(Na),Oie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,disabled:r,dir:s,orientation:o="vertical",...i}=e,a=S.useRef(null),l=p.useComposedRefs(a,t),u=kZe(n),f=p.useDirection(s)==="ltr",h=p.composeEventHandlers(e.onKeyDown,m=>{var j;if(!NZe.includes(m.key))return;const g=m.target,b=u().filter(I=>{var E;return!((E=I.ref.current)!=null&&E.disabled)}),x=b.findIndex(I=>I.ref.current===g),y=b.length;if(x===-1)return;m.preventDefault();let w=x;const v=0,C=y-1,N=()=>{w=x+1,w>C&&(w=v)},k=()=>{w=x-1,w<v&&(w=C)};switch(m.key){case"Home":w=v;break;case"End":w=C;break;case"ArrowRight":o==="horizontal"&&(f?N():k());break;case"ArrowDown":o==="vertical"&&N();break;case"ArrowLeft":o==="horizontal"&&(f?k():N());break;case"ArrowUp":o==="vertical"&&k();break}const _=w%y;(j=b[_].ref.current)==null||j.focus()});return c.jsx(DZe,{scope:n,disabled:r,direction:s,orientation:o,children:c.jsx(nL.Slot,{scope:n,children:c.jsx(p.Primitive.div,{...i,"data-orientation":o,ref:l,onKeyDown:r?void 0:h})})})}),iN="AccordionItem",[MZe,sL]=W_(iN),Lie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,value:r,...s}=e,o=Y_(iN,n),i=jZe(iN,n),a=rL(n),l=p.useId(),u=r&&i.value.includes(r)||!1,d=o.disabled||e.disabled;return c.jsx(MZe,{scope:n,open:u,disabled:d,triggerId:l,children:c.jsx(Jse,{"data-orientation":o.orientation,"data-state":Uie(u),...a,...s,ref:t,disabled:d,open:u,onOpenChange:f=>{f?i.onItemOpen(r):i.onItemClose(r)}})})});Lie.displayName=iN;var $ie="AccordionHeader",zie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Y_(Na,n),o=sL($ie,n);return c.jsx(p.Primitive.h3,{"data-orientation":s.orientation,"data-state":Uie(o.open),"data-disabled":o.disabled?"":void 0,...r,ref:t})});zie.displayName=$ie;var yA="AccordionTrigger",Bie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Y_(Na,n),o=sL(yA,n),i=EZe(yA,n),a=rL(n);return c.jsx(nL.ItemSlot,{scope:n,children:c.jsx(XUe,{"aria-disabled":o.open&&!i.collapsible||void 0,"data-orientation":s.orientation,id:o.triggerId,...a,...r,ref:t})})});Bie.displayName=yA;var Vie="AccordionContent",Hie=S.forwardRef((e,t)=>{const{__scopeAccordion:n,...r}=e,s=Y_(Na,n),o=sL(Vie,n),i=rL(n);return c.jsx(QUe,{role:"region","aria-labelledby":o.triggerId,"data-orientation":s.orientation,...i,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...e.style}})});Hie.displayName=Vie;function Uie(e){return e?"open":"closed"}var AZe=Rie,RZe=Lie,FZe=zie,qie=Bie,Wie=Hie;const oL=AZe,$y=Q.forwardRef(({className:e,...t},n)=>c.jsx(RZe,{ref:n,className:p.cn("border-b",e),...t}));$y.displayName="AccordionItem";const zy=Q.forwardRef(({className:e,children:t,...n},r)=>c.jsx(FZe,{className:"flex",children:c.jsxs(qie,{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,c.jsx(p.ChevronDown,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));zy.displayName=qie.displayName;const By=Q.forwardRef(({className:e,children:t,...n},r)=>c.jsx(Wie,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:c.jsx("div",{className:p.cn("pb-4 pt-0",e),children:t})}));By.displayName=Wie.displayName;let Yie=(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 G_=[{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}],PZe=G_.filter(e=>e.id!=="custom"&&!!e.insertTemplate),iL=e=>e.trim().toLowerCase().replace(/\s+/g,"_"),aN=e=>e!=null&&e.startsWith("card-source-")?e.replace("card-source-",""):e;function Gie(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),yie(n)){t.disqualified=!0;return}const s=(i=n.calculatedFormula)==null?void 0:i.inputFields;if(s!=null&&s.length){Gie(s,t);return}if(n.expression&&!(Lu(n)==="inline_expression"&&la(n)&&n.fieldScope==="domain")){t.disqualified=!0;return}if(!n.entityName||!n.entityId){t.disqualified=!0;return}const o=n.qualifiedEntityName||n.entityId||n.entityName;t.entities.has(o)||t.entities.set(o,{entityName:n.entityName,entityId:n.entityId,qualifiedEntityName:n.qualifiedEntityName})})}function aL(e){const t={entities:new Map,disqualified:!1,visited:new Set};if(Gie(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 P9="calculated_fields";function OZe(e){return e?e.startsWith("calc_")||e.startsWith("calc_dim_"):!1}function LZe(e){return e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===P9||e.qualifiedEntityName===P9||OZe(e.id)}function $Ze(e){return e.aggregate?e.aggregate:DP(e.dataType)}function zZe(e,t){const n=$Ze(t);return n==="DISTINCT"?`COUNT(DISTINCT ${e})`:`${n}(${e})`}function BZe(e,t){return e.replace(/\{field_(\d+)\}/g,(n,r)=>{const s=Number(r),o=t[s];return!o||LZe(o)||typeof o.expression=="string"&&OQ(o.expression)?n:zZe(n,o)})}function VZe(e,t,n,r,s,o,i,a,l,u){if(!G_.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=iL(e),x=aL(h);return{id:i||`calc_${Yie(10)}`,name:b,label:e,alias:b,qualifiedFieldName:b,dataType:"number",role:"metric",expression:f,calculatedFormula:g,entityId:x.kind==="inline"?x.entityId:o,entityName:x.kind==="inline"?x.entityName:nr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:x.kind==="inline"?x.qualifiedEntityName:void 0,entityType:x.kind==="inline"?"dataset":"table",description:`Calculated field: ${e}`}}function HZe(e){var r,s;const t=G_.find(o=>o.id===e.operation);if(!t)return"Unknown operation";if(e.operation==="custom")return"Custom expression";if(e.operation==="scale"){const o=((r=e.inputFields[0])==null?void 0:r.label)||((s=e.inputFields[0])==null?void 0:s.name)||"A",i=e.constant??1;return`${o} × ${i}`}return e.inputFields.map(o=>o.label||o.name).join(` ${t.symbol} `)}function UZe(e,t,n,r,s,o){const i=iL(e),a=aL(n);return LQ({id:o||`calc_dim_${Yie(10)}`,name:i,label:e.trim(),alias:i,qualifiedFieldName:i,dataType:r,role:"groupby",expression:t.trim(),calculatedFormula:{operation:"custom",inputFields:n.map(l=>l.role==="metric"?{...l,role:"metric"}:{...l,role:"groupby"})},entityId:a.kind==="inline"?a.entityId:s,entityName:a.kind==="inline"?a.entityName:nr.CALCULATED_FIELD_ENTITY_MARKER,qualifiedEntityName:a.kind==="inline"?a.qualifiedEntityName:void 0,entityType:a.kind==="inline"?"dataset":"table",description:`Calculated field: ${e.trim()}`})}function Kie(e){return e==="metric"?"Calculated Metric":"Calculated Column"}function qZe(e){return e==="inline"?"Single dataset":"Cross-entity"}function Zb(e){switch(e){case"card":return"This card";case"sheet":return"This sheet";case"dashboard":return"This dashboard";case"domain":return"Semantic domain"}}function O9(e){return e.replace(/\s+/g,"")}function WZe(e){var s;const t=e.calculatedFormula;if(!t||t.operation==="custom")return;const n=G_.find(o=>o.id===t.operation),r=(s=n==null?void 0:n.template)==null?void 0:s.call(n);if(r)return t.operation!=="scale"?r:r.replace("{constant}",String(t.constant??1))}function YZe(e){var r;const t=e.expression||"",n=WZe(e);return!n||O9(t)!==O9(n)?t:BZe(t,((r=e.calculatedFormula)==null?void 0:r.inputFields)||[])}function GZe(e){const t=new Set,n=/\{field_(\d+)\}/g;let r=n.exec(e);for(;r;)t.add(Number(r[1])),r=n.exec(e);return[...t].sort((s,o)=>s-o)}function KZe(e){var o;const t=e.expression||"",n=GZe(t);if(n.length===0)return{readOnly:!1};const r=((o=e.calculatedFormula)==null?void 0:o.inputFields)||[];return n[n.length-1]<r.length?{readOnly:!1}:{readOnly:!0,reason:"This legacy metric uses saved field tokens but is missing the input metadata needed to reopen it safely. It can be viewed, but editing is disabled to avoid changing query semantics."}}function ZZe(e,t){const{aggregate:n,...r}=e;return{...r,...t}}function XZe(e){var r;const t=new Map;return(((r=e==null?void 0:e.calculatedFormula)==null?void 0:r.inputFields)||[]).forEach(s=>{const o=aN(s.id);o&&t.set(o,s),s.qualifiedFieldName&&t.set(s.qualifiedFieldName,s),s.name&&t.set(s.name,s)}),t}function QZe(e,t){const n=aN(e.id);return n&&t.get(n)||e.qualifiedFieldName&&t.get(e.qualifiedFieldName)||t.get(e.name)}function JZe(e){const t=DP(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 eXe(e,t){const n=XZe(t);return e.map(r=>{const s=QZe(r,n);return(s==null?void 0:s.role)==="metric"?s:JZe(r)})}function tXe({fields:e,normalizedName:t,existingFieldId:n,targetKind:r,targetEntityName:s,targetQualifiedEntityName:o}){return e.some(i=>{if(n&&i.id===n||i.name!==t)return!1;const a=Lu(i);if(r==="inline"){const l=p.getCalculatedFieldNamespace(i),u=o||s;return a==="inline_expression"&&!!u&&l===u}return a==="domain_calculated"})}function nXe({value:e,onChange:t,disabled:n,options:r=["dimension","metric"]}){const s=r.length>0?r:["dimension","metric"],o=["dimension","metric"].filter(l=>s.includes(l)),i=n||o.length<=1,a=o.includes(e)?e:o[0];return c.jsx(p.Tabs,{value:a,onValueChange:l=>t(l),className:"w-fit shrink-0",children:c.jsx(p.TabsList,{size:"xs",children:o.map(l=>c.jsx(p.TabsTrigger,{value:l,disabled:i,children:Kie(l)},l))})})}const lL=Q.forwardRef(({className:e,sideOffset:t=8,...n},r)=>c.jsx(p.Portal$2,{children:c.jsx(Sg,{children:c.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})})}));lL.displayName="ValidationTooltipContent";const Zie=p.Arrow2$1;function ET(e,t){return`${e} ${t}${e===1?"":"s"}`}function rXe({result:e}){const t=e.errors.length>0,n=ET(e.tokens.length,"token"),r=e.errors.length>0?ET(e.errors.length,"error"):null,s=e.warnings.length>0?ET(e.warnings.length,"warning"):null,o=e.errors.map(i=>i.suggestion?`${i.message} (${i.suggestion})`:i.message).join(`
|
|
1224
1224
|
`);return c.jsxs(p.Tooltip,{delayDuration:120,children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.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?c.jsx(p.X,{className:"h-3 w-3","aria-hidden":!0}):c.jsx(p.Check,{className:"h-3 w-3","aria-hidden":!0})})}),c.jsxs(lL,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[c.jsxs("div",{className:"space-y-2.5 p-3 text-xs",children:[c.jsx("div",{className:p.cn("font-semibold",t?"text-destructive":"text-emerald-700"),children:t?"Validation failed":"Validation passed"}),c.jsxs("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[c.jsx("span",{children:n}),r&&c.jsx("span",{children:r}),s&&c.jsx("span",{children:s}),e.inferredDataType&&c.jsxs("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&c.jsxs("div",{className:"space-y-1.5 border-t pt-2",children:[c.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),c.jsx("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((i,a)=>c.jsxs("div",{className:"flex items-start gap-1.5",children:[c.jsx("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${i.token}}`}),c.jsx(AN,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),i.field?c.jsx("span",{className:"break-all text-muted-foreground",children:i.field.qualifiedFieldName||i.field.name}):c.jsx("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${i.token}-${a}`))})]}),e.errors.length>0&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),c.jsx(bu,{text:o,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),c.jsx("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((i,a)=>c.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.warnings.length>0&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),c.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)=>c.jsxs("div",{className:"break-words",children:[i.message,i.suggestion?` (${i.suggestion})`:""]},`${i.code}-${a}`))})]}),e.inferredDataType&&c.jsxs("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",c.jsx("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),c.jsx(Zie,{className:"fill-popover"})]})]})}function sXe({onValidate:e,isValidating:t,validationResult:n,error:r,disabled:s}){return c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:e,disabled:t||s,className:"text-[11px]",children:t?"Validating…":"Validate"}),n&&c.jsx(rXe,{result:n}),!n&&r&&c.jsxs(p.Tooltip,{delayDuration:120,children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.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:c.jsx(p.X,{className:"h-3 w-3","aria-hidden":!0})})}),c.jsxs(lL,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[c.jsxs("div",{className:"space-y-2 text-xs",children:[c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx("span",{className:"font-semibold text-destructive",children:"Validation failed"}),c.jsx(bu,{text:r,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),c.jsx("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:r})]}),c.jsx(Zie,{className:"fill-popover"})]})]})]})}const oXe={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 iXe({mode:e,fieldType:t,prompt:n,onPromptChange:r,generated:s,explanation:o,isGenerating:i,error:a,onGenerate:l,onTryAgain:u,onCancel:d,onUseDraft:f,disabled:h}){const m=e==="result",g=e==="loading"||i,b=oXe[t],x=t==="metric"?"e.g. average revenue per order, in dollars":"e.g. bucket orders into 'Large' / 'Small' by amount";return c.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:[c.jsxs("div",{className:"flex items-center gap-2 border-b border-blue-200/60 px-3 py-2 dark:border-blue-900/30",children:[c.jsx(E1,{className:"h-3 w-3 text-blue-600 dark:text-blue-400","aria-hidden":!0}),c.jsx("span",{className:"text-[11px] font-medium text-zinc-900 dark:text-zinc-100",children:m?"AI draft — ready to use":"Compose with AI"}),c.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."}),c.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:c.jsx(p.X,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"space-y-2 p-3",children:m?c.jsxs(c.Fragment,{children:[n.trim()&&c.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:[c.jsx("span",{className:"shrink-0 text-zinc-400",children:"›"}),c.jsxs("span",{className:"italic text-zinc-600 dark:text-zinc-400",children:["“",n.trim(),"”"]})]}),c.jsx("div",{className:"overflow-hidden rounded-[5px] border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950",children:c.jsx("div",{className:"max-h-[180px]",children:c.jsx(p.CodeEditor,{value:s,language:"sql-jinja",readOnly:!0,embedded:!0,hideLineNumbers:!0,dense:!0,ariaLabel:"Generated expression"})})}),o?c.jsx("p",{className:"text-[11px] text-zinc-500 dark:text-zinc-400",children:o}):null]}):c.jsxs(c.Fragment,{children:[c.jsx(p.Label,{htmlFor:"ai-compose-prompt",className:"sr-only",children:"Describe what you want to calculate"}),c.jsx(hh,{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&&c.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[c.jsx("span",{className:"mr-1 text-[10px] uppercase tracking-[0.08em] text-zinc-400",children:"Try"}),b.map(y=>c.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&&c.jsx("p",{className:"whitespace-pre-wrap text-[11px] text-destructive",children:a})]})}),c.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?c.jsxs(c.Fragment,{children:[c.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:u,disabled:h,children:"Try again"}),c.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:d,disabled:h,children:"Cancel"}),c.jsx(p.Button,{type:"button",size:"xs",onClick:f,disabled:h||!s.trim(),children:"Use draft"})]}):c.jsxs(c.Fragment,{children:[c.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:d,disabled:h,children:"Cancel"}),c.jsx(p.Button,{type:"button",size:"xs",onClick:l,disabled:g||h||!n.trim(),className:p.cn("gap-1.5",g&&"pointer-events-none"),children:g?c.jsxs(c.Fragment,{children:[c.jsx(p.LoaderCircle,{className:"h-3 w-3 animate-spin","aria-hidden":!0}),"Generating…"]}):c.jsxs(c.Fragment,{children:[c.jsx(E1,{className:"h-3 w-3","aria-hidden":!0}),"Generate"]})})]})})]})}function aXe({groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:r,selectedFieldIds:s,disabled:o}){const i=new Set(s||[]),a=e.length>0||t.length>0,l=e.map(f=>f.id),u=(f,h)=>{if(!h)return f;const m=f.toLowerCase(),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 c.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2",children:[a&&c.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:[c.jsx(Xs,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),c.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&&c.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:c.jsx(p.X,{className:"h-3 w-3"})})]}),c.jsx(bl,{className:"min-h-0 flex-1",children:e.length===0?c.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."}):c.jsx(oL,{type:"multiple",defaultValue:l,className:"space-y-1",children:e.map(f=>c.jsxs($y,{value:f.id,className:"border-none",children:[c.jsx(zy,{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:c.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[c.jsx("span",{className:"max-w-[180px] truncate text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:f.label}),c.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:f.fields.length})]})}),c.jsx(By,{className:"pb-1",children:c.jsx("div",{children:f.fields.map(h=>{const m=i.has(h.id),g=!h.isCompatible||o,b=d(h,f.label);return c.jsx(Nie,{asButton:!0,disabled:g,icon:c.jsx(fv,{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?c.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Selected"}):void 0},h.id)})})})]},f.id))})})]})}function lXe({groups:e,searchTerm:t,onSearchTermChange:n,onFieldSelect:r,selectedFieldIds:s,disabled:o}){const[i,a]=S.useState(!1);return c.jsxs(p.Popover,{open:i,onOpenChange:a,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsxs(p.Button,{type:"button",variant:"outline",size:"xs",disabled:o,className:"gap-1.5",children:[c.jsx(wr,{className:"h-3 w-3","aria-hidden":!0}),"Insert field"]})}),c.jsx(p.PopoverContent,{align:"end",sideOffset:6,className:"z-[51] w-[320px] max-w-[min(320px,calc(100vw-32px))] p-2",children:c.jsx("div",{className:"flex h-[360px] min-h-0 flex-col",children:c.jsx(aXe,{groups:e,searchTerm:t,onSearchTermChange:n,onFieldClick:l=>{r(l),a(!1)},selectedFieldIds:s,disabled:o})})})]})}function cXe({onInsert:e,disabled:t}){return c.jsxs(po,{children:[c.jsx(go,{asChild:!0,children:c.jsxs(p.Button,{type:"button",variant:"outline",size:"xs",disabled:t,className:"gap-1.5",children:["Templates",c.jsx(p.ChevronDown,{className:"h-3 w-3","aria-hidden":!0})]})}),c.jsx(Ks,{align:"end",className:"w-[300px]",children:PZe.map(n=>{var r;return c.jsxs(bn,{onSelect:s=>{var i;s.preventDefault();const o=(i=n.insertTemplate)==null?void 0:i.call(n);o&&e(o)},className:"flex items-start justify-between gap-3 py-2",children:[c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-mono text-[12px] text-muted-foreground",children:n.symbol}),c.jsx("span",{className:"text-[12px] font-medium",children:n.label})]}),c.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?c.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:n.insertHint}):null]},n.id)})})]})}const uXe="Calculated fields";function dXe(e){var t;if(e.kind==="inline"){const n=(t=e.entityName)==null?void 0:t.trim();if(n)return`${n} dataset`}return uXe}function fXe({fieldType:e,inlineAnalysis:t,availability:n,hasInputFields:r=!0}){const s=[{label:"Type",value:Kie(e)}];return e==="metric"&&s.push({label:"Compute",value:"After aggregation"}),r&&(s.push({label:"Uses",value:qZe(t.kind)}),s.push({label:"Stored with",value:dXe(t)})),s.push({label:"Available in",value:Zb(n)}),s}function hXe(e){const t=fXe(e);return c.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:[c.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:t.map(n=>c.jsxs("span",{className:"inline-flex items-baseline gap-1.5 rounded-[4px] border bg-background px-1.5 py-0.5 text-[11px]",children:[c.jsx("span",{className:"text-[9px] font-medium uppercase tracking-[0.06em] text-muted-foreground/80",children:n.label}),c.jsx("span",{className:"text-foreground",children:n.value})]},n.label))}),c.jsx("span",{className:"text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70",children:"Derived"})]})}function mXe(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 pXe({endpoint:e,availableFields:t,fieldType:n,dialect:r}){const{authToken:s}=mt(),[o,i]=S.useState(!1),[a,l]=S.useState(null),u=S.useCallback(async f=>{var h;if(!e)return l("AI generation is not available"),null;if(!f.trim())return l("Describe what you want to calculate"),null;i(!0),l(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,(s==null?void 0:s.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 l(mXe(m)),null}finally{i(!1)}},[e,t,n,r,s==null?void 0:s.accessToken]),d=S.useCallback(()=>l(null),[]);return{generateExpression:u,isGenerating:o,error:a,resetError:d}}const gXe=/\{([^}]+)\}/g;function K_(e){return e.trim().toLowerCase()}function Xie(e){return Array.from(e.matchAll(gXe)).map(t=>t[1]).filter(Boolean)}function bXe(e){const t=new Set,n=[];return e.forEach(r=>{const s=K_(r);t.has(s)||(t.add(s),n.push(r))}),n}function cL(e){const t=new Map,n=(r,s)=>{const o=K_(r),i=t.get(o)||[];i.some(a=>a.id===s.id)||t.set(o,[...i,s])};return e.forEach(r=>{n(r.tokenLabel,r),r.name&&r.name!==r.tokenLabel&&n(r.name,r),r.baseLabel&&r.baseLabel!==r.tokenLabel&&n(r.baseLabel,r)}),t}function c1(e,t){const n=Xie(e),r=bXe(n),s=cL(t),o=r.map(a=>{const l=s.get(K_(a))||[];return l.length===1?l[0]:null}),i=r.filter((a,l)=>!o[l]);return{orderedTokens:r,orderedFields:o,unresolvedTokens:i}}function vA(e,t){return t.reduce((n,r,s)=>{const o=new RegExp(`\\{${xXe(r)}\\}`,"gi");return n.replace(o,`{field_${s}}`)},e)}function xXe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const yXe=e=>e.entityName===p.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===p.CALCULATED_FIELDS_GROUP_NAME||e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER?"Calculated Fields":e.qualifiedEntityName?p.toLabel(e.entityName||e.qualifiedEntityName):p.toLabel(e.entityName||"Other");function vXe(e){return e.entityName===p.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===p.CALCULATED_FIELDS_GROUP_NAME||e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER?p.CALCULATED_FIELDS_GROUP_NAME:e.qualifiedEntityName||e.entityName||"Other"}function wXe(e){return e.role!=="metric"?!1:e.fieldScope==="domain"||e.fieldScope==="sheet"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===nr.CALCULATED_FIELD_ENTITY_MARKER||e.entityName===p.CALCULATED_FIELDS_GROUP_NAME||e.qualifiedEntityName===p.CALCULATED_FIELDS_GROUP_NAME}function SXe(e,t){const n=new Set((t||[]).map(r=>aN(r)));return e.filter(r=>{const s=aN(r.id);return!(s&&n.has(s))})}function CXe(e){const t=new Map,n=new Map;return e.forEach(r=>{let o=r.entityName&&r.entityName!==nr.CALCULATED_FIELD_ENTITY_MARKER?`${r.entityName}.${r.name}`:r.name;const i=o.toLowerCase(),a=n.get(i)||0;a>0&&(o=`${o} ${a+1}`),n.set(i,a+1),t.set(r.id,o)}),t}function NXe(e,t,n,r){return t==="dimension"?e.map(s=>({...s,isCompatible:!wXe(s)})).filter(s=>r):t!=="metric"?e.map(s=>({...s,isCompatible:!0})):e.map(s=>({...s,isCompatible:!0}))}function kXe(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 _Xe(e){const t=new Map;return e.forEach(n=>{var s;const r=vXe(n);t.has(r)||t.set(r,{id:r,label:yXe(n),fields:[]}),(s=t.get(r))==null||s.fields.push(n)}),Array.from(t.values())}function jXe({fields:e,mode:t,searchTerm:n,excludeFieldIds:r,selectedAggregate:s,showIncompatible:o}){const i=S.useMemo(()=>SXe(e,r),[e,r]),a=S.useMemo(()=>CXe(i),[i]),l=S.useMemo(()=>i.map(g=>{const b=g.label||g.name,x=g.role==="metric"&&nr.isCalculatedMetric(g)||g.role==="groupby"&&nr.isCalculatedDimension(g);return{...g,baseLabel:b,tokenLabel:a.get(g.id)||b,isCalculated:x,isCompatible:!0}}),[i,a]),u=S.useMemo(()=>NXe(l,t,s,o),[l,t,s,o]),d=S.useMemo(()=>kXe(u,n),[u,n]),f=S.useMemo(()=>u.filter(g=>g.isCompatible),[u]),h=S.useMemo(()=>cL(f),[f]),m=S.useMemo(()=>_Xe(d),[d]);return{allFields:l,filteredFields:d,groups:m,tokenCandidates:h,tokenFields:f}}const EXe=e=>p.getDataType(e.dataType||"")==="number",L9=e=>EXe(e)?"SUM":"COUNT",IXe=e=>{if(e.role==="metric"){const n=e;return{...n,aggregate:n.aggregate||L9(e)}}const t=L9(e);return{...e,role:"metric",aggregate:t,alias:`${(e.alias||e.name).toLowerCase()}_${t.toLowerCase()}`}},TXe=(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 DXe({expression:e,availableFields:t,validationEndpoint:n,connectionId:r,dialect:s,fieldType:o,outputType:i,validationContext:a}){const{authToken:l}=mt(),[u,d]=S.useState(null),[f,h]=S.useState(!1),[m,g]=S.useState(null),b=S.useMemo(()=>cL(t),[t]),x=S.useMemo(()=>Xie(e).map(N=>{const k=b.get(K_(N))||[];return{token:N,field:k.length===1?k[0]:null}}),[e,b]),y=S.useCallback((C,N)=>{const k=[{code:"SQL_VALIDATION_ERROR",message:C,suggestion:(N==null?void 0:N.suggestion)||(N==null?void 0:N.errorCode)}];return{isValid:!1,tokens:x,errors:k,warnings:[]}},[x]),w=S.useCallback(async()=>{var P;g(null);const C=n==null?void 0:n.trim();if(!C){const R=y("Validation endpoint is not configured");return d(R),R}if(!!!(a!=null&&a.cardConfig&&(a!=null&&a.cardDataSource)&&(a!=null&&a.cardId)&&(a!=null&&a.connectionId||r))){const R=y("Validation context is incomplete for server-side validation");return d(R),R}const{orderedTokens:k,orderedFields:_}=c1(e,t),j=[],I=[];k.forEach((R,H)=>{const z=_[H];z&&(j.push(R),I.push(z))});const E=o==="metric"?I.map(IXe):I,T=TXe(e,I),D=vA(e,j),A={type:"calculated-field-expression",fieldType:o,expression:D,inputFields:E,outputType:i,options:{validateWithExplain:!0},context:{connectionId:(a==null?void 0:a.connectionId)||r,cardId:a==null?void 0:a.cardId,cardConfig:a==null?void 0:a.cardConfig,cardDataSource:a==null?void 0:a.cardDataSource,activeFilters:(a==null?void 0:a.activeFilters)||[],cardType:(a==null?void 0:a.cardType)||"table",dialect:s}};h(!0);try{const R=await p.postRequestRegular(C,(l==null?void 0:l.accessToken)||"",A),H=R==null?void 0:R.status,z=R==null?void 0:R.error,U=R==null?void 0:R.errorCode,W=[],O=[];H==="invalid"?W.push({code:"SQL_VALIDATION_ERROR",message:z||"Expression failed SQL validation",suggestion:U?`Validation code: ${U}`:void 0}):H==="unverified"?O.push({code:"EXECUTION_UNVERIFIED",message:z||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):H!=="valid"&&W.push({code:"SQL_VALIDATION_ERROR",message:z||"Unexpected SQL validation response from server",suggestion:U?`Validation code: ${U}`:void 0});const Z={isValid:(H==="valid"||H==="unverified")&&W.length===0,tokens:x,errors:W,warnings:O,inferredDataType:(R==null?void 0:R.inferredDataType)??((P=R==null?void 0:R.metadata)==null?void 0:P.inferredDataType)??T??i??void 0};return d(Z),Z}catch(R){const H=(R==null?void 0:R.error)||(R==null?void 0:R.message)||"Expression validation failed";g(H);const z=y(H);return d(z),z}finally{h(!1)}},[n,a,r,e,t,o,i,s,l==null?void 0:l.accessToken,y,x]),v=S.useCallback(()=>{d(null),g(null)},[]);return{validationResult:u,isValidating:f,serverError:m,validateExpression:w,resetValidation:v}}const $9=[{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"}],MXe=[],AXe="https://docs.semaphor.cloud/docs/concepts/calculated-fields/metrics",RXe="https://docs.semaphor.cloud/docs/concepts/calculated-fields/dimensions",FXe="SUM({revenue}) / NULLIF(COUNT({order_id}), 0)",PXe="DATE_TRUNC('month', {created_at})";function Qie({open:e,onOpenChange:t,availableFields:n,existingField:r,existingFieldScope:s,onSave:o,onSaveToSheet:i,onSaveToDashboard:a,cardId:l,initialFieldType:u="metric",allowedFieldTypes:d}){var Et,Bt,be;const{tokenProps:f}=mt(),h=((Bt=(Et=f.config)==null?void 0:Et.projectFeatures)==null?void 0:Bt.features.aiWritingHelpers)!==!1,{selectedConnection:m}=gK(),g=p.useEditorStore(Ne=>{var Be;return(Be=Ne.card)==null?void 0:Be.config}),b=p.useEditorStore(Ne=>{var Be;return(Be=Ne.card)==null?void 0:Be.dataSource}),x=p.useEditorStore(Ne=>{var Be;return(Be=Ne.card)==null?void 0:Be.type}),w=p.useEditorStore(Ne=>Ne.filterValues)??MXe,[v,C]=S.useState(u),[N,k]=S.useState(""),[_,j]=S.useState(""),[I,E]=S.useState(null),[T,D]=S.useState("card"),[A,P]=S.useState({}),[R,H]=S.useState(""),[z,U]=S.useState(!1),[W,O]=S.useState(""),[Z,Y]=S.useState(""),[M,K]=S.useState(void 0),[L,$]=S.useState(null),[B,V]=S.useState(!1),[F,q]=S.useState(!1),[G,X]=S.useState(null),J=S.useId(),fe=S.useRef(!1),ue=S.useRef(null),{userContext:pe}=zi(),ye=S.useMemo(()=>n.filter(Ne=>Ne.fieldScope==="domain"&&!!Ne.expression),[n]),ie=S.useMemo(()=>ye.filter(Ne=>Ne.role==="metric"),[ye]),ae=S.useMemo(()=>ye.filter(Ne=>Ne.role==="groupby"),[ye]),Ie=!((pe==null?void 0:pe.type)==="organization"),oe=!!G,me=Ie||oe,we=!!i,ge=!!a,re=(be=f==null?void 0:f.apiServiceUrl)==null?void 0:be.replace(/\/$/,""),ne=re?`${re}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",he=re?`${re}/v1/ai/generate`:"/v1/ai/generate",ee=S.useMemo(()=>{var gt;const Ne=[...n];return(((gt=r==null?void 0:r.calculatedFormula)==null?void 0:gt.inputFields)||[]).forEach(Lt=>{Ne.some(_n=>_n.id===Lt.id||_n.qualifiedFieldName===Lt.qualifiedFieldName||_n.name===Lt.name)||Ne.push(Lt)}),Ne},[n,r]),{tokenFields:Ce,groups:ve}=jXe({fields:ee,mode:v,searchTerm:R,excludeFieldIds:r?[r.id]:void 0,selectedAggregate:void 0,showIncompatible:!0}),te=Ce,{generateExpression:_e,isGenerating:De,error:Fe,resetError:Ye}=pXe({endpoint:he,availableFields:te,fieldType:v,dialect:m==null?void 0:m.dialect}),ze=De?"loading":Z?"result":"prompt",{validationResult:Ve,validateExpression:Ke,isValidating:ke,serverError:Xe,resetValidation:Pe}=DXe({expression:_,availableFields:te,validationEndpoint:ne,connectionId:m==null?void 0:m.id,dialect:m==null?void 0:m.dialect,fieldType:v,outputType:I||void 0,validationContext:{connectionId:(m==null?void 0:m.id)||(b==null?void 0:b.connectionId),cardId:l,cardConfig:g||{},cardDataSource:b||null,activeFilters:w,cardType:x}}),He=Ve==null?void 0:Ve.inferredDataType,nt=I||He||"string",Me=S.useCallback(()=>{U(!1),O(""),Y(""),K(void 0),Ye()},[Ye]),Ee=S.useCallback(()=>{me||!h||(Y(""),K(void 0),Ye(),U(!0))},[h,me,Ye]),We=S.useCallback(async()=>{if(!W.trim())return;const Ne=await _e(W);Ne&&(Y(Ne.generated),K(Ne.explanation))},[W,_e]),vt=S.useCallback(()=>{Y(""),K(void 0),Ye()},[Ye]),yt=S.useCallback(()=>{Z.trim()&&(j(Z),Pe(),Me())},[Z,Me,Pe]),ft=S.useMemo(()=>{const{orderedFields:Ne}=c1(_,te);return Ne.filter(Be=>!!Be)},[te,_]),Nt=S.useMemo(()=>aL(ft),[ft]),lt=S.useMemo(()=>{if(!N.trim())return!1;const Ne=iL(N);return tXe({fields:v==="metric"?ie:ae,normalizedName:Ne,existingFieldId:s==="domain"?r==null?void 0:r.id:void 0,targetKind:Nt.kind==="inline"?"inline":"root",targetEntityName:Nt.kind==="inline"?Nt.entityName:void 0,targetQualifiedEntityName:Nt.kind==="inline"?Nt.qualifiedEntityName:void 0})},[Nt,ae,ie,r,s,v,N]),Pt=S.useMemo(()=>ft.map(Ne=>Ne.id),[ft]),Te=Ne=>{me||r||C(Ne)},Ze=S.useCallback(()=>{k(""),j(""),E(null),D("card"),P({}),H(""),U(!1),O(""),Y(""),K(void 0),X(null),$(null),V(!1),Pe(),Ye(),t(!1)},[t,Pe,Ye]),Je=S.useCallback((Ne,Be)=>Ne.replace(/\{field_(\d+)\}/g,(gt,Lt)=>{var Tn;const jt=Be[Number(Lt)];return jt?`{${((Tn=te.find(Sr=>Sr.id===jt.id))==null?void 0:Tn.tokenLabel)||jt.label||jt.name}}`:gt}),[te]),st=S.useCallback(Ne=>{var Lt;const Be=((Lt=Ne.calculatedFormula)==null?void 0:Lt.inputFields)||[],gt=Ne.role==="metric"?YZe(Ne):Ne.expression||"";j(Je(gt,Be))},[Je]);S.useEffect(()=>{if(!e){fe.current=!1,ue.current=null;return}const Ne=r?`${r.role}-${r.id||r.name}`:"new";if(fe.current&&ue.current===Ne)return;if(fe.current=!0,ue.current=Ne,P({}),H(""),Pe(),r){if(r.role==="metric"){const jt=KZe(r);C("metric"),k(r.label||r.name),D(s||"card"),X(jt.reason||null),st(r),E(null);return}X(null),C("dimension");const gt=r;k(gt.label||gt.name),D(s||"card"),st(gt);const Lt=$9.some(jt=>jt.value===gt.dataType)?gt.dataType:"string";E(Lt);return}const Be=d&&d.length>0?d.includes(u)?u:d[0]:u;C(Be),k(""),j(""),E(null),X(null),D("card")},[e,r,s,u,d,st,Pe]);const pt=S.useCallback(Ne=>{const Be=typeof document<"u"?document.getElementById(J):null;if(!Be){j(jt=>jt+Ne);return}const gt=Be.selectionStart||0,Lt=Be.selectionEnd||0;j(jt=>`${jt.slice(0,gt)}${Ne}${jt.slice(Lt)}`),requestAnimationFrame(()=>{Be.focus();const jt=gt+Ne.length;Be.setSelectionRange(jt,jt)})},[J]),Rt=Ne=>{if(me)return;const Be=Ne.tokenLabel||Ne.label||Ne.name;pt(`{${Be}}`)},Mt=Ne=>{me||pt(Ne)},cn=async()=>{const Ne={};return N.trim()||(Ne.name="Name is required"),_.trim()||(Ne.expression="Expression is required"),Ne.expression||(await Ke()).isValid||(Ne.expression="Fix validation errors before saving"),P(Ne),Object.keys(Ne).length===0},Le=()=>{const{orderedTokens:Ne,orderedFields:Be}=c1(_,te),gt=Be.filter(_n=>!!_n),Lt=vA(_,Ne),jt=UZe(N,Lt,gt,nt,l,r==null?void 0:r.id);return r&&r.role==="groupby"?{...r,...jt}:jt},Ue=()=>{const{orderedTokens:Ne,orderedFields:Be}=c1(_,te),gt=Be.filter(Tn=>!!Tn),Lt=eXe(gt,(r==null?void 0:r.role)==="metric"?r:void 0),jt=vA(_,Ne),_n=VZe(N,"custom",null,null,{},l,r==null?void 0:r.id,jt,void 0,Lt);return r&&r.role==="metric"?ZZe(r,_n):_n},ot=async Ne=>{if(Ne==="domain"){P(gt=>({...gt,scope:"Domain scope is not available in this explorer."}));return}const Be=v==="dimension"?Le():Ue();if(Ne==="sheet"){if(!i){P(gt=>({...gt,scope:"Sheet scope is not available"}));return}await i(Be),Ze();return}if(Ne==="dashboard"){if(!a){P(gt=>({...gt,scope:"Dashboard scope is not available"}));return}await a(Be),Ze();return}await o(Be),Ze()},kt=async()=>{if(me||(P({}),!await cn()))return;const Ne=we||ge?T:s||"card";if(v==="metric"&&Ne!=="domain"&<&&!r){$(Ne),V(!0);return}q(!0);try{await ot(Ne)}finally{q(!1)}},St=v==="metric"?AXe:RXe,it=v==="metric"?FXe:PXe,ce=v==="metric"?"Metric formula":"Column expression",$e=we||ge,ht=d||["metric","dimension"];return c.jsxs(c.Fragment,{children:[c.jsxs(yo,{modal:!1,open:e,onOpenChange:Ne=>{Ne?t(!0):Ze()},children:[e&&c.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),c.jsxs(Js,{className:"max-w-3xl max-h-[90vh] overflow-hidden p-0",onInteractOutside:Ne=>{Ne.preventDefault()},children:[c.jsxs(Bi,{className:"space-y-2 border-b py-3 pl-5 pr-12",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(eo,{className:"shrink-0 text-[14px] font-semibold",children:r?"Edit field":"New field"}),c.jsx(nXe,{value:v,onChange:Te,disabled:me||!!r,options:ht}),c.jsx(p.Input,{id:"calculated-name",value:N,onChange:Ne=>k(Ne.target.value),placeholder:"Field name","aria-label":"Field name","aria-invalid":!!A.name,className:`h-7 flex-1 ${A.name?"border-destructive":""}`,disabled:me})]}),c.jsx(Bo,{className:"sr-only",children:"Build a calculated metric or column using expressions."}),A.name&&c.jsx("p",{className:"text-xs text-destructive",children:A.name}),G&&c.jsxs("div",{className:"rounded-control border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:[c.jsx("p",{className:"font-medium text-foreground",children:"Read-only legacy metric"}),c.jsx("p",{children:G})]})]}),c.jsxs("div",{className:"flex max-h-[calc(80vh-180px)] min-h-0 flex-col gap-4 overflow-y-auto px-5 py-4",children:[c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs("div",{className:"flex items-baseline gap-2 whitespace-nowrap",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:ce}),v==="metric"&&c.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:[c.jsx("span",{className:"text-muted-foreground/70",children:"·"}),c.jsx("span",{className:"font-medium text-foreground",children:"After aggregation"}),c.jsx(p.Info,{className:"h-2.5 w-2.5 text-muted-foreground/70","aria-hidden":!0})]})]}),c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(lXe,{groups:ve,searchTerm:R,onSearchTermChange:H,onFieldSelect:Rt,selectedFieldIds:Pt,disabled:me||z}),v==="metric"&&c.jsx(cXe,{onInsert:Mt,disabled:me||z}),!!he&&h&&!me&&c.jsxs(p.Button,{type:"button",variant:z?"default":"outline",size:"xs",onClick:Ee,disabled:z,className:"gap-1.5",children:[c.jsx(E1,{className:"h-3 w-3","aria-hidden":!0}),z?"Composing…":"Generate"]}),c.jsxs("a",{href:St,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground",children:["Docs ",c.jsx(Jm,{className:"h-2.5 w-2.5"})]})]})]}),z?c.jsx(iXe,{mode:ze,fieldType:v,prompt:W,onPromptChange:O,generated:Z,explanation:M,isGenerating:De,error:Fe,onGenerate:()=>void We(),onTryAgain:vt,onCancel:Me,onUseDraft:yt}):c.jsxs(c.Fragment,{children:[c.jsx("div",{"aria-invalid":!!A.expression,className:`overflow-hidden rounded-control border ${A.expression?"border-destructive":"border-input"}`,children:c.jsx("div",{className:"h-[160px]",children:c.jsx(p.CodeEditor,{value:_,onValueChange:j,language:"sql-jinja",placeholder:it,ariaLabel:v==="metric"?"Metric formula":"Column expression",textareaId:J,readOnly:me,embedded:!0,flushGutter:!0,dense:!0})})}),c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx(sXe,{onValidate:Ke,isValidating:ke,validationResult:Ve,error:Xe,disabled:me}),c.jsx("span",{className:"text-[11px] text-muted-foreground",children:v==="metric"?"Aggregate functions allowed":"Aggregate functions not allowed"})]}),A.expression&&c.jsx("p",{className:"text-xs text-destructive",children:A.expression})]})]}),v==="dimension"&&c.jsxs("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Output type"}),c.jsxs(p.Select,{value:nt,onValueChange:Ne=>E(Ne),disabled:me,children:[c.jsx(p.SelectTrigger,{className:"h-7 w-44 text-[12px]",children:c.jsx(p.SelectValue,{placeholder:"Select output type"})}),c.jsx(p.SelectContent,{children:$9.map(Ne=>c.jsx(p.SelectItem,{value:Ne.value,children:Ne.label},Ne.value))})]}),He&&!I&&c.jsxs("p",{className:"col-start-2 text-[11px] text-muted-foreground",children:["Suggested type: ",He]})]}),$e&&c.jsxs("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Availability"}),c.jsx(p.Tabs,{value:T,onValueChange:Ne=>D(Ne),className:"w-fit",children:c.jsxs(p.TabsList,{size:"xs",children:[c.jsx(p.TabsTrigger,{value:"card",disabled:me,children:Zb("card")}),we&&c.jsx(p.TabsTrigger,{value:"sheet",disabled:me,children:Zb("sheet")}),ge&&c.jsx(p.TabsTrigger,{value:"dashboard",disabled:me,children:Zb("dashboard")})]})}),A.scope&&c.jsx("p",{className:"col-start-2 text-xs text-destructive",children:A.scope})]})]}),c.jsx(hXe,{fieldType:v,inlineAnalysis:Nt,availability:$e?T:s||"card",hasInputFields:ft.length>0}),c.jsxs(vc,{className:"gap-1.5 border-t px-5 py-2.5",children:[c.jsx(p.Button,{variant:"outline",size:"xs",onClick:Ze,disabled:F,children:"Cancel"}),c.jsx(p.Button,{size:"xs",onClick:()=>void kt(),disabled:F||ke||me,children:F?c.jsxs(c.Fragment,{children:[c.jsx(p.LoaderCircle,{className:"mr-1.5 h-3 w-3 animate-spin"}),"Applying…"]}):oe?"Read-only":"Apply"})]})]})]}),c.jsx(dh,{open:B,onOpenChange:V,children:c.jsxs(Uu,{children:[c.jsxs(qu,{children:[c.jsx(Yu,{children:"Name conflict"}),c.jsxs(Gu,{children:['A domain metric named "',N.trim(),'" already exists. Your local version will override it for the selected availability:'," ",Zb(L||"card"),". Continue?"]})]}),c.jsxs(Wu,{children:[c.jsx(Zu,{onClick:()=>{$(null)},children:"Choose different name"}),c.jsx(Ku,{onClick:async()=>{if(L){V(!1),q(!0);try{await ot(L)}finally{q(!1),$(null)}}},children:"Continue"})]})]})})]})}function OXe(e,t){const n=e.fieldScope==="sheet"||e.fieldScope==="dashboard";if(e.role==="metric"){const r=t.metricFields.find(s=>p.matchesCalculatedField(s,e,{allowComparableFallback:n}));if(r)return r}if(e.role==="groupby"){const r=t.groupByFields.find(s=>p.matchesCalculatedField(s,e,{allowComparableFallback:n}));if(r)return r}return t.storedCalculatedFields.find(r=>p.matchesCalculatedField(r,e,{allowComparableFallback:n}))}function LXe(e,t){const n={...e,fieldScope:"domain"};return t.find(r=>r.fieldScope==="domain"&&p.matchesCalculatedField(r,n))}function Z_(e,t){var n,r,s,o;if(e.role==="metric"&&t.role==="metric"){const i=e,a=t;return{...a,parameters:i.parameters||a.parameters?{filters:((n=i.parameters)==null?void 0:n.filters)??((r=a.parameters)==null?void 0:r.filters),windowTransform:((s=i.parameters)==null?void 0:s.windowTransform)??((o=a.parameters)==null?void 0:o.windowTransform)}:void 0,aliasTemplate:i.aliasTemplate??a.aliasTemplate,valueAliases:i.valueAliases??a.valueAliases,customFormat:i.customFormat??a.customFormat,comparisonType:i.comparisonType??a.comparisonType,comparisonDisplay:i.comparisonDisplay??a.comparisonDisplay,targetValue:i.targetValue??a.targetValue}}if(e.role==="groupby"&&t.role==="groupby"){const i=e,a=t;return{...a,granularity:i.granularity??a.granularity,dateFormat:i.dateFormat??a.dateFormat,customFormat:i.customFormat??a.customFormat,timeDrillPath:i.timeDrillPath??a.timeDrillPath}}return t}function uL(e,t,n,r){if(!n)return null;const s=n||t,o=p.findCalculatedFieldIndex(e,s,r);if(n&&o<0)return null;if(o>=0){const i=e[o],a=i==null?void 0:i.id,l=r!=null&&r.mergeMatchedField?r.mergeMatchedField(i,t):t,d=a&&a!==l.id&&!((i==null?void 0:i.fieldScope)==="domain"&&l.fieldScope==="domain")?{...l,id:a}:l;return e.map((f,h)=>h===o?d:f)}return null}function dL(e,t){return{...e,fieldScope:t}}function $Xe(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 zXe(e,t,n,r){if(!(e!=null&&e.length)||!n)return null;const s=e.findIndex(u=>$Xe(u,n,r));if(s<0)return null;const o=e[s],i=Z_(o,{...t,role:o.role}),a=(()=>{if(o.role==="sortby")return{...i,role:"sortby",direction:o.direction};if(o.role==="detail"){const u=o;return{...i,role:"detail",dateFormat:u.dateFormat??i.dateFormat,customFormat:u.customFormat??i.customFormat}}return i})(),l=o.id&&o.id!==i.id?{...a,id:o.id}:a;return e.map((u,d)=>d===s?l:u)}function wA(e){const t=dL(e.updatedField,"card"),n=uL(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard",mergeMatchedField:Z_}),r=p.upsertCalculatedField(e.storedFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard"}),s=(e.previousScope==="sheet"||e.previousScope==="dashboard")&&e.editingField?p.removeCalculatedField(e.sharedFields,e.editingField,{allowComparableFallback:!0}):e.sharedFields,o=fL({sortByFields:e.sortByFields,updatedField:t,editingField:e.editingField,previousScope:e.previousScope});return{nextActiveFields:n,nextSortByFields:o,nextStoredFields:r,nextSharedFields:s}}function SA(e){const t=dL(e.updatedField,"sheet"),n=uL(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard",mergeMatchedField:Z_}),r=p.upsertCalculatedField(e.sheetFields,t,e.editingField,{allowComparableFallback:!0}),s=e.previousScope==="card"&&e.editingField?p.removeCalculatedField(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields,o=e.previousScope==="dashboard"&&e.editingField&&e.dashboardFields?p.removeCalculatedField(e.dashboardFields,e.editingField,{allowComparableFallback:!0}):e.dashboardFields,i=fL({sortByFields:e.sortByFields,updatedField:t,editingField:e.editingField,previousScope:e.previousScope});return{nextActiveFields:n,nextSortByFields:i,nextStoredFields:s,nextSheetFields:r,nextDashboardFields:o}}function Jie(e){const t=dL(e.updatedField,"dashboard"),n=uL(e.activeFields,t,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard",mergeMatchedField:Z_}),r=p.upsertCalculatedField(e.sharedFields,t,e.editingField,{allowComparableFallback:!0}),s=e.previousScope==="card"&&e.editingField?p.removeCalculatedField(e.storedFields,e.editingField,{allowComparableFallback:!0}):e.storedFields,o=e.previousScope==="sheet"&&e.editingField&&e.sheetFields?p.removeCalculatedField(e.sheetFields,e.editingField,{allowComparableFallback:!0}):e.sheetFields,i=fL({sortByFields:e.sortByFields,updatedField:t,editingField:e.editingField,previousScope:e.previousScope});return{nextActiveFields:n,nextSortByFields:i,nextStoredFields:s,nextSharedFields:r,nextSheetFields:o}}function fL(e){return zXe(e.sortByFields||[],e.updatedField,e.editingField,{allowComparableFallback:e.previousScope==="sheet"||e.previousScope==="dashboard"})}function Ad(e){const{nextSharedFields:t,currentSharedFields:n,isVisualEditing:r,selectedSheetId:s,updateFrame:o,updateSheetCalculatedFields:i,currentFrame:a,nextFramePatch:l,persistFrame:u,persistFrames:d}=e,f=l?{...l,calculatedFields:t}:{calculatedFields:t};(t!==n||l)&&o(f),s&&(r||(u&&(d!=null&&d.length)?d.forEach(h=>{u(s,{...h,calculatedFields:void 0})}):u&&a&&l&&u(s,{...a,...l,calculatedFields:void 0}),i&&i(s,t)))}const BXe=[];function dS({label:e,count:t,active:n,onClick:r,ariaLabel:s}){return c.jsxs("button",{type:"button",onClick:r,"aria-label":s,"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:[c.jsx("span",{children:e}),c.jsx("span",{className:p.cn("font-mono text-[10px] tabular-nums",n?"text-muted-foreground":"text-muted-foreground/70"),children:t})]})}const hL=S.memo(function({context:t="editor",onFieldSelect:n,inlineFilters:r}={}){var $e,ht,Et,Bt;const[s,o]=S.useState(""),[i,a]=S.useState("all"),l=S.useRef(null),[u,d]=S.useState(null),[f,h]=S.useState(!1),m=280,g=(be,Ne)=>(Be,gt)=>{if(!Be){d(Tn=>Tn&&Tn.field.id===be.id?null:Tn);return}if(f){d(null);return}if(!gt||!l.current)return;const Lt=gt.getBoundingClientRect(),jt=l.current.getBoundingClientRect(),_n=Math.max(0,jt.bottom-m);d({field:be,fieldState:Ne,top:Math.min(Lt.top,_n),left:jt.right+12})},[b,x]=S.useState(!1),[y,w]=S.useState(null),[v,C]=S.useState("card"),[N,k]=S.useState("metric"),[_,j]=S.useState(null),[I,E]=S.useState(!1);p.useEditorStore(be=>be.isDevMode);const T=p.useEditorStore(be=>be.card.dataSource),D=p.useEditorStore(be=>be.card.config),A=p.useEditorStore(be=>be.card),P=p.useEditorStore(be=>be.frame),R=p.useEditorStore(be=>be.actions.updateCardConfig),H=p.useEditorStore(be=>be.actions.updateCard),z=p.useEditorStore(be=>be.actions.updateFrame),U=p.useDashboardStore(be=>be.isVisualEditing),W=p.useDashboardStore(be=>be.selectedSheetId),O=p.useDashboardStore(be=>be.actions.updateSheetCalculatedFields),Z=p.useDashboardStore(be=>be.actions.updateDashboardCalculatedFields),M=p.useDashboardStore(be=>{var Ne;return be.visualEditPendingDashboardCalculatedFields??((Ne=be.dashboard)==null?void 0:Ne.calculatedFields)})??BXe,{userContext:K}=zi(),{autoJoinMetadata:L}=pk(A),{rawColumnGroups:$,scopedFields:B,filterableFields:V,dashboardFilterableFields:F,inlineFilterableFields:q,scopedCalculatedFields:G,sharedCalculatedFields:X,inlineCalculatedFields:J,isLoading:fe,error:ue}=Cie(),pe=(T==null?void 0:T.mode)==="semanticDomain"?T.semanticDomainId:void 0,{data:ye}=Z5(pe),ie=S.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]);(ht=($e=D==null?void 0:D.joinPlan)==null?void 0:$e.baseEntity)==null||ht.name,(Bt=(Et=L==null?void 0:L.resolvedJoinPlan)==null?void 0:Et.baseEntity)==null||Bt.name,Mie();const ae=t==="editor"?G:t==="filter"||t==="document-filter"?X:J,se=t==="editor"?ae.filter(be=>p.getCalculatedFieldNamespace(be)==="root"):ae,Ie=se.length>0,oe=(K==null?void 0:K.type)==="organization",me=t==="editor"?V||B:t==="filter"||t==="document-filter"?F:q,we=$,ge=s.toLowerCase(),re=(D==null?void 0:D.metricColumns)||[],ne=(D==null?void 0:D.groupByColumns)||[],he=(D==null?void 0:D.sortByColumns)||[],ee=A.calculatedFields||[],Ce=be=>be.name.toLowerCase().includes(ge)||be.label&&be.label.toLowerCase().includes(ge)||be.dataType.toLowerCase().includes(ge)||be.description&&be.description.toLowerCase().includes(ge)||be.qualifiedEntityName&&be.qualifiedEntityName.toLowerCase().includes(ge),ve=S.useCallback(be=>(be.label||be.name).toLowerCase().trim(),[]),te=S.useCallback((be,Ne)=>ve(be).localeCompare(ve(Ne),void 0,{numeric:!0,sensitivity:"base"}),[ve]),_e=me.filter(Ce).sort(te),De=S.useCallback(be=>t==="editor"?Tg(be):la(be),[t]),Fe=be=>{if(De(be))return"calculated";if(be.dataType==="number"||be.dataType==="integer"||be.dataType==="float"||be.dataType==="decimal"||be.dataType==="currency")return"metrics";const Ne=p.getDataType(be.dataType);return["date","string","boolean"].includes(Ne)?"dimensions":Ne==="number"?"metrics":"dimensions"},Ye=be=>{const Ne=be.filter(Ce);return i==="all"?Ne:Ne.filter(Be=>Fe(Be)===i)},ze=i==="all"?_e:_e.filter(be=>Fe(be)===i),Ve=Ie?Ye(se).sort(te):[],Ke=S.useCallback(be=>De(be)&&(t!=="editor"||p.getCalculatedFieldNamespace(be)==="root"),[t,De]),ke=me.filter(be=>!Ke(be)),Pe=Ye(ke).sort(te).reduce((be,Ne)=>{const Be=Ne.qualifiedEntityName||"Other Fields";return be[Be]||(be[Be]={label:p.toLabel(Ne.entityName),fields:[]}),be[Be].fields.push(Ne),be},{}),He=S.useMemo(()=>Object.entries(Pe).map(([be,Ne])=>{const Be=we.find(Lt=>Lt.entityName===be)||{entityName:be,label:Ne.label},gt=be===p.CALCULATED_FIELDS_GROUP_NAME?"Domain Calculated Fields":Be.label||Be.entityName;return{groupName:be,groupLabel:gt,fields:[...Ne.fields].sort(te)}}).sort((be,Ne)=>be.groupLabel.localeCompare(Ne.groupLabel,void 0,{numeric:!0,sensitivity:"base"})),[Pe,we,te]),nt=be=>be.id||`${be.entityName}-${be.qualifiedEntityName}-${be.name}-${be.role||"field"}`,Me=S.useMemo(()=>{const be=new Map;return me.forEach(Be=>{be.set(nt(Be),TP(Be,{joinabilityMap:(ye==null?void 0:ye.joinabilityMap)||null,selectedFields:ie,cardConfig:D,autoJoinMetadata:L,datasetAliases:ye==null?void 0:ye.datasets}))}),be},[me,ye==null?void 0:ye.joinabilityMap,ye==null?void 0:ye.datasets,ie,D,L]),Ee=i==="calculated"&&oe&&t==="editor"&&se.length===0,We=Ve.length>0?[{key:"scope-calculated",label:"Calculated Fields",fields:Ve}]:Ee?[{key:"scope-calculated",label:"Calculated Fields",fields:[]}]:[],yt=[...We.map(be=>be.key),...He.map(be=>be.groupName)],ft=_e.filter(be=>Fe(be)==="dimensions").length,Nt=_e.filter(be=>Fe(be)==="metrics").length,lt=_e.filter(be=>Fe(be)==="calculated").length,Pt=_e.length>0&&t!=="inline-filter"&&t!=="document-filter",Te=t==="inline-filter"||t==="document-filter"?"w-full":"w-[290px]";if(fe)return c.jsx("div",{className:p.cn("flex h-full flex-col items-center justify-center py-8",Te),children:c.jsx(Du,{size:"md",color:"muted","aria-label":"Loading data"})});if(ue)return c.jsxs("div",{className:p.cn("flex h-full flex-col items-center justify-center py-8",Te),children:[c.jsx(Mi,{className:"mb-4 h-12 w-12 text-red-300"}),c.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),c.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:ue.message||"Failed to load column data"})]});if(!T||!T.selectedEntities||T.selectedEntities.length===0)return c.jsxs("div",{className:p.cn("flex flex-col items-center justify-center py-8 text-center",Te),children:[c.jsx(Mi,{className:"mb-4 h-12 w-12 text-gray-300"}),c.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),c.jsx("p",{className:"px-4 text-xs text-gray-400",children:t==="filter"||t==="inline-filter"||t==="document-filter"?"Configure a data source for this card to see available fields":"Select a table, view, or dataset from the data source panel to see available fields"})]});const Ze=t==="inline-filter"||t==="document-filter"?"pb-3":"pb-2",Je=t==="inline-filter"||t==="document-filter"?"overflow-hidden":"",st=be=>OXe(be,{storedCalculatedFields:ee,metricFields:re,groupByFields:ne}),pt=be=>p.resolveLocalCalculatedFieldScope({field:be,sheetFields:(P==null?void 0:P.calculatedFields)||[],dashboardFields:M}),Rt=(be,Ne)=>{H(A.id,{calculatedFields:p.removeCalculatedField(ee,be,Ne)})},Mt=be=>{var Ne;return(Ne=P==null?void 0:P.calculatedFields)==null?void 0:Ne.find(Be=>p.matchesCalculatedField(Be,be))},cn=be=>M.find(Ne=>p.matchesCalculatedField(Ne,be,{allowComparableFallback:!0})),Le=(be,Ne)=>{if(be.role==="metric"){R(A.id,{metricColumns:p.removeCalculatedField(re,be,Ne)});return}be.role==="groupby"&&R(A.id,{groupByColumns:p.removeCalculatedField(ne,be,Ne)})},Ue=be=>{Z(p.removeCalculatedField(M,be,{allowComparableFallback:!0}))},ot=be=>{if(!P)return;const Ne=p.removeCalculatedField(P.calculatedFields||[],be);Ad({nextSharedFields:Ne,currentSharedFields:P.calculatedFields||[],isVisualEditing:U,selectedSheetId:W,updateFrame:z,updateSheetCalculatedFields:O})},kt=be=>{if(!oe)return;if(d(null),be.fieldScope==="domain"){tt.error("Domain calculated fields are read-only in this explorer.");return}const Ne=pt(be);if(Ne.scope==="sheet"){const gt=Ne.matchedField||Mt(be);if(!gt)return;w(gt),C("sheet"),k(gt.role==="metric"?"metric":"dimension"),x(!0);return}if(Ne.scope==="dashboard"){const gt=Ne.matchedField||cn(be);if(!gt)return;w(gt),C("dashboard"),k(gt.role==="metric"?"metric":"dimension"),x(!0);return}const Be=st(be);Be&&(w(Be),C("card"),k(Be.role==="metric"?"metric":"dimension"),x(!0))},St=async be=>{if(!oe)return;if(be.fieldScope==="domain"){tt.error("Domain calculated fields are read-only in this explorer.");return}const Ne=pt(be),Be={allowComparableFallback:Ne.scope!=="card"};if(Ne.scope==="sheet"){ot(Ne.matchedField||be),Le(be,Be);return}if(Ne.scope==="dashboard"){Ue(Ne.matchedField||be),Le(be,Be);return}Le(be,Be),Rt(be,Be)},it=async()=>{if(_){E(!0);try{await St(_),j(null)}catch{}finally{E(!1)}}},ce=be=>{if(!oe)return null;const Ne=be.fieldScope==="domain",Be=Ne;return c.jsxs(po,{onOpenChange:gt=>{h(gt),gt&&d(null)},children:[c.jsx(go,{asChild:!0,children:c.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:c.jsx(da,{className:"h-3 w-3"})})}),c.jsx(Ks,{align:"end",className:"w-36",children:Ne?c.jsx(bn,{disabled:!0,children:"Read-only"}):c.jsxs(c.Fragment,{children:[c.jsx(bn,{onClick:()=>kt(be),children:"Edit"}),c.jsx(bn,{className:"text-destructive focus:text-destructive",disabled:Be,onClick:()=>j(be),children:"Delete"})]})})]})};return c.jsxs(c.Fragment,{children:[c.jsxs("div",{ref:l,className:p.cn("relative flex h-full w-full grow flex-col",Ze,Je),children:[c.jsxs("div",{className:"flex-shrink-0 space-y-2 px-4 pt-2",children:[me.length>0&&c.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:[c.jsx(Xs,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),c.jsx("input",{type:"text",placeholder:"Search fields",value:s,onChange:be=>o(be.target.value),className:"h-full w-full bg-transparent text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none"}),s&&c.jsx("button",{type:"button","aria-label":"Clear search",onClick:()=>o(""),className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-control text-muted-foreground hover:bg-muted hover:text-foreground",children:c.jsx(p.X,{className:"h-3 w-3"})})]}),Pt&&c.jsxs("div",{className:"-mx-4 flex items-center gap-4 border-b border-border px-4",children:[c.jsx(dS,{label:"All",count:_e.length,active:i==="all",onClick:()=>a("all")}),c.jsx(dS,{label:"Dim",count:ft,active:i==="dimensions",onClick:()=>a(be=>be==="dimensions"?"all":"dimensions"),ariaLabel:"Dimensions"}),c.jsx(dS,{label:"Metric",count:Nt,active:i==="metrics",onClick:()=>a(be=>be==="metrics"?"all":"metrics"),ariaLabel:"Metrics"}),c.jsx(dS,{label:"Calc",count:lt,active:i==="calculated",onClick:()=>a(be=>be==="calculated"?"all":"calculated"),ariaLabel:"Calculated"})]})]}),c.jsxs(bl,{className:"min-h-0 flex-1 [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:w-full",children:[c.jsxs(oL,{type:"multiple",defaultValue:yt,className:"space-y-2",children:[We.map(be=>c.jsxs($y,{value:be.key,className:"border-none",children:[c.jsxs(zy,{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:[c.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[c.jsx("span",{className:"max-w-[180px] truncate text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:be.label}),c.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:be.fields.length})]}),t==="editor"&&oe&&c.jsx("span",{role:"button",tabIndex:0,"aria-label":"Add calculated field",title:"Add calculated field",onClick:Ne=>{Ne.stopPropagation(),w(null),C("card"),k("dimension"),x(!0)},onKeyDown:Ne=>{(Ne.key==="Enter"||Ne.key===" ")&&(Ne.preventDefault(),Ne.stopPropagation(),w(null),C("card"),k("dimension"),x(!0))},className:"inline-flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center rounded-[3px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:c.jsx(wr,{className:"h-3 w-3"})})]}),c.jsx(By,{className:"pb-1",children:c.jsxs("div",{children:[be.fields.length===0&&Ee&&c.jsx("p",{className:"px-4 py-2 text-[11px] text-muted-foreground",children:"No calculated fields yet — click + to add."}),be.fields.map(Ne=>{const Be=Me.get(nt(Ne)),gt=t==="editor"&&oe&&la(Ne);return c.jsx(F9,{field:Ne,context:t,fieldState:Be,onFieldSelect:n,inlineFilters:t==="inline-filter"||t==="document-filter"?r:void 0,actions:gt?ce(Ne):void 0,onHover:g(Ne,Be)},Ne.id)})]})})]},be.key)),He.map(({groupName:be,groupLabel:Ne,fields:Be})=>c.jsxs($y,{value:be,className:"border-none",children:[c.jsx(zy,{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:c.jsxs("div",{title:Ne,className:"flex min-w-0 flex-1 items-center gap-1.5",children:[c.jsx("span",{className:"max-w-[180px] truncate text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:Ne}),c.jsx("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground/70",children:Be.length})]})}),c.jsx(By,{className:"pb-2",children:c.jsx("div",{className:"space-y-1",children:Be.map(gt=>{const Lt=Me.get(nt(gt)),jt=t==="editor"&&oe&&la(gt);return c.jsx(F9,{field:gt,context:t,fieldState:Lt,onFieldSelect:n,inlineFilters:t==="inline-filter"||t==="document-filter"?r:void 0,actions:jt?ce(gt):void 0,onHover:g(gt,Lt)},gt.id)})})})]},be))]}),me.length===0&&c.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[c.jsx("p",{children:"No fields found for selected data source"}),c.jsx("p",{className:"mt-1 text-xs text-gray-400",children:t==="filter"?"The selected data source has no available fields":"Try selecting different data sources"})]}),me.length>0&&ze.length===0&&!Ee&&c.jsx("div",{className:"py-4 text-center text-[11px] text-muted-foreground",children:"No fields found for this category"}),c.jsx(p.ScrollBar,{orientation:"vertical"})]})]}),u&&c.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:c.jsx(CZe,{field:u.field,fieldState:u.fieldState})}),c.jsx(dh,{open:!!_,onOpenChange:be=>{be||j(null)},children:c.jsxs(Uu,{children:[c.jsxs(qu,{children:[c.jsx(Yu,{children:"Delete calculated field?"}),c.jsxs(Gu,{children:["This will remove"," ",c.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."]})]}),c.jsxs(Wu,{children:[c.jsx(Zu,{disabled:I,children:"Cancel"}),c.jsx(Ku,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",disabled:I,onClick:be=>{be.preventDefault(),it()},children:I?"Deleting...":"Delete"})]})]})}),c.jsx(Qie,{open:b,onOpenChange:be=>{x(be),be||(w(null),C("card"))},availableFields:B,existingField:y??void 0,existingFieldScope:v,initialFieldType:N,onSave:be=>{const Ne=y,Be=v==="dashboard"?M:(P==null?void 0:P.calculatedFields)||[];if(be.role==="metric"){const{nextActiveFields:Tn,nextSortByFields:Sr,nextStoredFields:Uo,nextSharedFields:So}=wA({activeFields:re,sortByFields:he,storedFields:ee,sharedFields:Be,updatedField:be,editingField:Ne,previousScope:v});(Tn||Sr)&&R(A.id,{...Tn?{metricColumns:Tn}:{},...Sr?{sortByColumns:Sr}:{}}),H(A.id,{calculatedFields:Uo}),v==="dashboard"&&So!==Be?Z(So):P&&So!==Be&&Ad({nextSharedFields:So,currentSharedFields:Be,isVisualEditing:U,selectedSheetId:W,updateFrame:z,updateSheetCalculatedFields:O});return}const{nextActiveFields:gt,nextSortByFields:Lt,nextStoredFields:jt,nextSharedFields:_n}=wA({activeFields:ne,sortByFields:he,storedFields:ee,sharedFields:Be,updatedField:be,editingField:Ne,previousScope:v});(gt||Lt)&&R(A.id,{...gt?{groupByColumns:gt}:{},...Lt?{sortByColumns:Lt}:{}}),H(A.id,{calculatedFields:jt}),v==="dashboard"&&_n!==Be?Z(_n):P&&_n!==Be&&Ad({nextSharedFields:_n,currentSharedFields:Be,isVisualEditing:U,selectedSheetId:W,updateFrame:z,updateSheetCalculatedFields:O})},onSaveToSheet:be=>{const Ne=y,Be=(P==null?void 0:P.calculatedFields)||[];if(be.role==="metric"){const{nextActiveFields:Sr,nextSortByFields:Uo,nextStoredFields:So,nextSheetFields:wl,nextDashboardFields:Oe}=SA({activeFields:re,sortByFields:he,storedFields:ee,sheetFields:Be,dashboardFields:M,updatedField:be,editingField:Ne,previousScope:v});P&&Ad({nextSharedFields:wl,currentSharedFields:Be,isVisualEditing:U,selectedSheetId:W,updateFrame:z,updateSheetCalculatedFields:O}),Oe&&Oe!==M&&Z(Oe),(Sr||Uo)&&R(A.id,{...Sr?{metricColumns:Sr}:{},...Uo?{sortByColumns:Uo}:{}}),H(A.id,{calculatedFields:So});return}const{nextActiveFields:gt,nextSortByFields:Lt,nextStoredFields:jt,nextSheetFields:_n,nextDashboardFields:Tn}=SA({activeFields:ne,sortByFields:he,storedFields:ee,sheetFields:Be,dashboardFields:M,updatedField:be,editingField:Ne,previousScope:v});P&&Ad({nextSharedFields:_n,currentSharedFields:Be,isVisualEditing:U,selectedSheetId:W,updateFrame:z,updateSheetCalculatedFields:O}),Tn&&Tn!==M&&Z(Tn),(gt||Lt)&&R(A.id,{...gt?{groupByColumns:gt}:{},...Lt?{sortByColumns:Lt}:{}}),H(A.id,{calculatedFields:jt})},onSaveToDashboard:be=>{const Ne=y,Be=be.role==="metric"?re:ne,gt=(P==null?void 0:P.calculatedFields)||[],{nextActiveFields:Lt,nextSortByFields:jt,nextStoredFields:_n,nextSharedFields:Tn,nextSheetFields:Sr}=Jie({activeFields:Be,sortByFields:he,storedFields:ee,sharedFields:M,sheetFields:gt,updatedField:be,editingField:Ne,previousScope:v});Z(Tn),P&&Sr&&Sr!==gt&&Ad({nextSharedFields:Sr,currentSharedFields:gt,isVisualEditing:U,selectedSheetId:W,updateFrame:z,updateSheetCalculatedFields:O}),(Lt||jt)&&R(A.id,{...Lt?{[be.role==="metric"?"metricColumns":"groupByColumns"]:Lt}:{},...jt?{sortByColumns:jt}:{}}),H(A.id,{calculatedFields:_n})},cardId:A.id})]})}),eae=S.memo(function({context:t,className:n,inlineFilters:r,onFieldSelect:s}){return c.jsx("div",{"data-content":"filterable-fields-panel",className:p.cn("flex min-h-0 grow flex-col overflow-hidden",n),children:c.jsx(yv,{collisionDetection:gv,children:c.jsx(vv,{items:[],strategy:U5,children:c.jsx(hL,{context:t,inlineFilters:r,onFieldSelect:s})})})})}),VXe=/{{\s*([A-Za-z_][A-Za-z0-9_]*)(?:\.([A-Za-z_][A-Za-z0-9_]*))?\s*}}/g,HXe=new Set(["generatedAt","pageNumber","pageCount"]),mL="document",UXe=/^(\d{4})-(\d{2})-(\d{2})$/;function qXe(e,t){const n=[],r=[];let s=0;for(const o of e.matchAll(VXe)){const i=o[0],a=o.index??0;a>s&&n.push({type:"text",value:e.slice(s,a),sourceStart:s,sourceEnd:a});const l=GXe({aliasOrKey:o[1],exportKey:o[2],inputs:t});l?n.push({type:"variable",ref:l,sourceStart:a,sourceEnd:a+i.length}):(n.push({type:"text",value:i,sourceStart:a,sourceEnd:a+i.length}),r.push(i)),s=a+i.length}return s<e.length&&n.push({type:"text",value:e.slice(s),sourceStart:s,sourceEnd:e.length}),{content:n,unresolvedTokens:r}}function WXe(e){return[...e.flatMap(n=>gL(n).map(r=>({label:`${n.variableName}.${r}`,token:`{{${n.variableName}.${r}}}`,ref:{source:"input",inputId:n.id,export:r}}))),{label:u1("generatedAt",e),token:IT("generatedAt",e),ref:{source:"documentMeta",key:"generatedAt"}},{label:u1("pageNumber",e),token:IT("pageNumber",e),ref:{source:"documentMeta",key:"pageNumber"}},{label:u1("pageCount",e),token:IT("pageCount",e),ref:{source:"documentMeta",key:"pageCount"}}]}function pL(e,t){if(e.source==="documentMeta")return u1(e.key,t);const n=t.find(r=>r.id===e.inputId);return`${(n==null?void 0:n.variableName)||e.inputId}.${e.export}`}function YXe({inputs:e,filterValuesByInputId:t,controlValuesByInputId:n,controlOptionsByInputId:r={},generatedAt:s,timezone:o,generatedAtFormat:i,pageNumber:a=1,pageCount:l=1}){const u={};for(const d of e)u[d.id]=d.kind==="filter"?ZXe(d,t[d.id],o):XXe(d,n[d.id],o,r[d.id]);return{inputs:e,resolvedInputsById:u,timezone:o,generatedAtFormat:i,meta:{generatedAt:s,pageNumber:a,pageCount:l}}}function tae(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:KXe(n.ref,t),...n.format?{format:n.format}:{}}))||[]}function GXe({aliasOrKey:e,exportKey:t,inputs:n}){if(e===mL&&t&&z9(t))return{source:"documentMeta",key:t};const r=n.find(s=>s.variableName===e);if(r){const s=t||JXe(r);return!nae(s)||!new Set(gL(r)).has(s)?null:{source:"input",inputId:r.id,export:s}}return!t&&z9(e)?{source:"documentMeta",key:e}:null}function KXe(e,t){var s;if(e.source==="documentMeta")return e.key==="generatedAt"?oae(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=(s=n==null?void 0:n.exports)==null?void 0:s[e.export];return r==null?"":String(r)}function ZXe(e,t,n){const r=(t==null?void 0:t.values)||[];if(p.getDataType(e.filter.dataType)==="date"){const a=r[0]?lN(r[0],n):"",l=r[1]?lN(r[1],n):"",u=a&&l?`${a} - ${l}`:a||l;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:l||null,range:u||null}}}const i=r.map(nQe).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 XXe(e,t,n,r=[]){const s=tQe(t),i=s.map(l=>e.control.type==="date"?lN(l,n):eQe(e.control,l,r)).join(", "),a=s.map(sae).join(", ");return{inputId:e.id,variableName:e.variableName,rawValue:t??null,displayValue:i,controlValue:t,exports:{label:i||null,value:a||null}}}function gL(e){const t=QXe(e),n=(e.exports||[]).filter(nae);return Array.from(new Set([...t,...n]))}function QXe(e){return e.kind==="filter"?p.getDataType(e.filter.dataType)==="date"?["label","start","end","range"]:["label","value"]:["label","value"]}function JXe(e){const t=gL(e);return t.includes("label")?"label":t.includes("range")?"range":t[0]||"value"}function nae(e){return e==="label"||e==="value"||e==="start"||e==="end"||e==="range"}function z9(e){return HXe.has(e)}function rae(e,t){return t.some(n=>n.variableName===e)}function IT(e,t){return rae(e,t)?`{{${mL}.${e}}}`:`{{${e}}}`}function u1(e,t){return rae(e,t)?`${mL}.${e}`:e}function eQe(e,t,n=[]){var o;const r=sae(t),s=n.find(i=>i.value===r);return s?s.label:e.source.kind==="manual"&&((o=e.source.options.find(i=>i.value===r))==null?void 0:o.label)||r}function tQe(e){return e==null?[]:Array.isArray(e)?e:[e]}function nQe(e){return e instanceof Date?lN(e):e==null?"":String(e)}function sae(e){return e instanceof Date?e.toISOString():e==null?"":String(e)}function lN(e,t){return e?oae(e,t,"MMM d, yyyy"):""}function oae(e,t,n){const r=sQe(n),s=rQe(e);if(s)return ln.format(s,r);const o=e instanceof Date?e:new Date(String(e));return Number.isNaN(o.getTime())?e==null?"":String(e):ln.formatInTimeZone(o,t||"UTC",r)}function rQe(e){if(typeof e!="string")return null;const t=UXe.exec(e.trim());if(!t)return null;const n=Number(t[1]),r=Number(t[2]),s=Number(t[3]),o=new Date(n,r-1,s);return o.getFullYear()!==n||o.getMonth()!==r-1||o.getDate()!==s?null:o}function sQe(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 Sv={text:"Text",table:"Table",chart:"Chart",spacer:"Spacer",page_break:"Page break"},iae=["text","table","spacer","page_break"];function Vy(e){return e==="table"?p.Table2:e==="text"?p.Type:e==="spacer"?Yme:e==="page_break"?qme:oi}function oQe(e){const t=`doc_section_${p.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 TT(e,t){if(e.type==="text"){const n=p.textContentToString(e.content,t).trim();return n?n.split(`
|
|
1225
1225
|
`)[0].slice(0,40):"Text"}return e.type==="table"?e.title||e.card.title||"Table":e.type==="spacer"?`Spacer (${e.heightPx}px)`:Sv[e.type]}function iQe(e,t){if(e.type==="spacer")return"Spacer";if(e.type==="text"){const n=p.textContentToString(e.content,t).trim();return n?n.split(`
|
|
1226
1226
|
`)[0].slice(0,28):"Text section"}return e.type==="table"?e.title||e.card.title||"Table":e.type==="page_break"?"Page break":Sv[e.type]}function aQe(e){return e.type==="spacer"?`${e.heightPx} px`:e.type==="table"?"Table":null}const yd=pu,vd=Ei,lQe={spacious:40,comfortable:36,standard:32,compact:28,dense:24};function bL(e){var t;return ZP((t=e.card.preferences)==null?void 0:t.tablePrefs)}function cQe(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 uQe=FJ;function CA(e){return lQe[e]}function dQe(e){return e.table.rowHeightPx??CA(bL(e).density)}function fQe(e){const t=new Set;return e.forEach(n=>{Object.keys(n).forEach(r=>t.add(r))}),Array.from(t)}function aae(e){var s;if(e.type!=="table"||e.card.type!=="table")return"";const t=e.card,n=t.config,r=t.dataSource;return JSON.stringify({type:t.type,connectionId:t.connectionId||(r==null?void 0:r.connectionId)||"",sql:((s=t.sql)==null?void 0:s.trim())||"",datamodelId:t.datamodelId||(r==null?void 0:r.datamodelId)||"",semanticDomainId:(r==null?void 0:r.semanticDomainId)||"",selectedEntities:(r==null?void 0:r.selectedEntities)||null,lastSelectedDatabase:t.lastSelectedDatabase||"",lastSelectedSchema:t.lastSelectedSchema||"",lastSelectedTable:t.lastSelectedTable||"",detailColumns:fS(n==null?void 0:n.detailColumns),groupByColumns:fS(n==null?void 0:n.groupByColumns),metricColumns:fS(n==null?void 0:n.metricColumns),pivotByColumns:fS(n==null?void 0:n.pivotByColumns)})}function fS(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 cl(e){return e.kind==="filter"}function el(e){return e.kind==="control"}function lae(e,t){return e.reduce((n,r)=>{if(!cl(r))return n;const s=p.buildFilterValueFromDefaults(r.filter,t);return s&&(n[r.id]=s),n},{})}function cae(e){return e.reduce((t,n)=>{if(!el(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 hQe(e){return e.map(t=>`${t.id}:${dae(t)}`).join("|")}function uae(e){return e.reduce((t,n)=>(t[n.id]=dae(n),t),{})}function dae(e){return el(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 mQe(e,t,n,r,s){const o={};for(const i of t){if(!cl(i))continue;const a=e[i.id],l=Cv(i.id,r,s),u=Hy(i,a),d=Object.prototype.hasOwnProperty.call(e,i.id);if(!l&&d&&!a){o[i.id]=void 0;continue}if(!l&&u){o[i.id]=u;continue}n[i.id]&&(o[i.id]=n[i.id])}return xQe(e,o)?e:o}function pQe(e,t,n,r,s){const o={};for(const i of t){if(!el(i))continue;if(!Cv(i.id,r,s)&&Object.prototype.hasOwnProperty.call(e,i.id)){o[i.id]=e[i.id];continue}Object.prototype.hasOwnProperty.call(n,i.id)&&(o[i.id]=n[i.id])}return yQe(e,o)?e:o}function xL(e,t){const n={...t,filterId:e.filter.id};return p.isCompatibleFilterValue(e.filter,n)?gQe(e).has(t.name):!1}function Hy(e,t){if(!(!t||!xL(e,t)))return t.filterId===e.filter.id?t:{...t,filterId:e.filter.id}}function gQe(e){return new Set([e.filter.column,...(e.filter.targetColumns||[]).map(t=>t.column)])}function bQe(e,t){const n=new Set(t.filter(s=>cl(s)&&X_(s.filter.operation)).map(s=>s.id)),r={};for(const[s,o]of Object.entries(e))n.has(s)&&(r[s]=o);return vQe(e,r)?e:r}function xQe(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>e[s]===t[s])}function yQe(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>Object.is(e[s],t[s]))}function vQe(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(s=>e[s]===t[s])}function X_(e){return e==="in"||e==="not in"}function fae(e){return e==="not in"?"exclude":"include"}function NA(e){return e==="exclude"?"not in":"in"}function wQe(e,t,n,r){return t.map(s=>{if(!cl(s))return;const o=e[s.id];if(!(!o||Cv(s.id,n,r)||!xL(s,o)))return Hy(s,o)}).filter(s=>!!s)}function SQe(e,t,n,r){return t.reduce((s,o)=>(!el(o)||Cv(o.id,n,r)||!Object.prototype.hasOwnProperty.call(e,o.id)||(s[o.control.id]=e[o.id]),s),{})}function hae(e,t,n,r,s){return e.filter(o=>o.requiredAtExecution?Cv(o.id,r,s)?!0:cl(o)?!t[o.id]||!xL(o,t[o.id]):!CQe(n,o.id):!1).map(o=>o.label)}function CQe(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 Cv(e,t,n){const r=n[e];return!!r&&r!==t[e]}const NQe=["table","pivotTable"];function kQe(e){return{id:`doc_editor_frame_${e.id}`,cards:[e.card],activeCardId:e.card.id}}function _Qe(e,t){return e.cards.find(n=>n.id===t)||null}function jQe(e){return NQe.includes(e.type)}function EQe(){const e=p.useDashboardStore(E=>E.dashboard),t=p.useEditorStore(E=>E.selectedConnectionId),n=p.useEditorStore(E=>E.selectedDatabaseName),r=p.useEditorStore(E=>E.selectedSchemaName),s=p.useEditorStore(E=>E.selectedTableName),o=p.useEditorStore(E=>E.selectedDatamodelId),{clearSelectedVisual:i}=ah(),{setIsDashboardEditing:a,setIsVisualEditing:l}=p.useDashboardActions(),{setFrame:u,setCard:d,setIsDevMode:f,initializeModeDrafts:h,setActiveTabCardId:m,updateDataSource:g,setQueryResultColumns:b,setFilterValues:x,setInlineFilterValuesMap:y,setApplyFilters:w,clearModeDrafts:v,setEditorContext:C}=p.useEditorActions(),N=p.useEditorStore(E=>E.actions.setSelectedConnectionId),k=p.useEditorStore(E=>E.actions.setSelectedDatamodelId),_=p.useEditorStore(E=>E.actions.setSelectedDatabaseName),j=p.useEditorStore(E=>E.actions.setSelectedSchemaName),I=p.useEditorStore(E=>E.actions.setSelectedTableName);return S.useCallback((E,T,D=[],A=[],P={},R=[])=>{const H=kQe(T);i(),v(),C({type:"documentSection",sheetId:E,sectionId:T.id,cardId:T.card.id,documentFilterValues:IQe(D),documentControlDefinitions:TQe(A),documentControlValues:{...P},missingRequiredInputLabels:[...R]}),gk({frame:H,card:T.card,setFrame:u,setCard:d,setIsDevMode:f,initializeModeDrafts:h,setActiveTabCardId:m,updateDataSource:g,setQueryResultColumns:b,setSelectedConnectionId:N,setSelectedDatabaseName:_,setSelectedSchemaName:j,setSelectedTableName:I,setSelectedDatamodelId:k,setFilterValues:x,setInlineFilterValuesMap:y,setApplyFilters:w,setIsDashboardEditing:a,setIsVisualEditing:l,dashboard:e,selectedSheetId:E,selectedFrameId:null,currentSelections:{connectionId:t,databaseName:n,schemaName:r,tableName:s,datamodelId:o}})},[v,i,e,h,t,n,o,r,s,m,w,d,C,x,u,y,a,f,l,b,N,_,k,j,I,g])}function IQe(e){return e.map(t=>({...t,values:[...t.values]}))}function TQe(e){return e.map(t=>({...t,source:t.source.kind==="manual"?{...t.source,options:t.source.options.map(n=>({...n}))}:{...t.source}}))}function DT({inputs:e,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,onOptionsChange:s}){return c.jsx(c.Fragment,{children:e.filter(el).map(o=>c.jsx(DQe,{input:o,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,onOptionsChange:s},o.id))})}function DQe({input:e,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,onOptionsChange:s}){const o=e.control,i=o.source.kind==="sql_query"?o.source:void 0,a=Cg({controlId:o.id,source:i,enabled:!!i,controlDefinitionsOverride:n,controlValuesOverride:r,activeFiltersOverride:t}),l=S.useMemo(()=>i?[]:O5(o),[o,i]),u=i?a.options:l;return S.useEffect(()=>{s(e.id,u)},[e.id,s,u]),null}function kA({children:e,className:t,empty:n,wrap:r=!1}){const s=S.Children.toArray(e).filter(o=>o!=null);return s.length===0?n??null:c.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:s})}function MT({children:e,className:t}){return c.jsx("div",{className:p.cn("shrink-0",t),children:e})}const d1=({dataType:e})=>QC(e),mae=["day","week","month","quarter","year"],MQe=[...mae,"hour","minute","second"],AQe=e=>/timestamp|datetime|time/i.test(e||""),yL=e=>AQe(e)?MQe:mae;function pae(e){const{controlId:t,onCommit:n}=e,[r,s]=S.useState(t);return c.jsx(p.Input,{size:"xs",value:r,onChange:o=>s(o.target.value),onBlur:()=>{n(r),s(o=>o.trim().length===0?t:o)}})}function B9(e){const{control:t,onChange:n}=e,r=p.ensureManualSource(t),s=r.source.kind==="manual"?r.source.options:[],i=!!p.getPresetOptionsForControlType(t.type),a=h=>{n({...r,source:{kind:"manual",options:h}})},l=()=>{const h=s.length+1,m=`Option ${h}`;a([...s,{label:m,value:p.slugifyControlValue(m)||`option_${h}`}])},u=(h,m)=>{a(s.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(s.map((g,b)=>b===h?{...g,value:m}:g))},f=h=>{a(s.filter((m,g)=>g!==h))};return c.jsxs("div",{className:"space-y-1.5",children:[c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Options"}),!i&&c.jsxs(p.Button,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:l,children:[c.jsx(wr,{className:"mr-1 h-3 w-3"}),"Add option"]})]}),s.length===0?c.jsx("div",{className:"rounded-md border border-dashed p-2.5 text-xs text-muted-foreground",children:"No options yet."}):c.jsxs("div",{className:"rounded-md border",children:[c.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:[c.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:"Label"}),c.jsx("span",{className:"text-[11px] font-medium text-muted-foreground",children:"Value"}),c.jsx("span",{})]}),s.map((h,m)=>c.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<s.length-1&&"border-b"),children:[c.jsx(p.Input,{size:"xs",value:h.label,placeholder:"Label",className:"h-7 text-xs",onChange:g=>u(m,g.target.value),disabled:i}),c.jsx(p.Input,{size:"xs",value:h.value,placeholder:"Value",className:"h-7 text-xs",onChange:g=>d(m,g.target.value),disabled:i}),c.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:c.jsx(rl,{className:"h-3.5 w-3.5"})})]},`${t.id}-option-${m}`))]})]})}function RQe(e){return c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Choices (built in)"}),c.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 FQe(e){return e?p.getDataType(e.dataType||"")==="date":!1}function PQe(e){return e!=null&&e.granularity?e.granularity:yL(e==null?void 0:e.dataType)[0]||"day"}function OQe(e,t){var n;return e!=null&&e.dateFormat?e.dateFormat:((n=Oy(t)[0])==null?void 0:n.value)||"YYYY-MM-DD"}function LQe(e){var N,k;const{control:t,choices:n,choiceLabel:r,emptyMessage:s,onChange:o}=e,i=p.ensureManualSource(t),a=i.source.kind==="manual"?i.source.options:[],l=new Map(a.map(_=>[_.value,_])),u=new Set(a.map(_=>_.value)),[d,f]=S.useState(""),[h,m]=S.useState(((N=a[0])==null?void 0:N.value)||null),g=_=>{o({...i,source:{kind:"manual",options:_}})},b=(_,j)=>{g(a.map(I=>I.value===_?j(I):I))},x=n.filter(({option:_})=>u.has(_.value)),y=h&&a.some(_=>_.value===h)?h:((k=a[0])==null?void 0:k.value)||null,w=x.find(({option:_})=>_.value===y)||x[0],v=n.filter(({option:_})=>{var I,E;if(u.has(_.value))return!1;const j=d.trim().toLowerCase();return j?_.label.toLowerCase().includes(j)||_.value.toLowerCase().includes(j)||((E=(I=_.presentation)==null?void 0:I.customFormat)==null?void 0:E.toLowerCase().includes(j)):!0}),C=(_,j)=>{var R,H,z;const I=l.get(_.value),E=j?p.getDataType(j.dataType||""):void 0,T=FQe(j),D=T?((R=I==null?void 0:I.presentation)==null?void 0:R.granularity)??PQe(j):void 0,A=T&&D?((H=I==null?void 0:I.presentation)==null?void 0:H.dateFormat)??OQe(j,D):void 0,P=T&&D?Oy(D):[];return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs("p",{className:"text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Editing selected ",r.slice(0,-1).toLowerCase()]}),c.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c.jsx("div",{className:"shrink-0",children:c.jsx(d1,{dataType:(j==null?void 0:j.dataType)||"string"})}),c.jsx("span",{className:"text-sm font-medium text-foreground/90",children:(I==null?void 0:I.label)??_.label}),E?c.jsx(rs,{variant:"outline",className:"text-[11px]",children:E}):null,"aggregate"in(j||{})&&typeof(j==null?void 0:j.aggregate)=="string"?c.jsx(rs,{variant:"secondary",className:"text-[11px]",children:j.aggregate}):null]}),j!=null&&j.qualifiedFieldName?c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:j.qualifiedFieldName}):null]}),c.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx(p.Label,{className:"text-[11px] text-muted-foreground",children:"Shown as"}),c.jsx(p.Input,{size:"xs",value:(I==null?void 0:I.label)??_.label,onChange:U=>b(_.value,W=>({...W,label:U.target.value}))})]}),T&&D?c.jsxs("div",{className:"space-y-1",children:[c.jsx(p.Label,{className:"text-[11px] text-muted-foreground",children:"Granularity"}),c.jsxs(p.Select,{value:D,onValueChange:U=>{var Z;const W=U,O=((Z=Oy(W)[0])==null?void 0:Z.value)||"YYYY-MM-DD";b(_.value,Y=>{var M,K;return{...Y,presentation:{...Y.presentation,granularity:W,dateFormat:O,customFormat:((M=Y.presentation)==null?void 0:M.dateFormat)==="custom"?(K=Y.presentation)==null?void 0:K.customFormat:void 0}}})},children:[c.jsx(p.SelectTrigger,{size:"xs",children:c.jsx(p.SelectValue,{})}),c.jsx(p.SelectContent,{children:yL(j.dataType).map(U=>c.jsx(p.SelectItem,{value:U,children:U.charAt(0).toUpperCase()+U.slice(1)},U))})]})]}):null,T&&D?c.jsx("div",{className:"space-y-1 md:col-span-2",children:c.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsx(p.Label,{className:"text-[11px] text-muted-foreground",children:"Date format"}),c.jsxs(p.Select,{value:A,onValueChange:U=>b(_.value,W=>{var O;return{...W,presentation:{...W.presentation,granularity:D,dateFormat:U,customFormat:U==="custom"?((O=W.presentation)==null?void 0:O.customFormat)||"":void 0}}}),children:[c.jsx(p.SelectTrigger,{size:"xs",children:c.jsx(p.SelectValue,{})}),c.jsx(p.SelectContent,{children:P.map(U=>c.jsx(p.SelectItem,{value:U.value,children:U.label},U.value))})]})]}),A==="custom"?c.jsxs("div",{className:"space-y-1",children:[c.jsx(p.Label,{className:"text-[11px] text-muted-foreground",children:"Custom format"}),c.jsx(p.Input,{size:"xs",value:((z=I==null?void 0:I.presentation)==null?void 0:z.customFormat)||"",placeholder:"MMM YYYY",onChange:U=>b(_.value,W=>({...W,presentation:{...W.presentation,granularity:D,dateFormat:"custom",customFormat:U.target.value}}))})]}):null]})}):null]})]})};return c.jsxs("div",{className:"grid gap-4 md:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]",children:[c.jsxs("div",{className:"flex min-h-0 flex-col gap-3 rounded-lg border bg-muted/10 p-3",children:[c.jsxs("div",{className:"space-y-1",children:[c.jsxs(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Add ",r.toLowerCase()]}),c.jsxs("div",{className:"relative",children:[c.jsx(Xs,{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"}),c.jsx(p.Input,{size:"xs",value:d,name:`${t.id}-search-${r.toLowerCase()}`,placeholder:`Search ${r.toLowerCase()}…`,autoComplete:"off",onChange:_=>f(_.target.value),className:"pl-9 pr-9"}),d?c.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:c.jsx(p.X,{className:"h-3.5 w-3.5"})}):null]})]}),n.length===0?c.jsx("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:s}):v.length===0?c.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.`}):c.jsx("div",{className:"h-[320px] overflow-y-auto pr-1",children:c.jsx("div",{className:"space-y-1",children:v.map(({option:_,target:j})=>{const I=j?p.getDataType(j.dataType||""):void 0;return c.jsxs("button",{type:"button",className:"group/container flex w-full items-center gap-3 rounded-lg border border-transparent px-2 py-2 text-left transition-all hover:bg-muted",onClick:()=>{g([...a,{..._}]),m(_.value),f("")},children:[c.jsx("div",{className:"shrink-0",children:c.jsx(d1,{dataType:(j==null?void 0:j.dataType)||"string"})}),c.jsxs("div",{className:"min-w-0 flex-1 overflow-hidden",children:[c.jsx("div",{className:"truncate text-sm text-foreground/85 group-hover/container:text-foreground",children:(j==null?void 0:j.label)||_.label}),j!=null&&j.qualifiedFieldName?c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:j.qualifiedFieldName}):null]}),c.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[I?c.jsx(rs,{variant:"outline",className:"text-[11px]",children:I}):null,c.jsx(rs,{variant:"secondary",className:"text-[11px]",children:"Add"})]})]},`${t.id}-available-${_.value}`)})})})]}),c.jsxs("div",{className:"flex min-h-0 flex-col gap-3 rounded-lg border bg-card p-3",children:[c.jsxs("div",{className:"flex items-center justify-between gap-3",children:[c.jsxs(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:["Selected ",r.toLowerCase()]}),c.jsx(rs,{variant:"secondary",className:"text-[11px]",children:x.length})]}),x.length===0?c.jsx("div",{className:"rounded-md border border-dashed p-3 text-xs text-muted-foreground",children:"Choose at least one option from the catalog."}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"max-h-[220px] overflow-y-auto pr-1",children:c.jsx("div",{className:"space-y-1",children:x.map(({option:_,target:j})=>{const I=l.get(_.value),E=j?p.getDataType(j.dataType||""):void 0,T=(w==null?void 0:w.option.value)===_.value;return c.jsxs("div",{className:p.cn("flex items-center gap-2 rounded-lg border p-2 transition-colors",T?"border-foreground/20 bg-muted/40":"border-transparent hover:bg-muted/20"),children:[c.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-3 text-left",onClick:()=>m(_.value),children:[c.jsx("div",{className:"shrink-0",children:c.jsx(d1,{dataType:(j==null?void 0:j.dataType)||"string"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:"truncate text-sm font-medium text-foreground/90",children:(I==null?void 0:I.label)??_.label}),j!=null&&j.qualifiedFieldName?c.jsx("div",{className:"truncate text-xs text-muted-foreground",children:j.qualifiedFieldName}):null]})]}),c.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[E?c.jsx(rs,{variant:"outline",className:"text-[11px]",children:E}):null,c.jsx(p.Button,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7","aria-label":`Remove ${(I==null?void 0:I.label)??_.label}`,onClick:()=>{var A;const D=a.filter(P=>P.value!==_.value);g(D),y===_.value&&m(((A=D[0])==null?void 0:A.value)||null)},children:c.jsx(p.X,{className:"h-3.5 w-3.5"})})]})]},`${t.id}-selected-${_.value}`)})})}),c.jsx("div",{className:"rounded-lg border bg-muted/5 p-3",children:w?C(w.option,w.target):c.jsx("div",{className:"text-xs text-muted-foreground",children:"Select a field to configure how it appears in the control."})})]})]})]})}function gae(e){if(e.participants.length===0)return null;const t=new Set(e.selectedCardIds);return c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Cards using this shared control"}),c.jsx("div",{className:"space-y-2 rounded-md border p-3",children:e.participants.map(n=>c.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[c.jsx(En,{checked:t.has(n.cardId),onCheckedChange:r=>{if(r===!0){e.onChange([...e.selectedCardIds,n.cardId]);return}e.onChange(e.selectedCardIds.filter(s=>s!==n.cardId))}}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"font-medium",children:n.title}),c.jsxs("div",{className:"text-xs text-muted-foreground",children:[n.choiceCount," ",e.type==="field_selector"?"compatible group-by fields":"compatible metrics"]})]})]},n.cardId))})]})}function $Qe(e){const t=e.value===!0?"true":"false";return c.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[c.jsx(p.Button,{type:"button",variant:t==="true"?"default":"outline",onClick:()=>e.onChange(!0),children:"On"}),c.jsx(p.Button,{type:"button",variant:t==="false"?"default":"outline",onClick:()=>e.onChange(!1),children:"Off"})]})}function zQe(e){return e.scope==="dashboard"&&(e.type==="enum"||e.type==="multi_enum")}const bae={kind:"sql_query",connectionId:"",sql:"",valueColumn:""};function V9(e){return{kind:"manual",options:e.options.map(t=>({...t,...t.presentation?{presentation:{...t.presentation}}:{}}))}}function H9(e){return{...e}}function BQe(e){return e.source.kind==="sql_query"?e.source:bae}function xae(e){const t=vL(e);return JSON.stringify({controlId:e.controlId,source:yoe(e.source),controlDefinitions:voe(t.controlDefinitions),controlValues:xoe(t.controlValues,t.controlDefinitions),activeFilters:e.activeFiltersOverride??null})}function vL(e){const t=goe(e.previewControlDefinitions),n={...e.previewControlValues||{}};delete n[e.controlId];const r=boe(n,t);return{controlDefinitions:t,controlValues:r}}function VQe(e){const[t,n]=S.useState(null),r=S.useRef(e);return S.useEffect(()=>{r.current!==e&&(r.current=e,n(null))},[e]),{requestedForCurrentKey:t===e,markCurrentKeyRequested:()=>n(e)}}function HQe(e){var v;const{control:t,onChange:n,previewControlDefinitions:r,previewControlValues:s,activeFiltersOverride:o}=e,i=BQe(t),{connections:a,isPending:l}=Cc(),u=t.id||"preview",d=i.connectionId.trim().length>0&&i.sql.trim().length>0&&i.valueColumn.trim().length>0,f=vL({controlId:u,previewControlDefinitions:r,previewControlValues:s}),h=xae({controlId:u,source:i,previewControlDefinitions:r,previewControlValues:s,activeFiltersOverride:o}),{requestedForCurrentKey:m,markCurrentKeyRequested:g}=VQe(h),b=Cg({controlId:u,source:d?i:void 0,enabled:m&&d,controlDefinitionsOverride:f.controlDefinitions,controlValuesOverride:f.controlValues,activeFiltersOverride:o}),x=C=>{const N={...i,...C,kind:"sql_query"};(!N.labelColumn||N.labelColumn.trim().length===0)&&delete N.labelColumn,n({...t,source:N})},y=p.getRequestErrorMessage(b.error,""),w=b.options;return S.useEffect(()=>{var k;if(i.connectionId||a.length!==1)return;const C=(k=a[0])==null?void 0:k.id;if(!C)return;const N={...i,kind:"sql_query",connectionId:C};(!N.labelColumn||N.labelColumn.trim().length===0)&&delete N.labelColumn,n({...t,source:N})},[a,t,i,n]),c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Connection"}),c.jsxs(p.Select,{value:i.connectionId,onValueChange:C=>{x({connectionId:C})},disabled:l||a.length===0,children:[c.jsx(p.SelectTrigger,{size:"xs",children:c.jsx(p.SelectValue,{placeholder:l?"Loading connections…":a.length===0?"No connections available":"Select a connection"})}),c.jsx(p.SelectContent,{children:a.map(C=>c.jsx(p.SelectItem,{value:C.id,children:C.name},C.id))})]})]}),i.connectionId.trim().length===0?c.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:[c.jsx("p",{className:"text-[13px] font-medium text-foreground",children:"Pick a connection above"}),c.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Then write your SQL query to source options."})]}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL"}),c.jsx("div",{className:"h-24 w-full overflow-hidden rounded-control border border-input",onKeyDown:C=>C.stopPropagation(),children:c.jsx(p.CodeEditor,{value:i.sql,onValueChange:C=>x({sql:C}),language:"sql-jinja",embedded:!0,hideLineNumbers:!0,dense:!0,ariaLabel:"Control options SQL query",placeholder:"SELECT id, name FROM segments WHERE account_id = [[param.tenantId]]"})})]}),c.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Value column"}),c.jsx(p.Input,{size:"xs",value:i.valueColumn,placeholder:"id",onChange:C=>{x({valueColumn:C.target.value})}})]}),c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label column (optional)"}),c.jsx(p.Input,{size:"xs",value:i.labelColumn||"",placeholder:"name",onChange:C=>{x({labelColumn:C.target.value})}})]})]}),c.jsxs("div",{className:"flex items-center gap-2",children:[c.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?c.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[w.length," option",w.length===1?"":"s",(v=b.metadata)!=null&&v.truncated?" (truncated)":""]}):null]}),m&&b.isError?c.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Preview unavailable",y?` — ${y}`:""]}):null]})]})}function UQe(e){const{control:t,onChange:n,controlLifecycle:r="edit"}=e,s=t.source.kind==="sql_query"?"sql_query":"manual",o=S.useRef(t.source.kind==="manual"?V9(t.source):null),i=S.useRef(t.source.kind==="manual"?t.requiredAtExecution:null),a=S.useRef(t.source.kind==="sql_query"?H9(t.source):null);t.source.kind==="manual"?(o.current=V9(t.source),i.current=t.requiredAtExecution):t.source.kind==="sql_query"&&(a.current=H9(t.source));const l=u=>{if(u!==s){if(u==="manual"){n({...t,source:o.current||{kind:"manual",options:[]},requiredAtExecution:i.current??t.requiredAtExecution});return}n({...t,source:a.current||bae,requiredAtExecution:t.initialValueStrategy==="embed_required"?!0:r==="create"?!1:t.requiredAtExecution})}};return c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Option source"}),c.jsxs(ma,{value:s,onValueChange:u=>l(u),className:"flex flex-col gap-1.5",children:[c.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[c.jsx(ps,{value:"manual",className:"mt-0.5"}),c.jsxs("span",{children:[c.jsx("span",{className:"font-medium text-foreground",children:"Manual"}),c.jsx("span",{className:"ml-1 text-muted-foreground",children:"— enter label/value rows"})]})]}),c.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[c.jsx(ps,{value:"sql_query",className:"mt-0.5"}),c.jsxs("span",{children:[c.jsx("span",{className:"font-medium text-foreground",children:"SQL query"}),c.jsx("span",{className:"ml-1 text-muted-foreground",children:"— resolve options from a database query at runtime"})]})]})]})]})}function yae(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 c.jsx(RQe,{options:t});if(n.type==="field_selector"||n.type==="metric_selector"){const s=n.type==="field_selector"?"Fields":"Metrics",o=n.type==="field_selector"?"No valid group-by fields are available yet. Add fields to the card first.":"No valid metrics are available yet. Add metrics to the card first.";return c.jsx(LQe,{control:n,choices:r,choiceLabel:s,emptyMessage:o,onChange:e.onChange})}return p.needsManualOptions(n)?zQe(n)?c.jsxs("div",{className:"space-y-3",children:[c.jsx(UQe,{control:n,onChange:e.onChange,controlLifecycle:e.controlLifecycle}),n.source.kind==="sql_query"?c.jsx(HQe,{control:n,onChange:e.onChange,previewControlDefinitions:e.previewControlDefinitions,previewControlValues:e.previewControlValues,activeFiltersOverride:e.activeFiltersOverride}):c.jsx(B9,{control:n,onChange:e.onChange})]}):c.jsx(B9,{control:n,onChange:e.onChange}):null}function vae(e){const{control:t,value:n,onChange:r,allowNoDefault:s=!1,allowCardDefault:o=!1,hint:i}=e;if(t.source.kind==="sql_query")return c.jsx(WQe,{control:t,value:n,onChange:r,allowNoDefault:s,allowCardDefault:o,hint:i,previewControlDefinitions:e.previewControlDefinitions,previewControlValues:e.previewControlValues,activeFiltersOverride:e.activeFiltersOverride});const a=p.ensureManualSource(t),l=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 c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default"}),t.type==="boolean"?c.jsx($Qe,{value:l,onChange:r}):f&&d.length>0?c.jsx(wae,{controlType:t.type,options:d,value:l,onChange:r,allowNoDefault:s,allowCardDefault:o}):f?c.jsx(p.Input,{size:"xs",value:"",placeholder:"Add choices first",disabled:!0,readOnly:!0}):c.jsx(p.Input,{size:"xs",value:Array.isArray(l)?l.join(", "):String(l??""),placeholder:t.type==="multi_enum"?"value_one, value_two":"Default value",onChange:h=>r(p.parseControlDefaultValue(a,h.target.value))}),i?c.jsx("p",{className:"text-[11px] text-muted-foreground",children:i}):null]})}function wae(e){const{controlType:t,options:n,value:r,onChange:s,allowNoDefault:o=!1,allowCardDefault:i=!1}=e,a=i&&p.supportsCardDefaultValue(t),l=r===void 0&&o?p.CONTROL_SELECT_UI_VALUES.noDefault:r===nr.CONTROL_CARD_DEFAULT_VALUE&&a?p.CONTROL_SELECT_UI_VALUES.cardDefault:typeof r=="string"?p.findControlSelectOptionUiValue(n,r):void 0;return c.jsxs(p.Select,{value:l,onValueChange:u=>{if(u===p.CONTROL_SELECT_UI_VALUES.noDefault){s(void 0);return}if(u===p.CONTROL_SELECT_UI_VALUES.cardDefault){s(nr.CONTROL_CARD_DEFAULT_VALUE);return}const d=p.getControlSelectOptionFromUiValue(n,u);d&&s(d.value)},children:[c.jsx(p.SelectTrigger,{size:"xs",children:c.jsx(p.SelectValue,{placeholder:"Choose a default"})}),c.jsxs(p.SelectContent,{children:[o?c.jsx(p.SelectItem,{value:p.CONTROL_SELECT_UI_VALUES.noDefault,children:"No default"}):null,a?c.jsx(p.SelectItem,{value:p.CONTROL_SELECT_UI_VALUES.cardDefault,children:"Card default"}):null,n.map((u,d)=>c.jsx(p.SelectItem,{value:p.getControlSelectOptionUiValue(d),children:u.label},u.value))]})]})}function qQe(e){var a;const{options:t,value:n,onChange:r,allowNoDefault:s=!1}=e,o=p.normalizeControlStringArrayValue(n),i=o.length===0?s?"No default":"Choose defaults":o.length===1?((a=t.find(l=>l.value===o[0]))==null?void 0:a.label)||o[0]:`${o.length} selected`;return c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs(p.Popover,{children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsx(p.Button,{type:"button",variant:"outline",className:"w-full justify-between",children:c.jsx("span",{className:"truncate",children:i})})}),c.jsx(p.PopoverContent,{align:"start",className:"w-64",children:c.jsx("div",{className:"space-y-2",children:t.map(l=>{const u=o.includes(l.value);return c.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[c.jsx(En,{checked:u,onCheckedChange:d=>{const f=d?[...o,l.value]:o.filter(h=>h!==l.value);r(f.length>0?f:void 0)}}),c.jsx("span",{children:l.label})]},l.value)})})})]}),s&&o.length>0?c.jsx(p.Button,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground",onClick:()=>r(void 0),children:"Clear"}):null]})}function WQe(e){const{control:t,value:n,onChange:r,allowNoDefault:s=!1,allowCardDefault:o=!1,hint:i,previewControlDefinitions:a,previewControlValues:l,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=vL({controlId:f,previewControlDefinitions:a,previewControlValues:l});xae({controlId:f,source:d,previewControlDefinitions:a,previewControlValues:l,activeFiltersOverride:u});const g=Cg({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(C=>({value:C.value,label:C.label})),y=t.type==="multi_enum"?p.normalizeControlStringArrayValue(n):p.getDefaultValueForType(t,n),w=(()=>{const C=[...x],N=new Set(C.map(_=>_.value)),k=_=>{typeof _!="string"||_.length===0||N.has(_)||(N.add(_),C.push({value:_,label:_}))};return Array.isArray(y)?y.forEach(k):k(y),C})(),v=b&&w.length>0;return c.jsxs("div",{className:"space-y-1.5",children:[c.jsx(p.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Default"}),v&&t.type==="multi_enum"?c.jsx(qQe,{options:w,value:y,onChange:r,allowNoDefault:s}):v?c.jsx(wae,{controlType:t.type,options:w,value:y,onChange:r,allowNoDefault:s,allowCardDefault:o}):c.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?c.jsx("p",{className:"text-[11px] text-muted-foreground",children:i}):null]})}function YQe(e){const{control:t,onChange:n}=e;return c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"space-y-1",children:c.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[c.jsx(En,{checked:t.hidden===!0,onCheckedChange:r=>n({...t,hidden:r===!0})}),"Hide control UI from viewers"]})}),c.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[c.jsx(En,{checked:t.locked===!0,onCheckedChange:r=>n({...t,locked:r===!0})}),"Locked"]})]})}function Sae(e){const t=Ay(e);return e.scope==="dashboard"?t==="advanced"?"More controls":"dashboard toolbar":t==="advanced"?"More options":"card header"}function GQe(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(dv(n));for(const s of r)t.has(s)&&t.set(s,(t.get(s)||0)+1)}return Object.fromEntries((e.controls||[]).map(n=>{if(n.hidden)return[n.id,{tone:"default",status:"Hidden from viewers",helper:"This control can still be used by connected cards, but it will not appear in the dashboard UI."}];const r=t.get(n.id)||0,s=Sae(n);return r===0?[n.id,{tone:"warning",status:"Not used by any cards yet",helper:`This control is already available in the ${s}. Next: open a card's Controls and either bind this control or reference [[param.${n.id}]] in SQL.`}]:[n.id,{tone:"success",status:`Used in ${r} ${r===1?"card":"cards"}`,helper:`Available in the ${s}. ${r===1?"That card":"Those cards"} will respond when the value changes.`}]}))}function KQe(e){const t=new Set(dv(e.card));return Object.fromEntries(e.controls.map(n=>{var s;const r=Sae(n);return n.hidden?[n.id,{tone:"default",status:"Hidden from viewers",helper:"This control is available for runtime state but will not appear in this card UI."}]:t.has(n.id)?[n.id,{tone:"success",status:"Used by this card",helper:`Available in the ${r} for this card.`}]:[n.id,{tone:"warning",status:"Not used by this card yet",helper:(s=e.card)!=null&&s.sql?`Reference [[param.${n.id}]] in this card's SQL to make the card respond to it.`:"Choose what this control changes below to make this card respond to it."}]}))}function ZQe(e){let t=0,n=0,r=0;const s=[];for(const o of p.getDashboardCards(e.dashboard)){if(!new Set(dv(o)).has(e.controlId))continue;t+=1,s.push(o.title||o.id),Ere({sql:o.sql,controlBindings:o.controlBindings}).some(u=>u.controlId===e.controlId)&&(n+=1),(o.controlBindings||[]).some(u=>u.target!=="sql_param"&&u.controlId===e.controlId)&&(r+=1)}return{totalCards:t,sqlCards:n,configCards:r,cardTitles:s}}function Cae(e){var n;const t=new Map;for(const r of p.getDashboardCards(e))for(const s of r.controlBindings||[])s.target!=="config_field_selector"&&s.target!=="config_metric_selector"||(t.has(s.controlId)||t.set(s.controlId,new Set),(n=t.get(s.controlId))==null||n.add(r.id));return Object.fromEntries(Array.from(t.entries()).map(([r,s])=>[r,Array.from(s)]))}function XQe(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 QQe(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 JQe(e){const t=new Map;return e.flatMap(n=>XQe(n)).forEach(({cardId:n,target:r})=>{const s=QQe(r),o=t.get(s);if(!o){t.set(s,{key:s,cardIds:[n],target:r});return}o.cardIds.includes(n)||o.cardIds.push(n)}),Array.from(t.values())}function eJe(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 tJe(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 nJe(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,format:p.fromSemanticFormat(n.format)}}function Nae(e){const{tokenProps:t}=mt(),n=p.useDashboardStore(l=>l.authToken),r=S.useMemo(()=>JQe(e),[e]),s=Ap({queries:r.map(({key:l,target:u})=>({queryKey:["dashboard-structural-columns",l],queryFn:()=>p.getRequest(`${t.apiServiceUrl}/v1/columns`,(n==null?void 0:n.accessToken)||"",tJe(u)),enabled:!!(n!=null&&n.accessToken)&&eJe(u)}))}),o=s.some(l=>l.isPending&&l.fetchStatus==="fetching"),i=S.useMemo(()=>{const l=new Map;return s.forEach((u,d)=>{const f=r[d],h=f==null?void 0:f.target;if(!f||!h||!u.data)return;const m=[...(u.data.columns||[]).map(g=>nJe({target:h,column:g})),...u.data.calculatedFields||[]];f.cardIds.forEach(g=>{l.set(g,[...l.get(g)||[],...m])})}),l},[s,r]);return{participants:S.useMemo(()=>e.map(l=>{var b,x,y,w,v;const u=i.get(l.id)||[],d=((y=(x=(b=l.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(l),g=p.getMetricSelectorChoicesForCard(l);return{cardId:l.id,title:l.title||l.id,canBindStructuralControl:!!l.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=l.config)==null?void 0:w.groupByColumns)||[]).filter(C=>typeof C.id=="string").map(C=>[C.id,C])),metricTargetMap:h.choices.length>0?h.targetMap:Object.fromEntries((((v=l.config)==null?void 0:v.metricColumns)||[]).filter(C=>typeof C.id=="string").map(C=>[C.id,C]))}}),[e,i]),isLoading:o}}function kae({control:e,defaultValue:t,defaultPlacement:n,placementOptions:r,previewControlDefinitions:s,previewControlValues:o,availableFieldChoices:i=[],availableMetricChoices:a=[],structuralParticipantSelector:l,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,v=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 c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:v,children:[c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx(p.Label,{className:y,children:"Label"}),c.jsx(p.Input,{size:"xs",value:e.label,placeholder:"Control label",onChange:C=>g(N=>({...N,label:C.target.value}))})]}),w?c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx(p.Label,{className:y,children:"Variable name"}),c.jsx(pae,{controlId:e.id,onCommit:x},e.id)]}):null,f?c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx(p.Label,{className:y,children:"Show in"}),c.jsxs(p.Select,{value:e.placement||n,onValueChange:C=>g(N=>({...N,placement:C})),children:[c.jsx(p.SelectTrigger,{size:"xs",children:c.jsx(p.SelectValue,{})}),c.jsx(p.SelectContent,{children:r.map(C=>c.jsx(p.SelectItem,{value:C.value,children:C.label},C.value))})]})]}):null]}),l,c.jsx(yae,{control:e,availableFieldChoices:i,availableMetricChoices:a,previewControlDefinitions:s,previewControlValues:o,activeFiltersOverride:m,controlLifecycle:"edit",onChange:C=>g(()=>C)}),e.initialValueStrategy==="saved_default"&&c.jsx(vae,{control:e,value:t,allowNoDefault:!0,allowCardDefault:u,previewControlDefinitions:s,previewControlValues:o,activeFiltersOverride:m,onChange:b}),c.jsx("div",{className:"grid grid-cols-1 gap-2",children:c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx(p.Label,{className:y,children:"Initial value"}),c.jsxs(p.Select,{value:e.initialValueStrategy,onValueChange:C=>g(N=>({...N,initialValueStrategy:C})),children:[c.jsx(p.SelectTrigger,{size:"xs",children:c.jsx(p.SelectValue,{})}),c.jsx(p.SelectContent,{children:p.INITIAL_VALUE_STRATEGY_OPTIONS.map(C=>c.jsx(p.SelectItem,{value:C.value,children:C.label},C.value))})]})]})}),c.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[c.jsx(En,{checked:e.showLabel??!0,onCheckedChange:C=>g(N=>({...N,showLabel:C===!0}))}),"Show label in toolbar"]}),h?c.jsxs("label",{className:"flex items-center gap-2 text-[13px]",children:[c.jsx(En,{checked:e.hidden===!0,onCheckedChange:C=>g(N=>({...N,hidden:C===!0}))}),"Hide control UI from viewers"]}):null]})}function _ae({open:e,onOpenChange:t,trigger:n,title:r,subtitle:s,description:o,body:i,footer:a,onClose:l,useDialog:u=!1,deleteDialogOpen:d,onDeleteDialogOpenChange:f,deleteDescription:h,deleteDetails:m,onConfirmDelete:g}){const b=Sc("interactive"),x=c.jsx(rJe,{title:r,subtitle:s,onClose:l,titleAsDialogTitle:u});return c.jsxs(c.Fragment,{children:[u?c.jsxs(yo,{open:e,onOpenChange:t,children:[c.jsx(fY,{asChild:!0,children:n}),c.jsxs(Js,{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:[c.jsx(Bo,{className:"sr-only",children:o}),x,c.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i}),c.jsx("div",{className:"shrink-0 border-t border-border/60 px-4 py-2.5",children:a})]})]}):c.jsxs(p.Popover,{open:e,onOpenChange:t,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:n}),c.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,c.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i}),c.jsx("div",{className:"shrink-0 border-t border-border/60 px-4 py-2.5",children:a})]})]}),c.jsx(dh,{open:d,onOpenChange:f,children:c.jsxs(Uu,{style:b.controlStyle,children:[c.jsxs(qu,{children:[c.jsx(Yu,{children:"Delete control?"}),c.jsx(Gu,{children:h}),m]}),c.jsxs(Wu,{children:[c.jsx(Zu,{children:"Cancel"}),c.jsx(Ku,{onClick:g,children:"Delete control"})]})]})})]})}function rJe({title:e,subtitle:t,onClose:n,titleAsDialogTitle:r}){const s="truncate text-[13px] font-medium text-foreground",o=r?c.jsx(eo,{className:s,title:e,children:e}):c.jsx("span",{className:s,title:e,children:e});return c.jsxs("div",{className:"flex h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 px-3",children:[c.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[c.jsx(p.SlidersHorizontal,{"aria-hidden":!0,className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),o,c.jsx("span",{className:"shrink-0 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:t})]}),c.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:c.jsx(p.X,{className:"h-3.5 w-3.5"})})]})}function sJe({control:e}){const t=p.useDashboardStore(V=>V.dashboard),{setDashboardControlsModel:n}=p.useDashboardActions(),[r,s]=S.useState(!1),[o,i]=S.useState(!1),a=p.getPlacementOptionsForScope("dashboard"),l=p.getDefaultPlacement("dashboard"),{participants:u}=Nae(p.getDashboardCards(t)),d=Cae(t),f=S.useMemo(()=>d[e.id]||[],[d,e.id]),h=p.isStructuralSelectorControlType(e.type)?p.getEligibleParticipantsForStructuralControl(u,e.type):[],m=p.resolveAuthoringControlDefaultValue({control:e,defaultValues:t.defaultControlValues||{}}),g=S.useCallback(V=>({...V,source:V.source.kind==="manual"?{kind:"manual",options:V.source.options.map(F=>({...F,presentation:F.presentation?{...F.presentation}:void 0}))}:{...V.source}}),[]),b=S.useCallback(()=>({control:g(e),selectedCardIds:[...f],defaultValue:m}),[g,e,m,f]),[x,y]=S.useState(b),w=S.useRef(m),v=x.control,C=x.selectedCardIds,N=p.isStructuralSelectorControlType(v.type)?p.getCompatibleStructuralChoiceCatalog({controlType:v.type,participants:u,selectedCardIds:C}):{choices:[],fieldTargetMap:{},metricTargetMap:{}},k=v.type==="field_selector"?N.choices.map(V=>({option:V,target:N.fieldTargetMap[V.value]})):Array.from(new Map(u.flatMap(V=>V.fieldChoices.map(F=>{var q;return[F.value,{option:F,target:(q=V.fieldTargetMap)==null?void 0:q[F.value]}]}))).values()),_=v.type==="metric_selector"?N.choices.map(V=>({option:V,target:N.metricTargetMap[V.value]})):Array.from(new Map(u.flatMap(V=>V.metricChoices.map(F=>{var q;return[F.value,{option:F,target:(q=V.metricTargetMap)==null?void 0:q[F.value]}]}))).values()),j=S.useMemo(()=>(t.controls||[]).map(V=>V.id===e.id?v:V),[e.id,t.controls,v]),I=S.useMemo(()=>p.buildAuthoringPreviewControlValues({controls:j,defaultValues:t.defaultControlValues||{},overrides:[{controlId:e.id,value:void 0},{controlId:v.id,value:x.defaultValue}]}),[e.id,t.defaultControlValues,x.defaultValue,v.id,j]),E=S.useMemo(()=>ZQe({dashboard:t,controlId:e.id}),[t,e.id]),T=V=>{y(F=>{const q=V(F.control);F.control.source.kind==="manual"&&q.source.kind==="sql_query"&&(w.current=F.defaultValue);const G=F.defaultValue===void 0&&F.control.source.kind==="sql_query"&&q.source.kind==="manual"?w.current:F.defaultValue,X=p.getNextEditedControlDefaultValue({previousControl:F.control,nextControl:q,currentDefaultValue:G});return q.source.kind==="manual"&&(w.current=X),{...F,control:q,defaultValue:X}})},D=V=>{if(!p.isStructuralSelectorControlType(v.type))return;const F=p.getCompatibleStructuralChoiceCatalog({controlType:v.type,participants:u,selectedCardIds:V}),q=p.reconcileStructuralControlChoices({control:v,choices:F.choices});y(G=>({...G,selectedCardIds:V,control:q,defaultValue:p.getNextEditedControlDefaultValue({previousControl:G.control,nextControl:q,currentDefaultValue:G.defaultValue})}))},A=V=>{if(!V.trim())return;const F=d0(V);F!==e.id&&Pse(t,{source:"dashboardControl",controlId:e.id}).includes(F)||y(q=>q.control.id===F?q:{...q,control:{...q.control,id:F}})},P=()=>{w.current=m,y(b()),s(!1)},R=()=>{const V={...t.defaultControlValues||{}};delete V[e.id];let F=x.control,q;if(p.isStructuralSelectorControlType(F.type)){const J=p.getCompatibleStructuralChoiceCatalog({controlType:F.type,participants:u,selectedCardIds:x.selectedCardIds});F=p.reconcileStructuralControlChoices({control:F,choices:J.choices}),q=Object.fromEntries(f.filter(fe=>!x.selectedCardIds.includes(fe)).map(fe=>[fe,void 0])),x.selectedCardIds.length>0&&F.source.kind==="manual"&&F.source.options.length>0&&Object.assign(q,p.buildStructuralControlBindingsForParticipants({control:F,participants:u,selectedCardIds:x.selectedCardIds}))}!p.isStructuralSelectorControlType(F.type)&&p.isStructuralSelectorControlType(e.type)&&(q=Object.fromEntries(f.map(J=>[J,void 0]))),F.initialValueStrategy==="saved_default"&&x.defaultValue!==void 0&&(V[F.id]=x.defaultValue),F={...F,defaultValue:V[F.id]},F=p.syncSqlQueryControlExecutionRequirement(F,V[F.id]);const G=(t.controls||[]).map(J=>J.id===e.id?F:J),X={renamed:F.id!==e.id?{oldId:e.id,newId:F.id}:void 0,cardBindingsById:q,affectedBindingControlIds:p.isStructuralSelectorControlType(F.type)?[F.id]:p.isStructuralSelectorControlType(e.type)?[e.id]:void 0};n(G,V,X),s(!1)},H=()=>{const V=(t.controls||[]).filter(q=>q.id!==e.id),F={...t.defaultControlValues||{}};delete F[e.id],n(V,F,{removedControlId:e.id}),i(!1),s(!1)},z=E.totalCards===0?`Delete "${e.label}"?`:`This control is used by ${E.totalCards} ${E.totalCards===1?"card":"cards"}. Deleting it will remove bindings and replace SQL references with NULL on affected cards.`,U=E.cardTitles.slice(0,3).join(", "),W=E.cardTitles.length>3,O=p.isStructuralSelectorControlType(e.type),Z=V=>{if(V){y(b()),s(!0);return}P()},Y=c.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Control settings",onClick:V=>V.stopPropagation(),children:c.jsx(p0,{className:"h-3 w-3"})}),M=c.jsx(kae,{control:v,defaultValue:x.defaultValue,defaultPlacement:l,placementOptions:a,previewControlDefinitions:j,previewControlValues:I,availableFieldChoices:k,availableMetricChoices:_,allowCardDefault:!0,structuralParticipantSelector:p.isStructuralSelectorControlType(v.type)?c.jsx(gae,{type:v.type,participants:h.map(V=>({cardId:V.cardId,title:V.title,choiceCount:v.type==="field_selector"?V.fieldChoices.length:V.metricChoices.length})),selectedCardIds:C,onChange:D}):null,onChangeControl:T,onChangeDefaultValue:V=>{v.source.kind==="manual"&&(w.current=V),y(F=>({...F,defaultValue:V}))},onCommitControlId:A}),K=c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.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:()=>i(!0),children:[c.jsx(p.X,{className:"h-3.5 w-3.5"}),"Delete"]}),c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:P,children:"Cancel"}),c.jsx(p.Button,{type:"button",size:"xs",onClick:R,children:"Accept"})]})]}),L=v.label||"Control",$=p.getFriendlyTypeOption(v.type).label,B=E.totalCards>0?c.jsxs("div",{className:"space-y-1 text-sm text-muted-foreground",children:[c.jsxs("p",{children:["Affected cards: ",U,W?` +${E.cardTitles.length-3} more`:""]}),E.sqlCards>0?c.jsxs("p",{children:["SQL references on ",E.sqlCards," ",E.sqlCards===1?"card":"cards"," will be replaced with `NULL`."]}):null,E.configCards>0?c.jsxs("p",{children:["Config bindings on ",E.configCards," ",E.configCards===1?"card":"cards"," will be removed."]}):null]}):null;return c.jsx(_ae,{open:r,onOpenChange:Z,trigger:Y,title:L,subtitle:$,description:"Update how this control appears and behaves in the dashboard toolbar.",body:M,footer:K,onClose:P,useDialog:O,deleteDialogOpen:o,onDeleteDialogOpenChange:i,deleteDescription:z,deleteDetails:B,onConfirmDelete:H})}const oJe=24,iJe=/^\d{4}-\d{2}-\d{2}$/;function hS(e,t=oJe){return e.length<=t?e:`${e.slice(0,t-1)}…`}function aJe(e,t,n,r){if(t==null||t==="")return null;if(e.type==="date")try{if(typeof t=="string"&&iJe.test(t)){const[o,i,a]=t.split("-").map(Number);return ln.format(new Date(o,i-1,a),"MMM d, yyyy")}const s=t instanceof Date?t:new Date(t);return Number.isNaN(s.getTime())?null:ln.formatInTimeZone(s,n,"MMM d, yyyy")}catch{return null}return e.type==="multi_enum"&&Array.isArray(t)?t.length===0?null:t.length===1?hS(String(AT(e,t[0],r)??t[0])):`${t.length} selected`:e.type==="enum"||poe(e)?hS(String(AT(e,t,r)??t)):e.type==="boolean"?t?"On":"Off":hS(String(t))}function AT(e,t,n){const r=String(t);if(n!=null&&n.has(r))return n.get(r)??null;const s=e.source;if(!s)return null;if(s.kind==="manual"&&Array.isArray(s.options)){const a=s.options.find(l=>l.value===t);return(a==null?void 0:a.label)??null}const i=lJe(e,t).find(a=>a.value===t);return i?i.label:null}function lJe(e,t){const n=O5(e);return!(t===nr.CONTROL_CARD_DEFAULT_VALUE||e.defaultValue===nr.CONTROL_CARD_DEFAULT_VALUE)||n.some(s=>s.value===uA.value)?n:[uA,...n]}function cJe(e){return e.type==="date"?Qm:p.SlidersHorizontal}function uJe(e){return e.type==="date"?360:e.type==="multi_enum"?300:e.type==="number"?240:280}function jae({control:e,value:t,isEditing:n=!1,dragListeners:r,onChange:s,onUpdateControl:o,disabled:i=!1,controlDefinitionsOverride:a,controlValuesOverride:l,activeFiltersOverride:u,actions:d}){var I,E,T;const f=Sc("interactive"),[h,m]=S.useState(!1),{tokenProps:g}=mt(),b=((E=(I=g==null?void 0:g.params)==null?void 0:I.calendarContext)==null?void 0:E.tz)||((T=g==null?void 0:g.params)==null?void 0:T.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,x=fJe(e,t),y=Cg({controlId:e.id,source:x,enabled:x!==void 0,controlDefinitionsOverride:a,controlValuesOverride:l,activeFiltersOverride:u}),w=S.useMemo(()=>{if(y.options.length!==0)return new Map(y.options.map(D=>[D.value,D.label]))},[y.options]),v=aJe(e,t,b,w),C=v!==null,N=e.showLabel??!0,k=i||e.locked===!0,_=hJe(e,t,k),j=cJe(e);return c.jsxs("div",{className:"group/chip flex shrink-0 items-center gap-2",children:[n&&r&&c.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:c.jsx(yc,{className:"size-3"})}),c.jsxs(p.Popover,{open:h,onOpenChange:m,children:[c.jsxs("div",{className:p.cn("inline-flex h-7 items-stretch overflow-hidden rounded-control border border-border text-[12px] transition-colors",C?f.hasAppearance?"bg-accent/80 hover:bg-accent":"bg-muted/80 hover:bg-muted":f.hasAppearance?"bg-muted/40 hover:bg-accent/50":"bg-muted/40 hover:bg-muted/70"),style:f.chipStyle,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.jsxs("button",{type:"button","aria-label":C?`${e.label}: ${v}`:e.label,className:"inline-flex items-center gap-1.5 px-2 focus:outline-none",children:[c.jsx(j,{className:p.cn("h-3 w-3 shrink-0",C?"text-muted-foreground":"text-muted-foreground/70")}),N&&c.jsx("span",{className:"whitespace-nowrap text-muted-foreground",children:e.label}),C&&c.jsxs(c.Fragment,{children:[N&&c.jsx("span",{className:"text-border","aria-hidden":"true",children:"·"}),c.jsx("span",{className:"max-w-[160px] truncate whitespace-nowrap font-medium text-foreground",children:v})]}),c.jsx(p.ChevronDown,{className:"h-3 w-3 shrink-0 text-muted-foreground/60"})]})}),C&&_&&c.jsxs(c.Fragment,{children:[c.jsx("span",{"aria-hidden":"true",className:"w-px bg-border"}),c.jsx("button",{type:"button",onClick:D=>{D.preventDefault(),D.stopPropagation(),s(void 0)},"aria-label":`Clear ${e.label}`,className:"inline-flex w-6 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:c.jsx(p.X,{className:"h-3 w-3"})})]})]}),c.jsx(p.PopoverContent,{align:"start",sideOffset:4,style:{width:uJe(e),...f.contentStyle},className:p.cn(U9(e)||q9(e)?"p-1":"p-3"),onMouseDown:D=>D.stopPropagation(),onClick:D=>D.stopPropagation(),children:U9(e)?c.jsx(W9,{control:e,value:t,disabled:k,multi:!1,popoverOpen:h,controlDefinitionsOverride:a,controlValuesOverride:l,activeFiltersOverride:u,onChange:D=>{s(D),m(!1)}}):q9(e)?c.jsx(W9,{control:e,value:t,disabled:k,multi:!0,popoverOpen:h,controlDefinitionsOverride:a,controlValuesOverride:l,activeFiltersOverride:u,onChange:s}):c.jsx(dA,{control:e,value:t,onChange:s,showLabel:!1,disabled:k,controlDefinitionsOverride:a,controlValuesOverride:l,activeFiltersOverride:u})})]}),n&&c.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:c.jsx(sJe,{control:e})})]})}function U9(e){return e.type==="enum"&&(e.source.kind==="manual"||e.source.kind==="sql_query")}function q9(e){return e.type==="multi_enum"&&(e.source.kind==="manual"||e.source.kind==="sql_query")}function dJe(e){return e.source.kind==="manual"?e.source.options:[]}function W9({control:e,value:t,disabled:n,multi:r,popoverOpen:s,controlDefinitionsOverride:o,controlValuesOverride:i,activeFiltersOverride:a,onChange:l}){const u=e.source.kind==="sql_query",d=u?e.source:void 0,f=Cg({controlId:e.id,source:d,enabled:u&&s,controlDefinitionsOverride:o,controlValuesOverride:i,activeFiltersOverride:a}),h=S.useMemo(()=>{if(!u)return dJe(e);const m=f.options.map(y=>({value:y.value,label:y.label})),g=new Set(m.map(y=>y.value)),b=[],x=y=>{typeof y!="string"||y.length===0||g.has(y)||(g.add(y),b.push({value:y,label:y}))};if(Array.isArray(t))for(const y of t)x(y);else x(t);return[...m,...b]},[e,u,f.options,t]);return u&&f.isLoading&&h.length===0?c.jsx("p",{className:"px-2 py-2 text-[12px] text-muted-foreground",children:"Loading options…"}):u&&f.isError&&h.length===0?c.jsx("p",{className:"px-2 py-2 text-[12px] text-destructive",children:"Failed to load options"}):r?c.jsx(pJe,{control:e,options:h,value:t,disabled:n,onChange:l}):c.jsx(mJe,{control:e,options:h,value:t,disabled:n,onChange:l})}function fJe(e,t){if(e.source.kind==="sql_query"&&!(e.type!=="enum"&&e.type!=="multi_enum")&&Eae(t)&&!(Array.isArray(t)&&t.length!==1))return e.source}function Eae(e){return e!=null&&e!==""&&(!Array.isArray(e)||e.length>0)}function hJe(e,t,n){return!n&&!e.requiredAtExecution&&Eae(t)}function mJe({control:e,options:t,value:n,disabled:r,onChange:s}){return t.length===0?c.jsx("p",{className:"px-2 py-2 text-[12px] text-muted-foreground",children:"No options"}):c.jsx("div",{role:"radiogroup",className:"flex flex-col gap-0.5",children:t.map(o=>{const i=n===o.value;return c.jsxs("button",{type:"button",role:"radio","aria-checked":i,disabled:r,onClick:()=>{r||s(o.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:[c.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:c.jsx(p.Check,{className:"h-3 w-3",strokeWidth:3})}),c.jsx("span",{className:"truncate",children:o.label})]},String(o.value))})})}function pJe({control:e,options:t,value:n,disabled:r,onChange:s}){const o=Array.isArray(n)?n:n!=null?[n]:[],i=new Set(o.map(l=>String(l)));if(t.length===0)return c.jsx("p",{className:"px-2 py-2 text-[12px] text-muted-foreground",children:"No options"});const a=l=>{if(r)return;const u=String(l),d=i.has(u);if(d&&o.length===1&&e.requiredAtExecution)return;const f=d?o.filter(h=>String(h)!==u):[...o,l];if(f.length===0&&!e.requiredAtExecution){s(void 0);return}s(f)};return c.jsx("div",{role:"listbox","aria-multiselectable":!0,className:"flex flex-col gap-0.5",children:t.map(l=>{const u=i.has(String(l.value)),d=r||u&&o.length===1&&e.requiredAtExecution;return c.jsxs("button",{type:"button",role:"option","aria-selected":u,disabled:d,onClick:()=>a(l.value),className:p.cn("flex w-full items-center gap-2 rounded-control px-2 py-1.5 text-left text-[13px] transition-colors",d?"cursor-not-allowed opacity-50":u?"bg-muted text-foreground hover:bg-foreground/[0.08]":"text-foreground hover:bg-muted"),children:[c.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",u&&"border-primary bg-primary text-primary-foreground",d&&"opacity-60"),children:u?c.jsx(p.Check,{className:"h-3 w-3",strokeWidth:3}):null}),c.jsx("span",{className:"truncate",children:l.label})]},String(l.value))})})}function gJe({control:e,controls:t,reservedVariableNames:n=[],activeFiltersOverride:r,onUpdateControl:s,onRemoveControl:o}){const[i,a]=S.useState(!1),[l,u]=S.useState(!1),d=p.getPlacementOptionsForScope("dashboard"),f=p.getDefaultPlacement("dashboard"),h=S.useMemo(()=>xJe(t),[t]),m=p.resolveAuthoringControlDefaultValue({control:e,defaultValues:h}),g=S.useCallback(z=>({...z,source:z.source.kind==="manual"?{kind:"manual",options:z.source.options.map(U=>({...U,presentation:U.presentation?{...U.presentation}:void 0}))}:{...z.source}}),[]),b=S.useCallback(()=>({control:g(e),defaultValue:m}),[g,e,m]),[x,y]=S.useState(b),w=S.useRef(m),v=x.control,C=S.useMemo(()=>t.map(z=>z.id===e.id?v:z),[e.id,t,v]),N=S.useMemo(()=>p.buildAuthoringPreviewControlValues({controls:C,defaultValues:h,overrides:[{controlId:e.id,value:void 0},{controlId:v.id,value:x.defaultValue}]}),[e.id,h,x.defaultValue,v.id,C]),k=z=>{y(U=>{const W=z(U.control);U.control.source.kind==="manual"&&W.source.kind==="sql_query"&&(w.current=U.defaultValue);const O=U.defaultValue===void 0&&U.control.source.kind==="sql_query"&&W.source.kind==="manual"?w.current:U.defaultValue,Z=p.getNextEditedControlDefaultValue({previousControl:U.control,nextControl:W,currentDefaultValue:O});return W.source.kind==="manual"&&(w.current=Z),{...U,control:W,defaultValue:Z}})},_=z=>{if(!z.trim())return;const U=d0(z);U!==e.id&&(n.includes(U)||t.some(W=>W.id===U&&W.id!==e.id))||y(W=>W.control.id===U?W:{...W,control:{...W.control,id:U}})},j=()=>{w.current=m,y(b()),a(!1)},I=()=>{if(!s){j();return}const z=v.initialValueStrategy==="saved_default"?x.defaultValue:void 0,U=p.syncSqlQueryControlExecutionRequirement({...v,defaultValue:z});s(bJe(U)),a(!1)},E=z=>{if(z){w.current=m,y(b()),a(!0);return}j()},T=()=>{o==null||o(),u(!1),a(!1)},D=v.label||"Control",A=p.getFriendlyTypeOption(v.type).label,P=c.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Control settings",onClick:z=>z.stopPropagation(),children:c.jsx(p0,{className:"h-3 w-3"})}),R=c.jsx(kae,{control:v,defaultValue:x.defaultValue,defaultPlacement:f,placementOptions:d,previewControlDefinitions:C,previewControlValues:N,allowControlIdEdit:!0,showPlacementSelect:!1,showViewerVisibilityToggle:!1,activeFiltersOverride:r,onChangeControl:k,onChangeDefaultValue:z=>{v.source.kind==="manual"&&(w.current=z),y(U=>({...U,defaultValue:z}))},onCommitControlId:_}),H=c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.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:[c.jsx(p.X,{className:"h-3.5 w-3.5"}),"Delete"]}),c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx(p.Button,{type:"button",variant:"outline",size:"xs",onClick:j,children:"Cancel"}),c.jsx(p.Button,{type:"button",size:"xs",onClick:I,children:"Accept"})]})]});return c.jsx(_ae,{open:i,onOpenChange:E,trigger:P,title:D,subtitle:A,description:"Update how this control appears and behaves in the document toolbar.",body:R,footer:H,onClose:j,deleteDialogOpen:l,onDeleteDialogOpenChange:u,deleteDescription:`Delete "${e.label}" from this document sheet?`,onConfirmDelete:T})}function bJe(e){const t={...e};return delete t.placement,delete t.hidden,t}function xJe(e){const t={};for(const n of e)n.defaultValue!==void 0&&(t[n.id]=n.defaultValue);return t}function Iae({className:e,inputs:t,filterValuesByInputId:n,filterModesByInputId:r,documentFilterValues:s,documentControlValues:o,onSetFilterValue:i,onSetFilterMode:a,onUpdateFilterInput:l,onUpdateControlInput:u,onRemoveFilterValue:d,onRemoveInput:f,controlValuesByInputId:h,onSetControlValue:m,actions:g,isEditing:b=!1}){const x=S.useMemo(()=>t.filter(el).map(C=>C.control),[t]),y=p.useDashboardStore(C=>{var N;return((N=C.dashboard.filterLayout)==null?void 0:N.toolbarWrap)??!1}),w=c.jsx("span",{className:"block shrink-0 text-[12px] text-muted-foreground",children:"None yet"}),v=t.map(C=>c.jsx(MT,{children:c.jsx(yJe,{input:C,filterValuesByInputId:n,filterModesByInputId:r,documentFilterValues:s,documentControlValues:o,documentControlDefinitions:x,onSetFilterValue:i,onSetFilterMode:a,onUpdateFilterInput:l,onUpdateControlInput:u,onRemoveFilterValue:d,onRemoveInput:f,reservedVariableNames:t.filter(N=>N.id!==C.id).map(N=>N.variableName),controlValuesByInputId:h,onSetControlValue:m,isEditing:b})},C.id));return c.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?c.jsxs(kA,{wrap:!0,className:"w-full gap-3 pr-0",children:[v.length>0?v:c.jsx(MT,{children:w}),g?c.jsx(MT,{children:g}):null]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"min-w-0 overflow-x-auto overflow-y-hidden",children:c.jsx(kA,{empty:w,children:v})}),g?c.jsx("div",{className:"shrink-0 justify-self-end",children:g}):null]})})}function yJe({input:e,filterValuesByInputId:t,filterModesByInputId:n,documentFilterValues:r,documentControlValues:s,documentControlDefinitions:o,onSetFilterValue:i,onSetFilterMode:a,onUpdateFilterInput:l,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]:s[e.control.id];return c.jsx(jae,{control:e.control,value:_,isEditing:b,onChange:j=>g(e.id,j),onUpdateControl:j=>u==null?void 0:u(e.id,j),controlDefinitionsOverride:o,controlValuesOverride:s,activeFiltersOverride:r,actions:b?c.jsx(gJe,{control:e.control,controls:o,reservedVariableNames:h,activeFiltersOverride:r,onUpdateControl:j=>u==null?void 0:u(e.id,j),onRemoveControl:()=>f==null?void 0:f(e.id)}):null})}const x=e,y=Hy(x,t[x.id]),w=y?[y]:[],v=n[x.id]||fae(x.filter.operation),C=X_(x.filter.operation)?{...x.filter,operation:NA(v)}:x.filter,N={filters:[],activeFilterValues:r,selectedSheetId:null,dashboardControls:o,controlValues:s};function k(_,j){const I={...x.filter,..._,operation:x.filter.operation};l==null||l(x.id,I,j)}return c.jsx(m5,{filter:C,isEditing:b,settingsVariant:"document",filterQueryContext:N,inputVariableName:x.variableName,reservedInputVariableNames:h,onUpdateFilter:k,onRemoveFilter:()=>f==null?void 0:f(x.id),storageOptions:{storageTarget:"card",cardId:`document-input-${x.id}`,inlineFilterValues:w,setInlineFilterValue:_=>i(x.id,_),removeInlineFilterValue:()=>d(x.id),setInlineFilterMode:(_,j)=>a(x.id,j),filterQueryContext:N}})}function vJe({sections:e,inputs:t,selectedSectionId:n,onSelectSection:r,onDeleteSection:s,onReorderSection:o,onInsertSection:i}){const[a,l]=S.useState(null),[u,d]=S.useState(!1);return c.jsxs("aside",{"data-testid":"document-outline",className:"flex w-64 shrink-0 flex-col border-r bg-background",children:[c.jsxs("div",{className:"flex h-10 items-center justify-between border-b px-3",children:[c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Sections"}),c.jsxs("span",{className:"font-mono text-[10px] tabular-nums text-muted-foreground",children:["· ",e.length]})]}),i?c.jsxs(p.Popover,{open:u,onOpenChange:d,children:[c.jsx(p.PopoverTrigger,{asChild:!0,children:c.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:[c.jsx(wr,{className:"h-3 w-3"}),"Add"]})}),c.jsx(p.PopoverContent,{align:"end",side:"bottom",sideOffset:6,className:"w-48 p-1",children:iae.map(f=>{const h=Vy(f);return c.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:[c.jsx(h,{className:"h-3.5 w-3.5 text-muted-foreground"}),Sv[f]]},f)})})]}):null]}),c.jsx("div",{className:"flex-1 overflow-y-auto py-1",children:e.length===0?c.jsx("p",{className:"px-3 py-3 text-[12px] text-muted-foreground",children:"No sections yet"}):e.map(f=>{const h=Vy(f.type),m=f.id===n,g=iQe(f,t),b=aQe(f);return c.jsxs("div",{"data-testid":`document-outline-section-${f.id}`,"data-selected":m?"true":void 0,draggable:!0,onDragStart:x=>{l(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(),v=x.clientY<w.top+w.height/2?"before":"after";o(y,f.id,v)}l(null)},onDragEnd:()=>l(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:[c.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:[c.jsx(yc,{className:"mt-0.5 h-3 w-3 shrink-0 cursor-grab text-muted-foreground/50"}),c.jsx(h,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("div",{className:p.cn("truncate text-[13px] leading-tight",m?"font-medium text-foreground":"text-foreground/90"),children:g}),b?c.jsx("div",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:b}):null]})]}),c.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:c.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(),s(f.id)},children:c.jsx(p.X,{className:"h-3 w-3"})})})]},f.id)})})]})}const RT=[];function wJe({card:e,queryOptions:t,surfaceMode:n,previewRowLimit:r,onPreviewRowLimitChange:s}){const{authToken:o,tokenProps:i}=mt(),a=p.useDashboardStore(ue=>ue.authToken),u=ip(e)?n==="print"?"export-full-with-cap":"preview-window":void 0,d=u?u==="preview-window"&&r||Kv(u):void 0,f=S.useMemo(()=>{if(u!=="preview-window")return"";const{paginationConfig:ue,...pe}=e;return JSON.stringify({card:pe,queryOptions:t,surfaceMode:n})},[e,u,t,n]),h=S.useRef(null),m=S.useMemo(()=>u&&d?{...e,paginationConfig:{page:1,pageSize:d}}:e,[e,d,u]),g=S.useMemo(()=>({...t,...u?{documentTableDataPolicy:u}:{}}),[u,t]),b=dc(m,g),x=!!u&&b.isFetching&&(b.isPlaceholderData||b.dataUpdatedAt===0),y=x?void 0:b.data,w=S.useMemo(()=>Array.isArray(y==null?void 0:y.records)?y.records:RT,[y==null?void 0:y.records]),v=h.current,C=u==="preview-window"&&b.isFetching&&!b.error&&!y&&(v==null?void 0:v.identity)===f,N=C?v.records:w,k=C?v.data:y,_=C?v.pagination:x?void 0:b.pagination,j=C?v.comparisonMetadata:x?void 0:b.comparisonMetadata,I=C?v.queryRequestPayload:x?void 0:b.queryRequestPayload,E=C?v.dataUpdatedAt:b.dataUpdatedAt;S.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 T=typeof(_==null?void 0:_.totalCount)=="number"?_.totalCount:void 0,D=!u||typeof(_==null?void 0:_.totalCount)=="number",A=u==="export-full-with-cap"&&T!==void 0&&T>rE,P=S.useMemo(()=>JSON.stringify(b.queryKey),[b.queryKey]),R=u&&d&&T!==void 0&&!A&&u==="export-full-with-cap"?Math.max(1,Math.ceil(T/d)):1,H=u&&d&&D&&R>1?Array.from({length:R-1},(ue,pe)=>pe+2):[],z=I,U=(o==null?void 0:o.accessToken)||(a==null?void 0:a.accessToken)||"",W=Ap({queries:H.map(ue=>({queryKey:["documentTableRows",P,E,ue,d,i.apiServiceUrl],enabled:!!(u&&d&&z&&U&&D&&!A),queryFn:async()=>{const pe={...z||{},pagination:{page:ue,pageSize:d}};return delete pe.tableTotalsRequest,p.postRequest(`${i.apiServiceUrl}/v1/query`,U,pe)}}))}),O=W.map(ue=>{var ye;const pe=Array.isArray((ye=ue.data)==null?void 0:ye.records)?ue.data.records.length:0;return`${ue.dataUpdatedAt}:${pe}`}).join("|"),Z=S.useMemo(()=>W.length===0?RT:W.flatMap(ue=>{var pe;return Array.isArray((pe=ue.data)==null?void 0:pe.records)?ue.data.records:RT}),[W.length,O]),Y=S.useMemo(()=>u?Z.length===0?N:[...N,...Z]:N,[Z,N,u]),M=W.map(ue=>{var pe,ye;return ue.error?{error:p.getRequestErrorMessage(ue.error,"Query failed",{preserveSyntheticMessage:!0}),sql:p.getRequestErrorSql(ue.error)||""}:(pe=ue.data)!=null&&pe.error?{error:p.getRequestErrorMessage(ue.data,"Query failed"),sql:p.getRequestErrorSql(ue.data)||(typeof((ye=ue.data)==null?void 0:ye.errorSql)=="string"?ue.data.errorSql:"")}:void 0}).find(Boolean),K=x&&!C?"":b.errorMessage,L=u&&I&&!b.isLoading&&!b.isPending&&!K&&!D?"Document table queries require backend pagination metadata.":"",$=A&&T!==void 0?`This table has ${T.toLocaleString()} rows. Paginated report export currently supports up to ${rE.toLocaleString()} rows. Add filters or reduce the result set before exporting.`:"",B=K||(M==null?void 0:M.error)||L||$,V=b.errorSql||(M==null?void 0:M.sql)||"",F=[u??"single-query",E,O,Y.length,T??"unknown",B].join(":"),q=W.some(ue=>ue.isFetching),G=W.some(ue=>ue.isLoading||ue.isPending),X=u==="export-full-with-cap"&&!B&&R>1&&Z.length+N.length<Math.min(T??0,rE),J=u==="preview-window"&&T!==void 0&&Y.length<T,fe=S.useCallback(()=>{u!=="preview-window"||!s||!d||s(Math.min(d+Kv("preview-window"),T??d+Kv("preview-window")))},[s,d,u,T]);return{data:k&&{...k,records:Y},records:Y,pagination:_,comparisonMetadata:j,queryRequestPayload:I,errorMessage:B,errorSql:V,isLoading:!C&&b.isLoading||G||X,isPending:!C&&b.isPending||G||X,isFetching:b.isFetching||q,isPreviewWindowIncomplete:J,loadedRowCount:Y.length,totalRowCount:T,rowDataVersion:F,loadMorePreviewRows:J&&s?fe:void 0}}function SJe(e){return zp(e)}function CJe(e){var s,o,i,a;if(!SJe(e)||!I0(e))return[];const t=(o=(s=e.preferences)==null?void 0:s.tablePrefs)==null?void 0:o.columnSettingsMap,n=(a=(i=e.preferences)==null?void 0:i.tablePrefs)==null?void 0:a.columnVisibility;let r=!1;return EF(e).flatMap(l=>n1e(l,n)?l.role!=="metric"&&!r?(r=!0,[M$(l,t)]):l.role==="metric"?[M$(l,t)]:[]:[])}function Tae(e){return s1e(e)}function NJe(e){return mK(e)}function kJe(e){return!!(e!=null&&e.columns.some(t=>t.behavior!=="label"))}function _Je(e){return o1e(e)}const jJe={mode:"table-print"},EJe={suppressSortControls:!0,renderPlainWrapper:!0,disableDashboardInteractions:!0};function IJe(e){return e.interactionConfig?{...e,interactionConfig:void 0}:e}function TJe(e){return Array.from(e.querySelectorAll("tbody tr, tfoot tr"))}function DJe({sectionElement:e,tableSurfaceElement:t,firstRowElement:n,lastRowElement:r,measurementScale:s}){const o=Number.isFinite(s)&&s>0?s:1,i=e.getBoundingClientRect(),a=t==null?void 0:t.getBoundingClientRect(),l=n.getBoundingClientRect(),u=r.getBoundingClientRect(),d=r.closest("table"),f=d?d.getBoundingClientRect().bottom:u.bottom,h=Math.max(0,(l.top-i.top)/o),m=Math.max(0,(Math.max(f,u.bottom)-u.bottom)/o),g=t?MJe({sectionRect:i,tableSurfaceElement:t,tableSurfaceRect:a,measurementScale:o}):void 0;return{chromeHeightPx:Math.ceil(h+m),trailingChromePx:Math.ceil(m),...g!==void 0?{renderedMinHeightPx:g}:{}}}function MJe({sectionRect:e,tableSurfaceElement:t,tableSurfaceRect:n,measurementScale:r}){const s=window.getComputedStyle(t),o=Number.parseFloat(s.minHeight||"0")||0;if(o<=0||!n)return;const i=Math.max(0,(n.top-e.top)/r);return Math.ceil(i+o)}function Y9(e){return e==null?void 0:e.closest('[data-testid="document-page"]')}function Dae(e){return e==null?void 0:e.querySelector('[data-document-region="footer"]')}function AJe(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 RJe(e,t){return e?Math.abs(e.rowHeightPx-t.rowHeightPx)>1||Math.abs((e.averageRowHeightPx??e.rowHeightPx)-(t.averageRowHeightPx??t.rowHeightPx))>1||FJe(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 FJe(e,t){return!e&&!t?!1:!e||!t||e.length!==t.length?!0:e.some((n,r)=>{const s=t[r];return n===void 0||s===void 0?n!==s:Math.abs(n-s)>1})}const G9=40,Q_=18,PJe=120;function cc({section:e,totalRowCount:t=0,layoutMeasurement:n}){var g;const r=$Je(e),s=r!=="unsupported",o=!!(e.card.connectionId||(g=e.card.dataSource)!=null&&g.connectionId),i=zJe(e,r),a=r==="table"?BJe(e):[],l=a.length>0?1:0,u=Math.max(0,t),d=OJe(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:s,hasConnection:o,hasRunnableQuery:i,isRunnable:s&&o&&i,totalRowCount:u,bodyRowCount:Math.max(0,u-l),trailingRowCount:l,visibleTotalsColumnIds:a,fallbackRowHeightPx:d,measuredRowHeightPx:f,measuredAverageRowHeightPx:h,measuredRowHeightsPx:m,effectiveRowHeightPx:Mae({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:EJe}}function OJe(e){return Math.max(G9,e.table.rowHeightPx??G9)}function Mae({fallbackRowHeightPx:e,measuredRowHeightPx:t,measuredRowHeightsPx:n,totalRowCount:r}){return n&&r!==void 0&&!LJe(n,r)?e:t!==void 0?Math.max(Q_,t):e}function LJe(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 $Je(e){return e.card.type==="table"||e.card.type==="pivotTable"?e.card.type:"unsupported"}function zJe(e,t){var n;return t==="unsupported"?!1:t==="pivotTable"?p.hasValidCardConfig(e.card.config):!!((n=e.card.sql)!=null&&n.trim()||p.hasValidCardConfig(e.card.config))}function BJe(e){return e.table.totalsRow?CJe(Tae(e.card)):[]}function J_({totalRowCount:e,fallbackRowHeightPx:t,layoutMeasurement:n}){const r=Math.max(0,e),s=Math.max(Q_,t),o=n==null?void 0:n.rowHeightsPx;if(!o||o.length===0){if((n==null?void 0:n.rowHeightPx)!==void 0){const d=cN(n.rowHeightPx)??s;return{kind:"uniform",totalRowCount:r,fallbackRowHeightPx:s,measuredRowHeightPx:d,measuredAverageRowHeightPx:n.averageRowHeightPx}}return{kind:"unmeasured",totalRowCount:r,fallbackRowHeightPx:s}}const i=Array.from({length:r},(d,f)=>cN(o[f])),a=i.filter(d=>d!==void 0);if(a.length===0)return{kind:"unmeasured",totalRowCount:r,fallbackRowHeightPx:s};const l=Math.max(...a),u=n.averageRowHeightPx??Math.ceil(a.reduce((d,f)=>d+f,0)/a.length);return YJe(i)?{kind:"complete",totalRowCount:r,fallbackRowHeightPx:s,measuredRowHeightPx:l,measuredAverageRowHeightPx:u,rowHeightsPx:i}:{kind:"sparse",totalRowCount:r,fallbackRowHeightPx:s,measuredRowHeightPx:l,measuredAverageRowHeightPx:u,rowHeightsPx:i}}function VJe(e,t){const{rowHeightsPx:n,rowRangeStartIndex:r,rowRangeEndIndex:s,totalRowCount:o}=t;if(!n||r===void 0||s===void 0||o===void 0)return PT(e,FT(t));const i=Math.max(0,o),a=Math.min(Math.max(0,r),i),l=Math.min(Math.max(a,s),i),u=l-a,d=FT({...t,rowRangeStartIndex:a,rowRangeEndIndex:l,totalRowCount:i});if(u===i||u!==n.length)return PT(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]=cN(m)}),PT(e,FT({...d,rowHeightsPx:h}))}function Aae(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 wL({rowMeasurementState:e,startIndex:t,endIndex:n}){let r=0;const s=Math.max(0,t),o=Math.min(Math.max(s,n),e.totalRowCount);for(let i=s;i<o;i+=1)r+=Aae(e,i);return r}function HJe({rowMeasurementState:e,startIndex:t,endIndex:n,chromeHeightPx:r,renderedMinHeightPx:s}){const o=wL({rowMeasurementState:e,startIndex:t,endIndex:n});return Math.max(r+o,Fae(s)??0)}function UJe({rowMeasurementState:e,startIndex:t,endIndex:n,chromeHeightPx:r}){return r+wL({rowMeasurementState:e,startIndex:t,endIndex:n})}function Rae({rowMeasurementState:e,startIndex:t,availableHeightPx:n}){if(!Number.isFinite(n)||n<=0)return 0;let r=0,s=Math.max(0,t);for(;s<e.totalRowCount;){const o=Aae(e,s);if(o<=0||r+o>n)break;r+=o,s+=1}return s-Math.max(0,t)}function qJe(e){return e.kind==="complete"||e.kind==="uniform"?e.measuredRowHeightPx:e.fallbackRowHeightPx}function WJe({tableSlice:e}){return!e||e.pageIndex===0}function FT(e){var o;const t=(o=e.rowHeightsPx)==null?void 0:o.map(i=>cN(i)),n=(t??[]).filter(i=>i!==void 0),r=n.length>0?Math.max(...n):Math.max(Q_,e.rowHeightPx),s=n.length>0?Math.ceil(n.reduce((i,a)=>i+a,0)/n.length):e.averageRowHeightPx;return{...e,rowHeightPx:r,averageRowHeightPx:s,rowHeightsPx:t,renderedMinHeightPx:Fae(e.renderedMinHeightPx),canUpdateLayoutChrome:e.canUpdateLayoutChrome}}function PT(e,t){return!e||t.canUpdateLayoutChrome===void 0||t.canUpdateLayoutChrome?t:{...t,chromeHeightPx:e.chromeHeightPx,renderedMinHeightPx:e.renderedMinHeightPx,rowsPerPage:e.rowsPerPage}}function Fae(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.ceil(e)}function cN(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.max(Q_,Math.ceil(e))}function YJe(e){return e.every(t=>t!==void 0)}const GJe={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%"},KJe=[],ZJe={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 XJe(e){const t=["full","outer"].includes(e.gridLines),n=t||e.gridLines==="top",r=t||e.gridLines==="right",s=t||e.gridLines==="bottom",o=t||e.gridLines==="left",i=["full","inner","horizontal"].includes(e.gridLines),a=["full","inner","vertical"].includes(e.gridLines);return 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",s?"border-b border-b-zinc-200":"border-b-0",o?"border-l border-l-zinc-200":"border-l-0","[&_.data-table-scroll-container]:!rounded-none [&_.data-table-scroll-container]:!border-0 [&_.data-table-scroll-container]:!bg-white","[&_table]:!bg-white","[&_tbody_td>div]:!text-[var(--document-table-cell-color)] [&_tbody_td]:!text-[var(--document-table-cell-color)]","[&_tbody_tr:hover]:!bg-white [&_tbody_tr]:h-[var(--document-table-row-height)] [&_tbody_tr]:!bg-white","[&_tfoot_td]:!bg-[var(--document-table-totals-bg)] [&_tfoot_td]:!text-[var(--document-table-totals-color)] [&_tfoot_td]:!font-[var(--document-table-totals-font-weight)]","[&_thead]:!bg-[var(--document-table-header-bg)] [&_thead_tr]:!bg-[var(--document-table-header-bg)]","[&_th]:!bg-[var(--document-table-header-bg)] [&_th]:!text-[var(--document-table-header-color)]",ZJe[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 QJe({section:e,documentFilterValues:t=[],documentControlDefinitions:n=[],documentControlValues:r={},documentDashboardInputValues:s,missingRequiredInputLabels:o=[],isEditing:i=!0,surfaceMode:a="preview",tableSlice:l,initialRowsPerPageLimit:u,previewRowLimit:d,showInlineEditAction:f=!0,onEditTableSection:h,onTableRowCountChange:m,onTableResultColumnsChange:g,onTableLayoutMeasure:b,onTableLayoutInvalidate:x,onUpdateTableSection:y,onPreviewRowLimitChange:w,measurementScale:v=1}){const C=cc({section:e});return C.isRunnable?o.length>0?c.jsx(Rd,{section:e,icon:c.jsx(Ai,{className:"h-4 w-4 text-amber-500"}),title:"Required inputs missing",message:`Set ${o.join(", ")} to run this table.`,exportState:"blocked",isEditing:i,showInlineEditAction:f,onEditTableSection:h}):c.jsx(I_,{displayPreferences:jJe,children:c.jsx(net,{section:e,documentFilterValues:t,documentControlDefinitions:n,documentControlValues:r,documentDashboardInputValues:s,isEditing:i,surfaceMode:a,tableSlice:l,initialRowsPerPageLimit:u,previewRowLimit:d,showInlineEditAction:f,onEditTableSection:h,onTableRowCountChange:m,onTableResultColumnsChange:g,onTableLayoutMeasure:b,onTableLayoutInvalidate:x,onUpdateTableSection:y,onPreviewRowLimitChange:w,measurementScale:v})}):c.jsx(cet,{section:e,isEditing:i,reason:C.isSupported?void 0:"Unsupported table type",showInlineEditAction:f,onEditTableSection:h})}const Pae=S.memo(QJe,JJe);Pae.displayName="DocumentTableSectionRenderer";function JJe(e,t){return e.section===t.section&&e.documentFilterValues===t.documentFilterValues&&e.documentControlDefinitions===t.documentControlDefinitions&&e.documentControlValues===t.documentControlValues&&e.documentDashboardInputValues===t.documentDashboardInputValues&&eet(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&&tet(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 eet(e,t){if(e===t)return!0;const n=e||[],r=t||[];return n.length===r.length&&n.every((s,o)=>s===r[o])}function tet(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 net({section:e,documentFilterValues:t=[],documentControlDefinitions:n=[],documentControlValues:r={},documentDashboardInputValues:s,isEditing:o=!0,surfaceMode:i="preview",tableSlice:a,initialRowsPerPageLimit:l,previewRowLimit:u,showInlineEditAction:d=!0,onEditTableSection:f,onTableRowCountChange:h,onTableResultColumnsChange:m,onTableLayoutMeasure:g,onTableLayoutInvalidate:b,onUpdateTableSection:x,onPreviewRowLimitChange:y,measurementScale:w=1}){var Ie,oe,me,we,ge,re,ne,he,ee;const v=S.useMemo(()=>e.card.type==="table"&&e.table.totalsRow?Tae(e.card):e.card,[e.card,e.table.totalsRow]),C=S.useMemo(()=>IJe(v),[v]),N=S.useMemo(()=>bL(e),[e]),k=S.useMemo(()=>e.card.type==="table"&&e.table.totalsRow?NJe(v):void 0,[v,e.card.type,e.table.totalsRow]),_=kJe(k),j=S.useMemo(()=>{const Ce=t.length>0,ve=n.length>0||Object.keys(r).length>0;return{runtimeContext:"documentSection",documentSectionId:e.id,...k?{tableTotalsRequest:k}:{},...Ce?{documentFilterValues:t}:{},...ve?{documentControlDefinitions:n,documentControlValues:r}:{},...s?{documentDashboardInputValues:s}:{}}},[t,n,r,s,e.id,k]),I=wJe({card:v,queryOptions:j,surfaceMode:i,previewRowLimit:u,onPreviewRowLimitChange:y}),E=I.records||KJe,T=S.useMemo(()=>fQe(E),[E]),D=S.useMemo(()=>aae(e),[e]),A=v.type==="table"?cc({section:e}).trailingRowCount:0,P=S.useMemo(()=>cc({section:e,totalRowCount:v.type==="table"?E.length+A:0}),[v.type,A,E.length,e]),R=v.type==="table"&&E.length>0&&P.trailingRowCount>0,H=I.errorMessage?0:P.totalRowCount,z=R&&(a?a.endIndex>E.length:!l||P.totalRowCount<=l),U=R&&z,W=S.useMemo(()=>v.type==="table"&&!U?_Je(C):C,[v.type,C,U]),O=S.useCallback(Ce=>{x==null||x(e.id,ve=>{var De;const te=(De=ve.card.preferences)==null?void 0:De.tablePrefs,_e=typeof Ce=="function"?Ce((te==null?void 0:te.columnSizing)||{}):Ce;return{...ve,card:{...ve.card,preferences:{...ve.card.preferences,tablePrefs:{...te,columnSizing:_e}}}}})},[x,e.id]);let Z=E;v.type==="table"&&a?Z=E.slice(Math.min(a.startIndex,E.length),Math.min(a.endIndex,E.length)):v.type==="table"&&l&&(Z=E.slice(0,l));const Y=(I.isLoading||I.isPending||I.isFetching)&&E.length===0,M=i!=="print"&&I.isFetching&&E.length>0,K=i==="print"&&I.isLoading&&E.length>0;S.useEffect(()=>{v.type==="table"&&(h==null||h(e.id,H))},[v.type,h,e.id,H]),S.useEffect(()=>{v.type==="table"&&(m==null||m(e.id,T,D))},[v.type,m,D,T,e.id]);const L=S.useMemo(()=>{var Ce,ve,te,_e;return v.type!=="pivotTable"||I.errorMessage||!E.length?null:{records:E,columnSubtotalMeta:(Ce=I.data)==null?void 0:Ce.columnSubtotalMeta,subtotalColumns:((ve=I.data)==null?void 0:ve.subtotalColumns)||[],pivotSchema:((te=I.data)==null?void 0:te.pivotSchema)||[],groupByColumns:(_e=I.data)==null?void 0:_e.groupByColumns}},[v.type,E,(Ie=I.data)==null?void 0:Ie.columnSubtotalMeta,(oe=I.data)==null?void 0:oe.subtotalColumns,(me=I.data)==null?void 0:me.pivotSchema,(we=I.data)==null?void 0:we.groupByColumns,I.errorMessage]),$=vh(v,L),B=S.useMemo(()=>{if(v.type!=="pivotTable"||!$)return 0;const Ce=GF($.data);return cc({section:e,totalRowCount:Ce.tableData.length+Ce.grandTotalRows.length}).totalRowCount},[v.type,$,e]);S.useEffect(()=>{v.type==="pivotTable"&&(h==null||h(e.id,B))},[v.type,h,$,B,e.id]);const V=dQe(e),F=cQe(N),q=S.useRef(null),G=S.useRef(null),X=S.useRef({rowDataVersion:I.rowDataVersion,errorMessage:I.errorMessage}),[J,fe]=S.useState(!1),[ue,pe]=S.useState(0),ye=oet({tableSlice:a,initialRowsPerPageLimit:l,totalRowCount:v.type==="pivotTable"?B:H}),ie=a?`${a.pageIndex}:${a.startIndex}:${a.endIndex}:${a.totalRows}`:"unsliced";if(S.useEffect(()=>{const Ce=X.current;X.current={rowDataVersion:I.rowDataVersion,errorMessage:I.errorMessage},!(Ce.rowDataVersion===I.rowDataVersion&&Ce.errorMessage===I.errorMessage)&&(b==null||b(e.id),pe(ve=>ve+1))},[b,I.errorMessage,I.rowDataVersion,e.id]),ret({sectionId:e.id,sectionRef:q,tableSurfaceRef:G,enabled:!J,measureKey:`${E.length}:${Z.length}:${Y?"loading":"ready"}:${F}:${ie}:${ue}`,measurementScale:w,fallbackRowHeightPx:V,fallbackRowCount:Math.max(0,ye.endIndex-ye.startIndex),rowRangeStartIndex:ye.startIndex,rowRangeEndIndex:ye.endIndex,totalRowCount:ye.totalRowCount,canUpdateLayoutChrome:WJe({tableSlice:a}),onTableLayoutMeasure:g}),I.errorMessage)return c.jsx(Rd,{section:e,icon:c.jsx(Ai,{className:"h-4 w-4 text-amber-500"}),title:"Table query failed",message:I.errorMessage,exportState:"error",isEditing:o,showInlineEditAction:d,onEditTableSection:f});if(Y)return c.jsx(uet,{section:e,isEditing:o,showInlineEditAction:d,onEditTableSection:f});if(K)return c.jsx(Rd,{section:e,icon:c.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:o,showInlineEditAction:d,onEditTableSection:f});if(U&&_&&!((ge=I.data)!=null&&ge.tableTotalsByColumnId)&&I.isFetching)return c.jsx(Rd,{section:e,icon:c.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:o,showInlineEditAction:d,onEditTableSection:f});if(U&&_&&!((re=I.data)!=null&&re.tableTotalsByColumnId))return c.jsx(Rd,{section:e,icon:c.jsx(Ai,{className:"h-4 w-4 text-amber-500"}),title:"Table totals unavailable",message:"Grand totals could not be computed for this document table.",exportState:"error",isEditing:o,showInlineEditAction:d,onEditTableSection:f});if(E.length===0)return c.jsx(Rd,{section:e,icon:c.jsx(p.Table2,{className:"h-4 w-4 text-zinc-300"}),title:e.title||v.title||"Table",message:"No records to display",exportState:"empty",isEditing:o,showInlineEditAction:d,onEditTableSection:f});let ae;if(v.type==="pivotTable"){if(!$)return c.jsx(Rd,{section:e,icon:c.jsx(Ai,{className:"h-4 w-4 text-amber-500"}),title:"Pivot table configuration unavailable",message:"Edit the table to confirm its rows, columns, and metrics.",exportState:"error",isEditing:o,showInlineEditAction:d,onEditTableSection:f});ae=c.jsx(wg,{card:C,data:aet($.data,a,l),options:$.options,suppressSortControls:P.renderContract.suppressSortControls,renderPlainWrapper:P.renderContract.renderPlainWrapper})}else ae=c.jsx(Tu,{card:W,data:Z,formattingFullRows:E,totalsData:U?E:void 0,totalsByColumnId:U?(ne=I.data)==null?void 0:ne.tableTotalsByColumnId:void 0,comparisonMetadata:I.comparisonMetadata,paginationMetadata:I.pagination,isLoading:Y,columnSizing:(ee=(he=W.preferences)==null?void 0:he.tablePrefs)==null?void 0:ee.columnSizing,onColumnSizingChange:o&&i!=="print"?O:void 0,onColumnResizeStateChange:fe,showColumnResizeHandles:o&&i!=="print",suppressSortControls:P.renderContract.suppressSortControls,suppressCellHoverCards:P.renderContract.disableDashboardInteractions});const se=i!=="print"&&I.isPreviewWindowIncomplete&&(!a||a.endIndex>=E.length);return c.jsxs("div",{className:"relative",children:[c.jsxs("div",{ref:q,className:"pt-3",children:[c.jsx(det,{section:e}),c.jsxs("div",{ref:G,"data-document-table-section":"true",className:XJe(N),style:{...GJe,"--document-table-row-height":`${V}px`,"--document-table-min-surface-height":`${a?0:PJe}px`,"--document-table-header-bg":N.headerBackgroundColor,"--document-table-header-color":N.headerTextColor,"--document-table-totals-bg":N.totalsStyle.backgroundColor,"--document-table-totals-color":N.totalsStyle.textColor,"--document-table-totals-border-color":N.totalsStyle.borderTopColor,"--document-table-totals-font-weight":String(uQe(N.totalsStyle.fontWeight)),"--document-table-cell-color":"#18181b"},children:[M?c.jsx(fet,{}):null,ae]})]}),se?c.jsx(het,{loadedRowCount:I.loadedRowCount,totalRowCount:I.totalRowCount,isFetching:I.isFetching,onLoadMore:I.loadMorePreviewRows}):null]})}function ret({sectionId:e,sectionRef:t,tableSurfaceRef:n,enabled:r,measureKey:s,measurementScale:o,fallbackRowHeightPx:i,fallbackRowCount:a,rowRangeStartIndex:l,rowRangeEndIndex:u,totalRowCount:d,canUpdateLayoutChrome:f,onTableLayoutMeasure:h}){const m=S.useRef(null);S.useEffect(()=>{if(!r||!h)return;m.current=null;let g=null;const b=()=>{const E=t.current,T=n.current;if(!E||!T)return;const D=Number.isFinite(o)&&o>0?o:1,A=V=>V/D,P=TJe(T),R=P.length>0?P.map(V=>{const F=A(V.getBoundingClientRect().height);return F>0?F:i}).filter(V=>V>0):Array.from({length:a},()=>i);if(R.length===0)return;const H=R.map(V=>Math.ceil(V)),z=Math.ceil(Math.max(...R)),U=R.reduce((V,F)=>V+F,0),W=Math.ceil(U/R.length),O=Math.ceil(A(E.getBoundingClientRect().height)),Z=Y9(E),Y=P[0],M=P[P.length-1],K=Y&&M?DJe({sectionElement:E,tableSurfaceElement:T,firstRowElement:Y,lastRowElement:M,measurementScale:D}):void 0;let L;if(Z&&Y&&M){const V=Z.getBoundingClientRect(),F=iet(Z,D,V),q=Y.getBoundingClientRect(),G=A(q.top-V.top),X=(K==null?void 0:K.trailingChromePx)??0,J=F-G-X;L=Math.max(1,set(R,J))}const $=(K==null?void 0:K.chromeHeightPx)??Math.max(0,Math.ceil(O-U)),B={rowHeightPx:z,averageRowHeightPx:W,rowHeightsPx:H,rowRangeStartIndex:l,rowRangeEndIndex:u,totalRowCount:d,chromeHeightPx:$,renderedMinHeightPx:K==null?void 0:K.renderedMinHeightPx,canUpdateLayoutChrome:f,rowsPerPage:L};RJe(m.current,B)&&(m.current=B,h(e,B))},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),v=new Set,C=E=>{!E||v.has(E)||(y.observe(E),v.add(E))},N=E=>{!E||!w||w.observe(E,{attributes:!0,characterData:!0,childList:!0,subtree:!0})},k=t.current,_=n.current,j=Y9(k),I=Dae(j);return C(k),C(_),C(j),C(I),N(j),()=>{g!==null&&window.cancelAnimationFrame(g),y.disconnect(),w==null||w.disconnect()}},[r,o,s,h,e,t,n,i,a,l,u,d,f])}function set(e,t){if(!Number.isFinite(t)||t<=0)return 0;let n=0,r=0;for(const s of e){if(n+s>t)break;n+=s,r+=1}return r}function oet({tableSlice:e,initialRowsPerPageLimit:t,totalRowCount:n}){const r=Math.max(0,n),s=Math.min((e==null?void 0:e.startIndex)??0,r),o=Math.min((e==null?void 0:e.endIndex)??t??r,r);return{startIndex:s,endIndex:Math.max(s,o),totalRowCount:r}}function iet(e,t,n){const r=Dae(e);if(r)return(r.getBoundingClientRect().top-n.top)/t;const s=window.getComputedStyle(e),o=Number.parseFloat(s.paddingBottom||"0")||0;return AJe(e)-o}function aet(e,t,n){var f,h,m,g,b,x;const r=(t==null?void 0:t.startIndex)??0,s=(t==null?void 0:t.endIndex)??(n||void 0);if(s===void 0)return e;const o=((f=e.rowData)==null?void 0:f.length)??((h=e.rowHeaders)==null?void 0:h.length)??0,i=((m=e.grandTotalRows)==null?void 0:m.length)??0,a=Math.min(r,o),l=Math.min(s,o),u=Math.max(0,r-o),d=Math.max(0,Math.min(s-o,i));return{...e,rowData:(g=e.rowData)==null?void 0:g.slice(a,l),rowHeaders:((b=e.rowHeaders)==null?void 0:b.slice(a,l))??[],grandTotalRows:((x=e.grandTotalRows)==null?void 0:x.slice(u,d))??[]}}function cet({section:e,isEditing:t,reason:n,showInlineEditAction:r,onEditTableSection:s}){return c.jsx("div",{className:"pt-3",children:c.jsxs("div",{className:"rounded border border-dashed border-zinc-200 px-4 py-8 text-center","data-document-render-error":"true",children:[c.jsx(p.Table2,{className:"mx-auto mb-2 h-5 w-5 text-zinc-300"}),c.jsx("p",{className:"text-[12px] font-medium text-zinc-600",children:e.title||e.card.title||"Table"}),n?c.jsx("p",{className:"mt-1 text-[11px] text-zinc-400",children:n}):null,r?c.jsx(SL,{section:e,isEditing:t,className:"mt-3",onEditTableSection:s}):null]})})}function uet({section:e,isEditing:t,showInlineEditAction:n,onEditTableSection:r}){return c.jsx("div",{className:"pt-3","data-document-render-loading":"true",children:c.jsxs("div",{className:"relative h-[220px] overflow-hidden rounded",children:[c.jsx(P5,{columns:5,rows:8}),n?c.jsx("div",{className:"absolute right-2 top-2 z-20",children:c.jsx(SL,{section:e,isEditing:t,onEditTableSection:r})}):null]})})}function Rd({section:e,icon:t,title:n,message:r,exportState:s,isEditing:o,showInlineEditAction:i,onEditTableSection:a}){const l=s==="blocked"||s==="error",u=s==="loading";return c.jsx("div",{className:"pt-3",children:c.jsx("div",{className:"rounded border border-zinc-200 bg-zinc-50 px-4 py-5","data-document-render-error":l?"true":void 0,"data-document-render-loading":u?"true":void 0,children:c.jsxs("div",{className:"flex items-start gap-3",children:[c.jsx("div",{className:"mt-0.5 shrink-0",children:t}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsx("p",{className:"text-[12px] font-medium text-zinc-700",children:n}),c.jsx("p",{className:"mt-1 break-words text-[11px] text-zinc-500",children:r})]}),i?c.jsx(SL,{section:e,isEditing:o,onEditTableSection:a}):null]})})})}function det({section:e}){const t=e.title||e.card.title;return t?c.jsx("div",{className:"mb-2 min-w-0",children:t?c.jsx("p",{className:"whitespace-normal break-words text-[12px] font-semibold leading-4 text-zinc-800",children:t}):null}):null}function fet(){return c.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:[c.jsx(p.LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Updating..."]})}function het({loadedRowCount:e,totalRowCount:t,isFetching:n,onLoadMore:r}){const s=t===void 0?"unknown":t.toLocaleString();return c.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:[c.jsxs("span",{className:"whitespace-nowrap",children:["Previewing ",e.toLocaleString()," of ",s," rows"]}),r?c.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 SL({section:e,isEditing:t,className:n,onEditTableSection:r}){return t?c.jsxs(p.Button,{type:"button",variant:"outline",size:"sm",className:n?`h-8 gap-2 ${n}`:"h-8 gap-2",onClick:s=>{s.stopPropagation(),r==null||r(e)},children:[c.jsx(p.Table2,{className:"h-3.5 w-3.5"}),"Edit table"]}):null}const met={a4:{width:595,height:842},letter:{width:612,height:792}},pet=96/72;function Oae(e){return get(e)}function get(e){return bet(e,{pointToPixelScale:pet})}function bet(e,{pointToPixelScale:t}){const n=met[e.size],r=e.orientation==="landscape"?n.height:n.width,s=e.orientation==="landscape"?n.width:n.height,o=e.margins,i=o.unit==="mm"?72/25.4:72,a=u=>Math.round(u*i*t),l={top:a(o.top),right:a(o.right),bottom:a(o.bottom),left:a(o.left)};return{width:Math.round(r*t),height:Math.round(s*t),padding:`${l.top}px ${l.right}px ${l.bottom}px ${l.left}px`,paddingPx:l}}const xet=16,Tp=78,yet=0,vet=0,wet=72,Cet=40;function Net(e,t={}){var m;const n=t.tablePaginationBySectionId??{},r=t.pageMetricsMode??"preview",s=t.document?$ae(t.document):Number.POSITIVE_INFINITY,o=[];let i=[],a=0,l=0,u;const d=(g,b=i,x=a,y=`document-page-${o.length+1}-${x}`,w=u)=>{o.push({id:y,startInsertIndex:x,sections:b,breakAfterSection:g,layoutError:w})},f=g=>{const b=o[o.length-1];return!b||b.breakAfterSection||b.sections.length===0?!1:(b.breakAfterSection=g,!0)};e.forEach((g,b)=>{if(g.type==="page_break"){i.length>0?d(g):f(g)||d(g),i=[],l=0,a=b+1;return}if(g.type==="table"){const w=n[g.id],v=(w==null?void 0:w.rowCount)??0,C=(w==null?void 0:w.rowsPerPage)??0,N=!!t.document,k=N&&C>0?jet(g,w,s-l):C;if(C>0&&(v>C||N&&i.length>0&&k>0&&v>k)&&w){!N&&i.length>0&&(d(),i=[],l=0,u=void 0,a=b),N&&i.length>0&&k<=0&&(d(),i=[],l=0,u=void 0,a=b);const j=CL(g,w),I=ket({rowCount:v,rowsPerPage:C,footerRowCount:(w==null?void 0:w.footerRowCount)??0,firstRowsPerPage:N&&i.length>0?k:C,rowMeasurementState:j,capFirstRowsPerPage:N&&i.length>0&&w.measuredRowsPerPage!==void 0,firstRowsAvailableHeightPx:N&&i.length>0?f1(w,s-l):f1(w,s),fullRowsAvailableHeightPx:f1(w,s)});I.forEach((E,T)=>{const D=T===I.length-1,A={section:g,sectionIndex:b,tableSlice:{startIndex:E.startIndex,endIndex:E.endIndex,pageIndex:T,pageCount:I.length,totalRows:v,rowsPerPage:C}},P=Eet(g,w,E.startIndex,E.endIndex);if(N&&T===0&&i.length>0){i.push(A),l+=P,D||(d(),i=[],l=0,u=void 0,a=b+1);return}if(D&&N){i=[A],l=P,u=void 0,a=b;return}d(void 0,[A],b,`document-page-table-${g.id}-${T+1}`,void 0)});return}}const x=t.document?Tet({section:g,document:t.document,tablePagination:n[g.id],pageMetricsMode:r,textRenderContext:t.textRenderContext}):0;if(Number.isFinite(s)&&x>s){i.length>0&&(d(),i=[],l=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=[],l=0,u=void 0,a=b+1;return}i.length>0&&l+x>s&&(d(),i=[],l=0,u=void 0,a=b),i.push({section:g,sectionIndex:b}),l+=x}),(o.length===0||i.length>0||((m=e[e.length-1])==null?void 0:m.type)==="page_break")&&d();const h=o.length;return o.map((g,b)=>({...g,pageNumber:b+1,pageCount:h}))}function ket({rowCount:e,rowsPerPage:t,footerRowCount:n=0,firstRowsPerPage:r,rowMeasurementState:s,capFirstRowsPerPage:o=!1,firstRowsAvailableHeightPx:i,fullRowsAvailableHeightPx:a}){const l=[];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=l.length===0?i:a,b=(s.kind==="sparse"||s.kind==="complete")&&Number.isFinite(m)?Rae({rowMeasurementState:s,startIndex:u,availableHeightPx:m??0}):void 0,x=b!==void 0?Math.max(1,l.length===0&&o?Math.min(b,d):b):Math.max(1,d);let y;if(f===0||u>=h)y=Math.min(u+x,e);else{const w=h-u;if(w+f<=x&&wL({rowMeasurementState:s,startIndex:u,endIndex:e})<=(m??Number.POSITIVE_INFINITY))y=e;else{let v=Math.min(x,w);v===w&&f>0&&w>1&&(v-=1),y=u+Math.max(1,v)}}l.push({startIndex:u,endIndex:y}),u=y,d=t}return l}function _et({document:e,tableRowCountsBySectionId:t,tableLayoutMeasurementsBySectionId:n,shouldPaginateTables:r,pageMetricsMode:s="preview"}){if(!r)return{};const o={};for(const i of e.sections){if(!Fx(i))continue;const a=t[i.id]??0;if(a<=0)continue;const l=n==null?void 0:n[i.id],u=cc({section:i,totalRowCount:a,layoutMeasurement:l}),d=J_({totalRowCount:u.totalRowCount,fallbackRowHeightPx:u.fallbackRowHeightPx,layoutMeasurement:l});o[i.id]={rowCount:u.totalRowCount,rowsPerPage:Lae(e,u,s),footerRowCount:u.trailingRowCount,fallbackRowHeightPx:u.fallbackRowHeightPx,rowMeasurementState:d,rowHeightPx:u.measuredRowHeightPx,averageRowHeightPx:u.measuredAverageRowHeightPx,rowHeightsPx:u.measuredRowHeightsPx,chromeHeightPx:u.chromeHeightPx,renderedMinHeightPx:u.renderedMinHeightPx,measuredRowsPerPage:u.measuredRowsPerPage}}return o}function Fx(e){return e.type!=="table"?!1:cc({section:e}).isRunnable}function Lae(e,t,n="preview"){const s=$ae(e)-(t.chromeHeightPx??Tp),o=Math.floor(s/t.effectiveRowHeightPx);return Math.max(1,o)}function jet(e,t,n){if(!Number.isFinite(n))return(t==null?void 0:t.rowsPerPage)??0;const r=f1(t,n),s=t&&CL(e,t),i=(s&&s.kind!=="unmeasured"?Rae({rowMeasurementState:s,startIndex:0,availableHeightPx:r}):void 0)??Math.max(0,Math.floor(r/uN(e,t)));return(t==null?void 0:t.measuredRowsPerPage)!==void 0?Math.max(0,Math.min(i,t.measuredRowsPerPage)):i}function Eet(e,t,n,r){return UJe({rowMeasurementState:t?CL(e,t):J_({totalRowCount:r,fallbackRowHeightPx:uN(e,t)}),startIndex:n,endIndex:r,chromeHeightPx:(t==null?void 0:t.chromeHeightPx)??Tp})}function f1(e,t){return t-((e==null?void 0:e.chromeHeightPx)??Tp)}function uN(e,t){if(t!=null&&t.rowMeasurementState)return qJe(t.rowMeasurementState);const n=(t==null?void 0:t.fallbackRowHeightPx)??cc({section:e}).fallbackRowHeightPx;return Mae({fallbackRowHeightPx:n,measuredRowHeightPx:t==null?void 0:t.rowHeightPx,measuredRowHeightsPx:t==null?void 0:t.rowHeightsPx,totalRowCount:t==null?void 0:t.rowCount})}function CL(e,t){return t.rowMeasurementState?t.rowMeasurementState:J_({totalRowCount:t.rowCount,fallbackRowHeightPx:uN(e,t),layoutMeasurement:t.rowHeightPx!==void 0||t.rowHeightsPx?{rowHeightPx:t.rowHeightPx??uN(e,t),averageRowHeightPx:t.averageRowHeightPx,rowHeightsPx:t.rowHeightsPx,chromeHeightPx:t.chromeHeightPx??Tp,renderedMinHeightPx:t.renderedMinHeightPx,rowsPerPage:t.rowsPerPage}:void 0})}function $ae(e,t){const n=zae(e),r=K9(e.header,wet),s=K9(e.footer,Cet);return n.height-n.paddingPx.top-n.paddingPx.bottom-r-s-xet}function Iet(e,t){const n=zae(e);return n.width-n.paddingPx.left-n.paddingPx.right}function Tet({section:e,document:t,tablePagination:n,pageMetricsMode:r,textRenderContext:s}){if(e.type==="spacer")return Math.max(8,e.heightPx);if(e.type==="text")return Det(e,t,r,s);if(e.type==="table"){const o=cc({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??Tp,renderedMinHeightPx:n.renderedMinHeightPx,rowsPerPage:n.rowsPerPage}:void 0}),i=(n==null?void 0:n.rowCount)??3;return HJe({rowMeasurementState:(n==null?void 0:n.rowMeasurementState)??J_({totalRowCount:i,fallbackRowHeightPx:o.effectiveRowHeightPx}),startIndex:0,endIndex:i,chromeHeightPx:(n==null?void 0:n.chromeHeightPx)??Tp,renderedMinHeightPx:n==null?void 0:n.renderedMinHeightPx})}return 0}function Det(e,t,n,r){var l,u;const s=((l=e.style)==null?void 0:l.fontSize)??13,o=Math.ceil(s*((u=e.style)!=null&&u.fontSize?1.45:1.55)),i=Math.max(120,Iet(t)-yet),a=Met({content:e.content,bodyWidthPx:i,fontSize:s,textRenderContext:r});return vet+a*o}function Met({content:e,bodyWidthPx:t,fontSize:n,textRenderContext:r}){const s=n*.54,o=r?tae(e,r):Aet(e),i=Ret(o,s);return i.length===0?1:i.reduce((a,l)=>a+Math.max(1,Math.ceil(l/t)),0)}function Aet(e){return e.map(t=>({type:t.type,value:t.type==="text"?t.value:"0".repeat(120),format:t.format}))}function Ret(e,t){const n=[0];for(const r of e){const s=Fet(r);r.value.split(`
|
|
@@ -1358,4 +1358,4 @@ prismjs/prism.js:
|
|
|
1358
1358
|
More info: ${s.docs}`:"",a=typeof s.message=="string"&&s.message.trim()?s.message.trim():typeof s.error=="string"&&s.error.trim()?s.error.trim():null;if(a){const l=o?` (code: ${o})`:"",u=o==="insufficient_quota"||a.toLowerCase().includes("quota")?`
|
|
1359
1359
|
|
|
1360
1360
|
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}${l}${i}${u}`}return null};if(typeof e=="string"){const r=e.trim();if(!r)return"Something went wrong.";try{const s=JSON.parse(r),o=t(s);if(o)return o}catch{}return r}const n=t(e);if(n)return n;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function g3({errorMessage:e}){return c.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:[c.jsx(Ai,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),c.jsx("span",{className:"whitespace-pre-wrap break-words leading-[1.55]",children:zxt(e)})]})}function Bxt({error:e,resetErrorBoundary:t}){return c.jsxs("div",{className:"my-3 space-y-2 rounded-control border border-border/60 bg-muted/20 p-2.5",children:[c.jsx(g3,{errorMessage:e==null?void 0:e.message}),c.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 Vxt({text:e,files:t}){return c.jsxs(Yde,{who:"You",children:[e&&c.jsx("div",{className:"whitespace-pre-line text-[13px] leading-[1.55] text-foreground",children:e}),t&&t.length>0&&c.jsx("div",{className:"flex flex-wrap gap-2 pt-0.5",children:t.map(n=>c.jsx(zct,{file:n},n.id))})]})}function Hxt({text:e}){const t=e.split("|"),n=t[0],r=t[1]||"{}",s=JSON.parse(r);return c.jsxs("div",{className:"space-y-1 text-xs",children:[c.jsxs("div",{children:[c.jsx("span",{className:"font-bold",children:"System Message:"})," ",n]}),c.jsxs("div",{className:"space-y-1",children:[c.jsx("span",{className:"font-mono text-xs",children:"Scope:"}),c.jsx(sut,{children:JSON.stringify(s,null,2)})]})]})}function Gde(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")?p3(r,t):!1}})}function uU(){return c.jsx("span",{className:"relative grid h-2 w-2 shrink-0 place-items-center",children:c.jsx("span",{className:"absolute inset-0 animate-pulse rounded-full bg-muted-foreground/70"})})}function Uxt({status:e,errorMessage:t,activeToolText:n}){return n?c.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-muted-foreground",children:[c.jsx(uU,{}),c.jsx("span",{children:n})]}):e==="submitted"||e==="streaming"?c.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-muted-foreground",children:[c.jsx(uU,{}),c.jsx("span",{children:e==="submitted"?"Thinking":"Generating"})]}):e==="error"?c.jsx(g3,{errorMessage:t}):null}function qxt(e){var t;return e?(t=[...e].reverse().find(n=>{var r;return n.role==="assistant"&&((r=n.parts)==null?void 0:r.some(s=>s.type==="text"&&typeof s.text=="string"&&s.text.trim().length>0))}))==null?void 0:t.id:void 0}function Wxt({message:e,messageIndex:t,messages:n,showTools:r=!1,onAddToDashboard:s,showSystemMessage:o=!1,handleRun:i,onQuickReply:a,disableQuickReplies:l=!1}){var y,w,v,C;const u=qxt(n),d=e.id===u;if(e.role==="user"){const N=((y=e.parts)==null?void 0:y.filter(I=>I.type==="text"))||[],k=((w=e.parts)==null?void 0:w.filter(I=>I.type==="file"))||[],_=N.map(I=>I.text).join(`
|
|
1361
|
-
`).trim(),j=k.map((I,E)=>{var A,P;let T="",D;if((A=I.url)!=null&&A.startsWith("data:")){const R=I.url.match(/data:[^;]+;base64,(.+)/);R&&(T=R[1],(P=I.mediaType)!=null&&P.startsWith("image/")&&(D=I.url))}return{id:`${e.id||t}-file-${E}`,name:I.filename||`File ${E+1}`,size:0,type:I.mediaType||"application/octet-stream",data:T,preview:D}});return c.jsx(Vxt,{text:_||void 0,files:j.length>0?j:void 0})}const f=((v=e.parts)==null?void 0:v.filter(N=>N.type==="reasoning"))||[],h=f.length>0,m=f.some(N=>N.state==="streaming"),g=f.filter(N=>N.text&&N.text.trim().length>0),b=h&&(g.length>0||m)?c.jsxs(mc,{className:"space-y-2",defaultOpen:!1,children:[c.jsx(pc,{asChild:!0,children:c.jsxs("button",{type:"button",className:"group inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:[c.jsx(vr,{className:"h-3 w-3 transition-transform duration-200 group-data-[state=open]:rotate-90"}),c.jsx("span",{className:m?"animate-pulse":"",children:m?"Reasoning":"Show reasoning"}),g.length>1&&c.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["(",g.length," steps)"]})]})}),c.jsx(gc,{children:c.jsx("ol",{className:"space-y-2 border-l border-border/60 pl-3",children:g.map((N,k)=>c.jsxs("li",{className:"relative",children:[c.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:k+1}),c.jsx(nU,{className:"text-[12px] leading-[1.55] text-muted-foreground",text:N.text})]},`${e.id||t}-reasoning-${k}`))})})]},`${e.id||t}-reasoning`):null,x=(C=e.parts)==null?void 0:C.map((N,k)=>{var j;const _=`${e.id||t}-${k}`;switch(N.type){case"text":{const I=typeof N.text=="string"?N.text:JSON.stringify(N.text??"",null,2);if(e.role==="assistant"){const{cleanedText:E,quickReplies:T}=Lxt(I),D=E.trim().length>0;return c.jsxs("div",{className:"space-y-2.5",children:[D&&c.jsx(nU,{text:E,handleRun:i,onAddToDashboard:s,messageId:e.id,messages:n}),T.length>0&&a&&d&&c.jsxs("div",{className:"space-y-1.5",children:[T.length>=3&&c.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Suggested next steps"}),c.jsx("div",{className:"flex flex-wrap gap-1",children:T.map(({label:A,value:P},R)=>c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.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:l,onClick:()=>a(P),children:c.jsx("span",{className:"truncate",children:A})})}),c.jsx(p.TooltipContent,{side:"top",align:"center",children:c.jsx("p",{className:"max-w-xs text-xs",children:P})})]},`${_}-qr-${R}`))})]})]},_)}return e.role==="system"&&o?c.jsx(Hxt,{text:I},_):null}case"error":{const I=N,E=I.errorText??I.error??I.message;return c.jsx("div",{className:"my-4",children:c.jsx(g3,{errorMessage:E})},_)}case"reasoning":return null;default:return((j=N.type)!=null&&j.startsWith("tool-")||N.type==="dynamic-tool")&&p3(N,r)?c.jsx(ba,{FallbackComponent:({error:I,resetErrorBoundary:E})=>c.jsx(Bxt,{error:I,resetErrorBoundary:E}),children:c.jsx(Axt,{part:N,idx:_,messageId:e.id,showTools:r,onAddToDashboard:s,messages:n})},_):null}});return e.role==="assistant"?Gde(e,r)?c.jsxs(Yde,{who:"Assistant",className:"space-y-2",children:[b,x]}):null:c.jsxs("div",{className:"space-y-2",children:[b,x]})}const Yxt=8,Gxt=24,Kxt=20;function Zxt(e,t,n,r){return e==="error"&&t?!0:r?!1:!!(n||e==="submitted"||e==="streaming")}function Kde({messages:e,showTools:t=!1,showSystemMessage:n=!1,handleRun:r,onAddToDashboard:s,onQuickReply:o,disableQuickReplies:i=!1,status:a,errorMessage:l,activeToolText:u,className:d,rowContentClassName:f,statusClassName:h,latestButtonClassName:m,scrollToEndSignal:g=0}){const b=S.useRef(null),x=S.useRef(null),y=S.useRef(e.length),w=S.useRef(!1),v=S.useRef(null),C=S.useRef(!1),N=S.useRef(g),[k,_]=S.useState(!0),[j,I]=S.useState(0),[E,T]=S.useState(Gxt);N.current!==g&&(N.current=g,C.current=!0);const D=e[e.length-1],A=Gde(D,t),P=Zxt(a,l,u,A),R=Gk({count:e.length,getScrollElement:()=>b.current,estimateSize:W=>{const O=e[W];return(O==null?void 0:O.role)==="user"?88:180},getItemKey:W=>{const O=e[W];return(O==null?void 0:O.id)||`message-${W}`},anchorTo:"end",followOnAppend:!0,scrollEndThreshold:Yxt,overscan:6,gap:20,paddingEnd:P?E+Kxt:0,useAnimationFrameWithResizeObserver:!0,onChange:W=>{const O=W.isAtEnd();_(Z=>Z===O?Z:O),O&&I(0)}}),H=S.useCallback((W="smooth")=>{v.current!==null&&cancelAnimationFrame(v.current),v.current=requestAnimationFrame(()=>{v.current=null,R.scrollToEnd({behavior:W})}),I(0),_(!0)},[R]);S.useLayoutEffect(()=>{w.current||(w.current=!0,H("auto"))},[H]),S.useLayoutEffect(()=>{C.current&&(C.current=!1,H("auto"))},[e.length,g,H]),S.useEffect(()=>{const W=y.current;y.current=e.length,e.length>W&&!R.isAtEnd()&&I(O=>O+e.length-W),e.length===0&&(I(0),_(!0),w.current=!1,C.current=!1)},[e.length,R]);const z=R.getVirtualItems(),U=R.getTotalSize();return S.useEffect(()=>()=>{v.current!==null&&cancelAnimationFrame(v.current)},[]),S.useLayoutEffect(()=>{const W=x.current;if(!W||!P)return;const O=()=>{const Y=Math.ceil(W.getBoundingClientRect().height);Y>0&&T(M=>M===Y?M:Y)};if(O(),typeof ResizeObserver>"u")return;const Z=new ResizeObserver(O);return Z.observe(W),()=>Z.disconnect()},[P,a,l,u]),c.jsxs(c.Fragment,{children:[c.jsx(bl,{"data-role":"assistant-virtualized-scroll-area",ref:b,className:p.cn("min-h-0 min-w-0 flex-1 basis-0",d),children:c.jsxs("div",{className:"relative w-full",style:{height:U},children:[z.map(W=>{const O=e[W.index];return O?c.jsx("div",{ref:R.measureElement,"data-index":W.index,className:"absolute left-0 top-0 w-full",style:{transform:`translateY(${W.start}px)`},children:c.jsx("div",{className:p.cn("min-w-0",f),children:c.jsx(Wxt,{message:O,messageIndex:W.index,messages:e,showTools:t,showSystemMessage:n,handleRun:r,onAddToDashboard:s,onQuickReply:o,disableQuickReplies:i})})},W.key):null}),P&&c.jsx("div",{ref:x,className:p.cn("absolute left-0 top-0 w-full",h),style:{transform:`translateY(${Math.max(U-E,0)}px)`},children:c.jsx("div",{className:p.cn("min-w-0",f),children:c.jsx(Uxt,{status:a,errorMessage:l,activeToolText:u})})})]})}),!k&&c.jsxs("button",{type:"button",onClick:()=>H("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:[c.jsx(Ns,{className:"h-3 w-3"}),"Latest",j>0&&c.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:j>9?"9+":j})]})]})}function Xxt(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 Qxt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Jxt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=S.useState(!1),[a,l]=S.useState(p.isDevEnv),[u,d]=S.useState(!1),[f,h]=S.useState("auto"),[m,g]=S.useState(!1),[b,x]=S.useState(!1),[y,w]=S.useState(0),v=n??b,{isLocalDev:C,isConsoleMode:N}=Pp(),k=C||N||a,_=S.useRef(null);p.useDashboardStore(ee=>ee.dashboard.aiScopeTables),p.useDashboardStore(ee=>ee.isDashboardEditing);const j=p.useDashboardStore(ee=>ee.selectedSheetId),{setDataSource:I}=p.useEditorActions(),{setSelectedFrameId:E,setIsDashboardEditing:T}=p.useDashboardActions(),D=R5(),{clearAssistantMessageContexts:A}=p.useAIActions(),{clearQueue:P}=p.useQueueActions(),{clearFileAttachments:R,getFileAttachments:H}=p.useFileActions(),z=p.useFileAttachments("dashboard"),U=p.useEditorStore(ee=>ee.card.dataSource),{assistantProfile:W}=nue(),O=p.useDashboardStore(ee=>ee.handleOpenAssistantProfile),{selectedEntities:Z,applyDashboardDefaultEntities:Y}=D_("dashboard"),{sendMessage:M,isLoading:K,messages:L,setMessages:$,status:B,stop:V,errorMessage:F,clearError:q}=yct({dynamicVisualMode:f}),G=S.useCallback(()=>{w(ee=>ee+1)},[]),X=S.useCallback(ee=>{r==null||r(ee),n===void 0&&x(ee)},[n,r]),J=S.useCallback(()=>{X(!v)},[v,X]);S.useEffect(()=>{if(!v)return;function ee(Ce){Ce.key==="Escape"&&X(!1)}return window.addEventListener("keydown",ee),()=>{window.removeEventListener("keydown",ee)}},[v,X]);const[fe,ue]=S.useState(""),pe=ee=>{ue(ee.target.value)};async function ye({sql:ee,cardTitle:Ce,connectionId:ve,cardType:te,python:_e,cardConfig:De,dataSource:Fe,customVisualPreferences:Ye,visualizationMode:ze,dynamicCardPreferences:Ve}){if(!j)return;const Ke=ze==="dynamic",ke=p.hasValidCardConfig(De),Xe=ve||(Fe==null?void 0:Fe.connectionId)||"",Pe=Fe?{...Fe,connectionId:Xe||Fe.connectionId,connectionType:Fe.connectionType||"",mode:Fe.mode||"database",selectedEntities:Fe.selectedEntities||[]}:Xe?{connectionId:Xe,connectionType:"",mode:"database",selectedEntities:[]}:Dp,nt=!(ke&&(!Ke||(Ve==null?void 0:Ve.provenance)==="card-config"||(Ve==null?void 0:Ve.provenance)==="query_spec")),Me=nt?Xxt(ee):"",Ee=nt?_e:"",We={id:p.v4(),title:Ce||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:te==="horizontalBar"?"y":"x"},...Ke&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:te,sql:Me,python:Ee,dataSource:Pe,config:De,connectionId:Xe,visualizationMode:ze,dynamicCardPreferences:Ve,customCardPreferences:Ye?{url:Ye.url,componentName:Ye.componentName,pluginChartType:Ye.pluginChartType,settings:Ye.settings,type:"component"}:void 0},vt={id:p.v4(),cards:[We],activeCardId:We.id};try{await D(j,vt,"end"),T(!0),E(vt.id)}catch(yt){console.error("Failed to add assistant visual to dashboard:",yt),tt.error(yt instanceof Error?yt.message:"Failed to prepare semantic metadata for the new visual")}}const ie=ee=>{ee.preventDefault();const Ce=fe.trim();if(!Ce&&z.length===0)return;const ve=[];Ce&&ve.push({type:"text",text:Ce}),z.forEach(te=>{te.data&&ve.push({type:"file",mediaType:te.type,filename:te.name,url:`data:${te.type};base64,${te.data}`})}),M({role:"user",parts:ve}),ue(""),R("dashboard"),G()};S.useEffect(()=>{var ee;e&&((ee=_.current)==null||ee.focus())},[e]),yue({assistantType:"dashboard",status:B,isLoading:K,sendMessage:M});const{hasActiveTools:ae,activeToolText:se}=vue(L);function Ie(ee){const Ce={role:"user",parts:[{type:"text",text:ee.title+" "+ee.subtitle}]};M(Ce),G()}function oe(ee){M({role:"user",parts:[{type:"text",text:ee}]}),G()}function me(ee){M({role:"user",parts:[{type:"text",text:ee}]}),G()}const we=S.useCallback(async()=>{const ee=JSON.stringify(L??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ee),tt.success("Conversation copied")}catch(Ce){console.error("Failed to copy conversation",Ce),tt.error("Unable to copy conversation")}},[L]),ge=(fe==null?void 0:fe.length)===0&&(L==null?void 0:L.filter(ee=>ee.role==="user").length)===0;function re(){return c.jsx("div",{"data-role":"header",className:"flex items-center gap-2",children:c.jsx("span",{className:"text-[13px] font-medium text-foreground",children:"Assistant"})})}function ne(){return c.jsxs(po,{children:[c.jsx(go,{asChild:!0,children:c.jsx(ec,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(ch,{className:"size-3.5"})})}),c.jsxs(Ks,{align:"end",children:[c.jsx(tc,{children:"Options"}),c.jsx(fa,{}),c.jsx(Lc,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Lc,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Lc,{checked:u,onCheckedChange:d,children:"System Message"}),(C||N)&&c.jsxs(c.Fragment,{children:[c.jsx(fa,{}),c.jsx(tc,{children:"Dynamic Visuals"}),c.jsx(Lc,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),c.jsx(Lc,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),c.jsx(Lc,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const he=c.jsxs("div",{"data-role":"dashboard-assistant",className:p.cn("relative flex h-full grow flex-col break-words bg-background",v&&"rounded-card border border-border/60 shadow-xl"),children:[c.jsxs("header",{"data-role":"header-section",className:"flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3",children:[re(),O&&c.jsxs("button",{type:"button",onClick:O,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:[c.jsx("span",{className:"h-1 w-1 rounded-full bg-muted-foreground/60"}),c.jsx("span",{className:"max-w-[180px] truncate",children:(W==null?void 0:W.name)||"Default profile"})]}),c.jsxs("div",{"data-role":"header-actions",className:"ml-auto flex items-center gap-0.5",children:[N&&ne(),k&&c.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"}),c.jsx(ec,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:v?"Exit fullscreen":"Expand",onClick:J,children:v?c.jsx(wR,{className:"h-3.5 w-3.5"}):c.jsx(PN,{className:"h-3.5 w-3.5"})}),c.jsx(ec,{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 ee=L.filter(Ce=>Ce.role==="assistant").map(Ce=>Ce.id).filter(Ce=>!!Ce);$([]),P("dashboard"),q(),A(ee)},children:c.jsx(CR,{className:"h-3.5 w-3.5"})}),c.jsx(ec,{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:c.jsx(p.X,{className:"h-3.5 w-3.5"})})]})]}),c.jsx(Kde,{messages:L,showTools:a,showSystemMessage:u,onAddToDashboard:ye,onQuickReply:me,disableQuickReplies:K,status:B,errorMessage:F,activeToolText:K&&ae?se:void 0,className:p.cn(v?"px-6 py-5":"px-3 py-3"),rowContentClassName:p.cn(v&&"mx-auto w-full max-w-[680px]"),latestButtonClassName:e?"bottom-[148px]":"hidden",scrollToEndSignal:y}),c.jsxs("div",{className:"shrink-0 space-y-2 border-t border-border/60 px-3 pb-3 pt-2",children:[!W&&ge&&c.jsx(Fle,{onClick:Ie,placeholders:Qxt}),ge&&W&&c.jsx(rue,{seedQuestions:W.seedQuestions||[],handleSeedQuestionClick:oe}),c.jsx(xue,{assistantType:"dashboard"}),c.jsx(GL,{ref:_,setInput:ue,stop:V,input:fe,handleInputChange:pe,handleSubmit:ee=>{ie(ee)},isLoading:K,status:B,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(YL,{incomingSelectedEntities:Z,open:m,onOpenChange:g,dataSource:U||Dp,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:ee=>Y()})]});return v&&s?fr.createPortal(c.jsx(Sg,{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:c.jsx("div",{className:"flex h-full w-full",children:he})}),s):he}function eyt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=p.useDashboardActions(),s=uoe(),o=p.useDashboardStore(d=>d.dashboard.sheets),a=p.useDashboardStore(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=p.useDashboardStore(d=>d.isDashboardEditing),u=p.useDashboardStore(d=>d.isVisualEditing);S.useEffect(()=>{if(!l||u)return;async function d(m){if(tyt(m.target))return;const g=m.ctrlKey||m.metaKey;g&&m.key==="c"?(await f(),tt.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=nyt(m);if(g!=null&&g.id){const b=aoe(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await s(a,b),r(b.id),tt.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)},[s,n,r,a,l,u,t])}function tyt(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 nyt(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 ryt(e,t){switch(e.interactionMode){case"drillToDetail":syt(e,t);break;case"drillThrough":oyt(e,t);break;case"drillToURL":iyt(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 syt(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function oyt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function iyt(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 ayt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(yo,{open:e,onOpenChange:t,children:c.jsxs(Js,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Bi,{children:[c.jsx(eo,{children:i||"Insight Detail"}),c.jsx(Bo,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(hoe,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(joe,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function lyt(){const e=p.useInteractionStore(C=>C.interactionStates),t=p.useInteractionStore(C=>C.setInteractionState),n=p.useInteractionStore(C=>C.clearLastInteractionEvent),r=p.useInteractionStore(C=>C.replaceCardWithInsight),s=p.useInteractionStore(C=>C.setPendingDrillThrough),o=p.useInteractionStore(C=>C.pendingDrillThrough),i=p.useInteractionStore(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=p.useDashboardActions(),{selectDashboard:u}=ah(),d=p.useDashboardStore(C=>C.dashboard),f=p.useDashboardStore(C=>C.filterValues),{data:h,isLoading:m}=qW((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[g,b]=S.useState({open:!1,insightId:""}),x=Eoe(g.insightId,{enabled:g.open&&!!g.insightId}),y=S.useRef(new Set),w=S.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:N,contextMode:k})=>{b({open:!0,insightId:C,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:k})},replaceCardContent:({cardId:C,insightId:N,filters:k,contextMode:_})=>{r(C,N,k,_)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:j})=>{const I={filters:C},E={sourceCardId:p.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[I]},T={...p.createInitialInteractionState(),appliedClickFilters:[E],contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:j};t(p.DRILL_CONTEXT_CARD_ID,T)}}),[a,r,f,l,d,s,t]);S.useEffect(()=>{Object.entries(e).forEach(([C,N])=>{if(N!=null&&N.lastInteractionEvent){const k=N.lastInteractionEvent,_=`${C}-${k.interactionMode}-${k.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{ryt(k,w)}catch(j){console.error("Error executing interaction event:",j)}finally{n(C),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,w]),S.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,m,u,l,i]);const v=()=>{b({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(ayt,{open:g.open,onOpenChange:v,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[c.jsx(p.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),c.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function cyt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=uyt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function uyt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function dyt(e){return e?`Back to ${e}`:"Back"}function fyt(){var y,w,v,C,N;const e=p.useInteractionStore(k=>k.interactionStates[p.DRILL_CONTEXT_CARD_ID]),t=p.useDashboardStore(k=>k.actions.goBackFromDrill),n=p.useDashboardStore(k=>k.actions.clearDrillContext),{selectDashboard:r}=ah(),[s,o]=S.useState({x:16,y:16}),[i,a]=S.useState(!1),l=S.useRef({x:0,y:0});S.useEffect(()=>{if(!i)return;const k=j=>{o({x:j.clientX-l.current.x,y:j.clientY-l.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",k),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",k),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(v=(w=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:w.filterGroups)==null?void 0:v[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(k){console.error("[DrillBack] Error during back navigation:",k)}},g=()=>{n()},b=k=>{k.target.closest("button")||(a(!0),l.current={x:k.clientX-s.x,y:k.clientY-s.y})};cyt(f);const x=dyt(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:b,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((k,_)=>{const j=k.field.label||k.field.name,I=String(k.value);return c.jsxs(rs,{variant:"secondary",className:"pointer-events-none text-xs",children:[j," = ",I]},_)})})]}),c.jsx(p.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(p.X,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(p.Button,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(f0,{className:"mr-2 h-4 w-4"}),x]})})]})})}function hyt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function myt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:l,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:m,transition:g,isDragging:b}=Ig({id:`filter:${e.id}`,disabled:n||!t}),x={transform:di.Translate.toString(m),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return c.jsx("div",{ref:h,style:x,...d,children:c.jsx(m5,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:l,onRemoveFilter:u})})}const dU="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",pyt=[];function Zde({open:e,onOpenChange:t}){var L,$,B;const[n,r]=S.useState(!1),[s,o]=S.useState(!1),[i,a]=S.useState({sheetSelection:"current",protectPdf:!1,password:""}),l=p.useDashboardStore(V=>{var F;return(F=V.dashboard)==null?void 0:F.sheets}),u=p.useDashboardStore(V=>V.dashboard),d=p.useDashboardStore(V=>V.dashboardInputValues),f=p.useDashboardStore(V=>V.filterValues),h=p.useDashboardStore(V=>V.controlValues),m=p.useDashboardStore(V=>V.inlineFilterValuesMap),g=p.useDashboardStore(V=>V.cardControlValuesMap),b=p.useDashboardStore(V=>V.selectedSheetId),x=p.useDashboardStore(V=>V.selectedSheetId?V.documentInputRuntimeBySheetId[V.selectedSheetId]:void 0),y=p.useDashboardStore(V=>V.isDownloadingPdf),{authToken:w,tokenProps:v}=mt(),C=l==null?void 0:l.find(V=>V.id===b),N=S.useMemo(()=>p.getDashboardExportSheets(l),[l]),k=p.isDocumentSheet(C),_=k&&C?C.document:void 0,j=S.useMemo(()=>k&&C?kv(u,C.id):[],[C,k,u]),I=j.length>0,E=S.useMemo(()=>k&&C?ule(u,C.id):!1,[C,k,u]),T=S.useMemo(()=>I?j.map(_v):(_==null?void 0:_.inputs)||pyt,[_,j,I]),D=(($=(L=v==null?void 0:v.params)==null?void 0:L.calendarContext)==null?void 0:$.tz)||((B=v==null?void 0:v.params)==null?void 0:B.timezone)||(typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),A=S.useMemo(()=>uae(T),[T]),P=S.useMemo(()=>lae(T,D),[T,D]),R=S.useMemo(()=>cae(T),[T]),H=x?x.filterValuesByInputId:P,z=x?x.controlValuesByInputId:R,U=S.useMemo(()=>k?E&&C&&_?CK({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(V=>V.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},timezone:D}):hae(T,H,z,A,A):[],[_,T,C,k,u,g,h,f,m,d,z,H,A,D,E]),W=!!C,O=N.length>0,Z=((l==null?void 0:l.length)||0)>1||k,Y=i.sheetSelection==="current"&&(!W||k&&U.length>0)||i.sheetSelection==="all"&&!O;S.useEffect(()=>{e&&i.sheetSelection==="all"&&!O&&a(V=>({...V,sheetSelection:"current"}))},[O,e,i.sheetSelection]);const M=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function K(){if(y){tt.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){tt.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!W){tt.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!O){tt.error("No dashboard sheets are available to export");return}o(!0);const V=i.sheetSelection==="current"&&k,F=V?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",q=tt.loading(F);try{if(V){if(!_||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){tt.dismiss(q),tt.error(`Set ${U.join(", ")} before exporting`);return}const X=new Date().toISOString(),J=E?kK({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(fe=>fe.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},generatedAt:X,timezone:D}).snapshot:void 0;await RF(v.apiServiceUrl,w,{sheetId:C.id,title:C.title||"Document",pageSize:_.page.size,orientation:_.page.orientation,timezone:D,password:i.protectPdf?i.password:void 0,inputSnapshot:J,...J?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:H,controlValuesByInputId:z,generatedAt:X}}})}else{const X=JQ();await MK(v.apiServiceUrl,w,i.protectPdf?i.password:void 0,i.sheetSelection,X)}tt.dismiss(q);const G=V?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!";tt.success(G,{duration:2e3}),M()}catch(G){tt.dismiss(q),tt.error("Failed to download PDF",{description:xk(G,"Please try again or contact support."),descriptionClassName:bk,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",G)}finally{o(!1)}}return c.jsx(yo,{open:e,onOpenChange:V=>{if(!V){M();return}t(!0)},children:c.jsxs(Js,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[c.jsxs(Bi,{children:[c.jsx(eo,{className:"text-[15px]",children:k?"Export document":"Export dashboard"}),c.jsx(Bo,{className:"text-[13px] leading-5",children:k?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),c.jsxs("div",{className:"space-y-4 py-1",children:[Z&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:dU,children:"Export scope"}),c.jsxs(ma,{value:i.sheetSelection,onValueChange:V=>a({...i,sheetSelection:V}),className:"gap-1.5",children:[c.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",!W&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[c.jsx(ps,{value:"current",id:"scope-current",disabled:!W}),k?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),c.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",!O&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[c.jsx(ps,{value:"all",id:"scope-all",disabled:!O}),"Dashboard sheets (",N.length," ",N.length===1?"sheet":"sheets",")"]})]}),k&&c.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:U.length>0?`Set ${U.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),c.jsx(p.Separator,{className:"bg-border/60"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs(p.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[c.jsx(En,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:V=>{a({...i,protectPdf:V,password:V?i.password:""}),V||r(!1)}}),c.jsx(FN,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&c.jsxs("div",{className:"ml-6 space-y-1.5",children:[c.jsx(p.Label,{htmlFor:"pdf-password",className:dU,children:"Password"}),c.jsxs("div",{className:"relative",children:[c.jsx(p.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:V=>a({...i,password:V.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:V=>{V.key==="Enter"&&i.password&&K()}}),c.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?c.jsx(RN,{className:"h-3.5 w-3.5"}):c.jsx(h0,{className:"h-3.5 w-3.5"})})]}),c.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),c.jsxs(vc,{children:[c.jsx(p.Button,{variant:"outline",size:"xs",onClick:M,disabled:s,children:"Cancel"}),c.jsx(p.Button,{size:"xs",onClick:K,disabled:s||y||Y,children:s?c.jsxs(c.Fragment,{children:[c.jsx(p.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):c.jsxs(c.Fragment,{children:[c.jsx(xc,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function Xde({iconClassName:e,open:t,onOpenChange:n}){const[r,s]=S.useState(!1),o=t!==void 0,i=o?t:r,a=u=>{o||s(u),n==null||n(u)},l=p.useDashboardStore(u=>u.isDownloadingPdf);return c.jsxs(c.Fragment,{children:[o?null:c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:l,onClick:()=>a(!0),children:c.jsx(xc,{className:p.cn("size-4",e)})}),c.jsx(Zde,{open:i,onOpenChange:a})]})}function fU(e,t,n){const r=new Set(t),s=[...n];return e.map(o=>r.has(o.id)?s.shift()??o.id:o.id)}function gyt({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:l,isDragging:u}=Ig({id:`control:${e.id}`,disabled:!n}),d={transform:di.Translate.toString(a),transition:l,opacity:u?.5:1,zIndex:u?10:void 0};return c.jsx("div",{ref:i,style:d,...s,children:c.jsx(jae,{control:e,value:t,isEditing:n,dragListeners:n?o:void 0,onChange:r})})}function hU(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function mU(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function byt(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 mU(t,n);const s=e.filter(a=>r.has(a)),o=new Set(s),i=mU(t,n).filter(a=>!o.has(a));return[...s,...i]}function xyt(e,t){return p.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function yyt(e){return op(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>op(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function pU(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function vyt(e){const t={sheetId:e.selectedSheetId},n=p.getDashboardInputRuntimeSlot(e.dashboardInputValues,e.dashboardInput,t);if(n)return n;const r=p.getDashboardInputRuntimeSlot(e.defaultInputValues,e.dashboardInput,t);return r||p.getBackingDefaultSlot(e.dashboardInput)}function wyt(e){return Qde(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 Qde(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=xyt(e.dashboard,t);return HG(uk({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!yyt({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function Syt(e,t){return"toolbar"}function Cyt(){const e=Sc("interactive"),t=p.useDashboardStore($=>$.selectedSheetId),n=p.useDashboardStore($=>$.dashboard.filters),r=p.useDashboardStore($=>$.dashboard.filterLayout),s=p.useDashboardStore($=>$.isDashboardEditing),o=p.useDashboardStore($=>$.controlValues),i=p.useDashboardStore($=>$.filterValues);p.useDashboardStore($=>$.filteringCards);const a=p.useDashboardStore($=>$.inlineFilterValuesMap),l=p.useDashboardStore($=>$.dashboardInputValues),u=p.useInteractionStore($=>$.clearAllClickFilters),d=p.useInteractionStore($=>Object.entries($.interactionStates).reduce((B,[V,F])=>{var q;return V===p.DRILL_CONTEXT_CARD_ID?B:B+(((q=F.appliedClickFilters)==null?void 0:q.length)??0)},0)),f=p.useDashboardStore($=>$.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:m,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:w,setFilteringCards:v,upsertDashboardInput:C}=p.useDashboardActions(),N=F_(Ep(jg,{activationConstraint:{distance:5}})),k=p.useDashboardStore($=>$.dashboard),_=wyt({dashboard:k,selectedSheetId:t}).filter($=>Syt($.filter)==="toolbar"),j=Qde({dashboard:k,selectedSheetId:t}),I=_.map($=>$.filter),E=new Map(_.map($=>[`filter:${$.filter.id}`,$])),T=DWe(k),D=T.filter($=>!$.hidden&&Ay($)==="toolbar"),A=T.filter($=>!$.hidden&&Ay($)==="advanced"),P=byt(r==null?void 0:r.toolbarItemOrder,I,D),R=new Map(I.map($=>[`filter:${$.id}`,$])),H=new Map(D.map($=>[`control:${$.id}`,$]));function z($){const{active:B,over:V}=$;if(!V||B.id===V.id)return;const F=String(B.id),q=String(V.id),G=P.findIndex(ae=>ae===F),X=P.findIndex(ae=>ae===q);if(G===-1||X===-1)return;const J=Eg(P,G,X);y({toolbarItemOrder:J});const fe=new Set((n||[]).map(ae=>ae.id)),ue=P.filter(ae=>ae.startsWith("filter:")).map(ae=>ae.replace("filter:","")).filter(ae=>fe.has(ae)),pe=J.filter(ae=>ae.startsWith("filter:")).map(ae=>ae.replace("filter:","")).filter(ae=>fe.has(ae)),ye=P.filter(ae=>ae.startsWith("control:")).map(ae=>ae.replace("control:","")),ie=J.filter(ae=>ae.startsWith("control:")).map(ae=>ae.replace("control:",""));h(fU(n||[],ue,pe)),g(fU(k.controls||[],ye,ie))}const U=(r==null?void 0:r.toolbarWrap)??!1,W=(r==null?void 0:r.showDownloadButton)??!1,O=(i==null?void 0:i.filter($=>hU($)).length)??0,Z=j.filter(pU),Y=Z.filter($=>{const B=vyt({dashboardInput:$,dashboardInputValues:l,defaultInputValues:k.defaultInputValues,selectedSheetId:t});return(B==null?void 0:B.status)==="set"&&B.value.kind==="filter"&&hU(B.value.filterValue)}).length,M=a?Object.values(a).reduce(($,B)=>$+((B==null?void 0:B.length)??0),0):0,K=O+Y+M+d,L=()=>{w([]),Z.forEach($=>{m($,{sheetId:t})}),v([]),u(),a&&Object.entries(a).forEach(([$,B])=>{B==null||B.forEach(V=>{f($,V.filterId)})})};return!I.length&&!D.length&&!A.length&&!W&&K===0?null:c.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:c.jsx(yv,{sensors:N,collisionDetection:gv,onDragEnd:z,children:c.jsxs("div",{className:p.cn("flex items-center",U?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[c.jsx(vv,{items:P,strategy:H5,children:c.jsx(kA,{className:"gap-3 pr-0",wrap:U,children:P.map($=>{const B=R.get($);if(B){const F=E.get($),q=F&&pU(F);return c.jsx(myt,{filter:B,isEditing:s,storageOptions:q?{storageTarget:"dashboardInput",dashboardInput:F,sheetId:t??void 0}:void 0,inputVariableName:q?F.variableName:void 0,onUpdateFilter:q?(G,X)=>{C({...F,variableName:(X==null?void 0:X.variableName)||F.variableName,filter:G})}:void 0,onRemoveFilter:q?()=>{w((i||[]).filter(G=>G.filterId!==B.id)),b(F.id)}:void 0},$)}const V=H.get($);return V?c.jsx(gyt,{control:V,value:o==null?void 0:o[V.id],isEditing:s,onChange:F=>x(V.id,F)},$):null})})}),A.length>0&&c.jsx(Soe,{title:"",controls:A,values:o,onChange:($,B)=>x($.id,B),immediatePlacement:"toolbar",advancedLabel:"More controls"}),K>0&&c.jsxs("button",{type:"button",onClick:L,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[c.jsx(p.X,{className:"h-3 w-3"}),"Clear all",c.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:K})]}),W&&c.jsx("div",{className:p.cn(K>0?"ml-1.5":"ml-auto"),children:c.jsx(Xde,{})})]})})})}function Jde(){var ne,he;const{showAssistant:e,tokenProps:t,renderMode:n}=mt(),r=hyt((ne=t.config)==null?void 0:ne.showDashboardAssistant,e),{preferences:s,isConsoleMode:o}=Pp(),i=(he=s==null?void 0:s.cardDisplay)==null?void 0:he.mode,a=bh(i),l=aK({displayMode:i,renderMode:n}),u=S.useRef(null),d=S.useRef(null),[f,h]=S.useState(!1),{handleDragStart:m,isDraggingRef:g,getStyle:b,getPositionClasses:x}=irt({initialPosition:"bottom-right"}),y=hf(ee=>ee.setFullscreen),w=hf(ee=>ee.setPanelOpen),v=hf(ee=>ee.setContainer),C=ZY("dashboard"),N=XY(),k=QY("dashboard"),_=C.isOpen,j=N==="dashboard",I=p.useDashboardStore(ee=>ee.isVisualEditing),E=p.useDashboardStore(ee=>ee.themeStyle),T=dl(),D=p.useDashboardStore(ee=>{var Ce;return(Ce=ee.dashboard)==null?void 0:Ce.sheets}),A=p.useDashboardStore(ee=>ee.showFilters),P=p.useDashboardStore(ee=>ee.isDashboardEditing),R=p.useDashboardStore(ee=>ee.selectedSheetId),H=D==null?void 0:D.find(ee=>ee.id===R),z=p.useDashboardStore(ee=>{var Ce,ve,te;return(te=(ve=(Ce=ee.dashboard)==null?void 0:Ce.sheets)==null?void 0:ve.find(_e=>_e.id===ee.selectedSheetId))==null?void 0:te.kind}),U=p.useDashboardStore(ee=>{var Ce,ve;return((ve=(Ce=ee.dashboard)==null?void 0:Ce.summary)==null?void 0:ve.position)||"top"}),W=z==="document",O=p.useDashboardStore(ee=>{var Ce;return(Ce=ee.dashboard)==null?void 0:Ce.id}),Z=p.useDashboardStore(ee=>ee.isDashboardPanelOpen),Y=p.useDashboardStore(ee=>ee.actions.setIsDashboardPanelOpen),{getDefaultSheetId:M,setDefaultSheetId:K,clearDefaultSheetId:L}=eq(O),[$,B]=S.useState(null);UN($r.DASHBOARD);const{setSelectedSheetId:V,setSheetTitle:F,addSheet:q,setSheets:G}=p.useDashboardActions();eyt(d);const{setActiveAssistantType:X}=p.useAIActions();S.useEffect(()=>{if(O){const ee=M();B(ee)}},[O,M]),S.useEffect(()=>{_?X("dashboard"):N==="dashboard"&&y(null)},[_,X,N,y]),S.useEffect(()=>{var ee;_||(ee=u.current)==null||ee.resize(0)},[_]);function J(ee){var Ce,ve;ee?((Ce=u.current)==null||Ce.resize(40),w("dashboard",!0),y("dashboard"),X("dashboard")):(w("dashboard",!1),y(null),(ve=u.current)==null||ve.resize(0),X(null))}function fe(ee="dashboard"){const Ce={id:p.v4(),title:ee==="document"?"New Document":"New Sheet",...ee==="document"?{kind:ee,document:p.createDefaultDocumentDefinition()}:{}};q(Ce),V(Ce.id)}function ue(ee,Ce){if(!O)return;$===ee?(L(),B(null),tt.success("Default sheet cleared")):(K(ee),B(ee),tt.success(`"${Ce}" set as default sheet`))}function pe(ee){var Ce;ee<1?(w("dashboard",!1),y(null),X(null),(Ce=u.current)==null||Ce.resize(0)):(_||w("dashboard",!0),X("dashboard"))}function ye(){return(E==null?void 0:E.canvasTheme)==="muted"||!(E!=null&&E.canvasTheme)?"hsl(var(--semaphor-muted))":(E==null?void 0:E.canvasTheme)==="clear"?"":E==null?void 0:E.canvasTheme}const ie=(ee,Ce)=>{ee.dataTransfer.setData("tabIndex",Ce.toString())},ae=ee=>{ee.preventDefault()},se=(ee,Ce)=>{const ve=ee.dataTransfer.getData("tabIndex");if(ve===Ce.toString())return;const te=Array.from(D||[]),[_e]=te.splice(parseInt(ve),1);te.splice(Ce,0,_e),G(te)},Ie=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,oe=r===!0&&!a&&!_&&!I&&!A;function me(){if(D&&D.length>1||P)return c.jsxs("div",{className:"relative flex w-full items-stretch border-b border-border",children:[o&&Ie&&!Z&&c.jsx("button",{type:"button","aria-label":"Toggle dashboards panel",onClick:()=>{Y(!Z)},className:"group/panel mx-2 inline-flex h-9 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",children:c.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-[4px] group-hover/panel:bg-muted",children:c.jsx(Dq,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),c.jsxs("div",{className:"relative min-w-0 flex-1",children:[c.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"}),c.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"}),c.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:[D==null?void 0:D.map((ee,Ce)=>{const ve=R===ee.id,te=$===ee.id;return c.jsxs(p.TabsTrigger,{draggable:!0,onDragStart:_e=>ie(_e,Ce),onDragOver:ae,onDrop:_e=>se(_e,Ce),onClick:()=>V(ee.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:ee.id,children:[ee.kind==="document"&&c.jsx(oi,{className:"h-3 w-3 text-muted-foreground"}),c.jsx(UC,{enabled:P&&ve,text:ee.title,onSave:_e=>F(ee.id,_e),children:ee.title},ee.id),c.jsx("span",{role:"button",tabIndex:0,"aria-label":te?"Clear default sheet":"Set as default sheet",title:te?"Clear default sheet":"Set as default sheet",onClick:_e=>{_e.stopPropagation(),ue(ee.id,ee.title||"Sheet")},onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),_e.stopPropagation(),ue(ee.id,ee.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",ve||te?"opacity-100":"opacity-0 group-hover:opacity-100"),children:c.jsx(kR,{className:p.cn("h-3 w-3 transition-colors",te?"fill-current text-amber-500":"text-muted-foreground")})}),P&&ve&&D.length>1&&c.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:_e=>{_e.stopPropagation(),h(!0)},onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),_e.stopPropagation(),h(!0))},children:c.jsx(p.X,{className:"h-3 w-3"})})]},ee.id)}),P&&c.jsxs(po,{children:[c.jsx(go,{asChild:!0,children:c.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:[c.jsx(wr,{className:"h-3 w-3"}),"Sheet"]})}),c.jsxs(Ks,{align:"start",className:"w-48",children:[c.jsxs(bn,{onSelect:()=>fe("dashboard"),children:[c.jsx(ep,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),c.jsxs(bn,{onSelect:()=>fe("document"),children:[c.jsx(oi,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})]})}function we(){return c.jsx("div",{ref:d,style:{},className:"h-full min-h-0 grow",children:D==null?void 0:D.map(ee=>c.jsx(p.TabsContent,{style:{backgroundColor:ye(),...T.dashboardCanvasStyle},className:p.cn("mt-0 h-full min-h-0",{}),value:ee.id,children:c.jsx(l7,{sheet:ee})},ee.id))})}function ge(){return c.jsxs(p.Tabs,{"data-role":"dashboard-tabs-container",className:p.cn("relative flex h-full flex-col",E==null?void 0:E.dashboardTabsContainer),onValueChange:ee=>{V(ee)},value:R||void 0,children:[me(),U==="top"&&!W&&c.jsx(oA,{}),R&&!W&&c.jsx(Cyt,{}),W?c.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:we()}):c.jsx(bl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:we()}),U==="bottom"&&!W&&c.jsx(oA,{}),c.jsx(art,{open:f,setOpen:h})]})}const re=S.useCallback(ee=>{v("dashboard",ee)},[v]);return D?l&&R&&!W?c.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',R,'" was not found or is not a document sheet in the loaded dashboard.']}):l&&W&&H?c.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:c.jsx(l7,{sheet:H})}):c.jsxs(c.Fragment,{children:[c.jsx(lyt,{}),c.jsx(fyt,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(Rle,{className:p.cn("flex-1 basis-0 overflow-y-auto transition-opacity",j&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(TA,{children:ge()}),r===!0&&c.jsxs(c.Fragment,{children:[c.jsx(ort,{open:_,onTabClick:J,withHandle:!0,disabled:!_}),c.jsx(TA,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:pe,defaultSize:_?40:0,ref:u,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(Jxt,{open:_,setOpen:J,isFullscreen:j,onFullscreenChange:ee=>y(ee?"dashboard":null),fullscreenContainer:k})})})]})]}),c.jsx("div",{ref:re,className:p.cn("absolute inset-0",!j&&"pointer-events-none")}),oe&&c.jsx("div",{className:p.cn("absolute z-50 transition-all duration-300 ease-in-out",x().horizontal,x().vertical),style:b(),children:c.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:()=>{g.current||J(!0)},onMouseDown:m,onTouchStart:m,title:"Open Assistant (drag to move)",children:c.jsx(zme,{className:"h-5 w-5"})})})]})]}):null}const efe=S.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:s,children:o,className:i,style:a,...l},u)=>{const d=S.useId(),f=S.useMemo(()=>Nyt(d),[d]),{theme:h}=lR(),m=kyt(h),g=S.useMemo(()=>s??bc.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,s,n]),b=S.useMemo(()=>p.compileAppearance({spec:g,systemMode:m}),[g,m]),x=S.useMemo(()=>p.createAppearanceContextValue(f,b),[b,f]);return c.jsx(p.AppearanceContext.Provider,{value:x,children:c.jsx(Sg,{...l,ref:u,className:i,style:a,children:o})})});efe.displayName="AppearanceProvider";function Nyt(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function kyt(e){const t=S1(e),[n,r]=S.useState(()=>_yt());return S.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const s=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!s)return;const o=()=>{r(s.matches?"dark":"light")};return o(),typeof s.addEventListener=="function"?(s.addEventListener("change",o),()=>s.removeEventListener("change",o)):((a=s.addListener)==null||a.call(s,o),()=>{var l;return(l=s.removeListener)==null?void 0:l.call(s,o)})},[t]),t==="system"?n:t}function _yt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const tfe=S.createContext({openBrandStudioPreview:()=>{}}),jyt=tfe.Provider;function Eyt(){return S.useContext(tfe)}function Iyt({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const s=S1(t),[o,i]=S.useState(()=>Tyt(n)||s),a=S.useCallback(u=>{const d=S1(u);Dyt(n,d),i(d)},[n]),l=S.useMemo(()=>({theme:o,setTheme:a}),[o,a]);return c.jsx(MU.Provider,{...r,value:l,children:e})}function Tyt(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=S1(t,"system");return n===t?n:null}catch{return null}}function Dyt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const Myt=S.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function b3({appearance:e,children:t}){var T,D;const{authToken:n,id:r,tokenProps:s}=mt(),o=u0(),i=(T=o.data)==null?void 0:T.organizationAppearance,a=(D=s.config)==null?void 0:D.appearance,[l,u]=S.useState(!1),[d,f]=S.useState(null),[h,m]=S.useState(null),[g,b]=S.useState(null),[x,y]=S.useState(null),w=`${s.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,v=jn({queryKey:zW({resourceType:$r.DASHBOARD,apiServiceUrl:s.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>p.getRequest(`${s.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:A=>(A==null?void 0:A.organizationAppearance)??null,enabled:!o.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});S.useEffect(()=>{i!==void 0&&y({scopeKey:w,appearance:i})},[i,w]),S.useEffect(()=>{v.data!==void 0&&y({scopeKey:w,appearance:v.data})},[v.data,w]);const C=(x==null?void 0:x.scopeKey)===w?x.appearance:null,N=i!==void 0?i:v.data!==void 0?v.data:C,k=S.useMemo(()=>bc.resolveAppearance({organizationAppearance:N,tokenAppearance:a,reactAppearance:e}),[e,N,a]),_=S.useCallback(()=>{f(g??h??k),u(!0)},[g,h,k]),j=S.useCallback(()=>{u(!1)},[]);S.useEffect(()=>{f(null),m(null),b(null),u(!1)},[r]);const I=S.useMemo(()=>({openBrandStudioPreview:_}),[_]),E=g??h??e;return c.jsx(Iyt,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(jyt,{value:I,children:c.jsx(efe,{organizationAppearance:N,tokenAppearance:a,reactAppearance:E,style:{height:"100%",width:"100%"},children:c.jsxs(p.TooltipProvider,{delayDuration:0,children:[t,l&&c.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:c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:c.jsx(Myt,{appearance:d,onDraftChange:b,onSave:A=>{m(A),b(A),f(A)},onCancel:j})})})]})})})})}function nfe({children:e,preferences:t}){const{currentUser:n}=zi(),r=S.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(OW.Provider,{value:r,children:c.jsx(I_,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Ayt(e=2e3,t=500){const n=Jhe(),[r,s]=S.useState(!1),[o,i]=S.useState(!1),a=S.useRef(null);return S.useEffect(()=>{const l=setTimeout(()=>s(!0),e);return()=>clearTimeout(l)},[e]),S.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function x3({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=Ayt(e,t);return S.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),c.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function rfe(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(ba,{FallbackComponent:j_,children:c.jsxs(mR,{dashboardProps:e,children:[c.jsx(x3,{componentType:"dashboard",componentId:e.id}),c.jsx(b3,{appearance:e.appearance,children:c.jsx(nfe,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(qR,{...e,type:"dashboard",children:c.jsx(Jde,{})})})})})]})})}function Ryt(e=[]){const t=S.useRef(null),n=S.useRef(null),r=S.useRef(null),[s,o]=S.useState(),i=S.useCallback(()=>{var m,g,b;const a=((m=t.current)==null?void 0:m.clientWidth)??0,l=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-l-u-8,h=Math.max(f,0);o(x=>x===h?x:h)},[]);return S.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const l=new ResizeObserver(()=>i());return l.observe(a),i(),()=>l.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function Fyt({filter:e}){var g;const t=p.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=Pp(),r=bh((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),s=p.useDashboardStore(b=>b.filterValues),o=s==null?void 0:s.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:l}=p.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:m}=Ryt([t,o,r]);return S.useEffect(()=>{m()},[e.title,m]),c.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[c.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[c.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:c.jsx(p.Label,{className:"my-1 block w-full text-sm",children:c.jsx(Oo,{value:e.title||e.column,onSave:b=>l({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),c.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&c.jsx(h5,{filter:e,isEditing:t}),t&&c.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:c.jsx(p.X,{className:"size-3.5"})})]})]}),c.jsx("div",{className:"hidden",ref:f})]})}function Pyt(){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?c.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=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(Fyt,{filter:r}),c.jsx(v_,{filter:r})]},r.id))}):null}function Oyt(){var i;const e=p.useDashboardStore(a=>a.dashboard),t=p.useDashboardStore(a=>a.selectedSheetId),n=p.useDashboardStore(a=>a.isVisualEditing),r=p.useDashboardStore(a=>a.isDashboardEditing),s=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),o=p.isDocumentSheet(s);return c.jsx("div",{role:"dashboard-plus-main",className:p.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:c.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!o&&c.jsx(Pyt,{}),c.jsx(Jde,{})]})})}const Lyt=S.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-CGt6_hMf.js"))),$yt=S.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-w6hKbjlw.js"))),zyt=S.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-CYSbOdmE.js"))),Byt=S.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-Bf8-3eUf.js")).then(e=>({default:e.ResourceManagementPanel})));function Vyt({showControls:e=!1,showFooter:t=!0,...n}){const r=p.useDashboardStore(u=>u.isDashboardPanelOpen),s=p.useDashboardStore(u=>u.isVisualEditing),o=p.useDashboardStore(u=>u.showDashboardJSON),i=p.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{appearance:a,preferences:l}=n;return c.jsx(ba,{FallbackComponent:j_,children:c.jsxs(mR,{dashboardProps:n,children:[c.jsx(x3,{componentType:"surfboard",componentId:n.id}),c.jsxs(b3,{appearance:a,children:[c.jsx(qge,{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"}}}),c.jsxs(nfe,{preferences:l,children:[o&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(zyt,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(Lyt,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(Byt,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(qR,{...n,type:"dashboard",children:[s&&c.jsx(S.Suspense,{fallback:null,children:c.jsx($yt,{})}),c.jsx(Oyt,{})]})})]})]})]})]})]})})}var Hyt=Object.defineProperty,Uyt=(e,t,n)=>t in e?Hyt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,jS=(e,t,n)=>Uyt(e,typeof t!="symbol"?t+"":t,n);const qyt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Wyt={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}},Yyt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Gyt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function sfe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Kyt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=sfe(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Zyt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Xyt={stringify:e=>e,parse:e=>e},bD={string:Xyt,number:Zyt,boolean:qyt,function:Wyt,method:Kyt,json:Yyt},jb=Symbol.for("r2wc.render"),ES=Symbol.for("r2wc.connected"),Nd=Symbol.for("r2wc.context"),Yo=Symbol.for("r2wc.props");function Qyt(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const g=Gyt(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(),jS(this,o,!0),jS(this,s),jS(this,r,{}),jS(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Yo].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=l[g],w=y?bD[y]:null;if(y==="method"){const v=sfe(b);Object.defineProperty(this[Yo].container,v,{enumerable:!0,configurable:!0,get(){return this[Yo][v]},set(C){this[Yo][v]=C,this[jb]()}}),this[Yo][g]=w.parse(x,b,this)}w!=null&&w.parse&&x&&(this[Yo][g]=w.parse(x,b,this))}for(const g of a)this[Yo][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[ES]=!0,this[jb]()}disconnectedCallback(){this[ES]=!1,this[Nd]&&n.unmount(this[Nd]),delete this[Nd]}attributeChangedCallback(g,b,x){const y=f[g],w=l[y],v=w?bD[w]:null;y in l&&v!=null&&v.parse&&x&&(this[Yo][y]=v.parse(x,g,this),this[jb]())}[(o=ES,s=Nd,r=Yo,jb)](){this[ES]&&(this[Nd]?n.update(this[Nd],this[Yo]):this[Nd]=n.mount(this.container,e,this[Yo]))}}for(const m of i){const g=d[m],b=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Yo][m]},set(x){this[Yo][m]=x;const y=b?bD[b]:null;if(y!=null&&y.stringify){const w=y.stringify(x,g,this);this.getAttribute(g)!==w&&this.setAttribute(g,w)}else this[jb]()}})}return h}function Jyt(e,t,n){const r=Lfe.createRoot(e),s=S.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function e0t({root:e,ReactComponent:t},n){const r=S.createElement(t,n);e.render(r)}function t0t({root:e}){e.unmount()}function n0t(e,t={}){return Qyt(e,t,{mount:Jyt,update:e0t,unmount:t0t})}const r0t={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},s0t=n0t(rfe,{props:r0t}),o0t=S.memo(function({context:t="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(hL,{context:t})," "]})}),ofe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),i0t=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),a0t=Array.from(ofe).join(", "),l0t=3,c0t="Self-heal",u0t=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function d0t({card:e}){var W,O,Z,Y,M;const[t,n]=S.useState({}),{authToken:r}=mt(),s=p.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:o}=p.useAppearance(),i=S.useMemo(()=>av(o),[o]),a=p.useEditorStore(K=>K.frame),l=p.useEditorStore(K=>K.inlineFilterValuesMap[e.id]),u=p.useEditorStore(K=>K.actions.setCardInlineFilterValue),d=p.useEditorStore(K=>K.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:m}=Nh(((W=f.customCardPreferences)==null?void 0:W.url)||""),g=(O=m==null?void 0:m.visuals)==null?void 0:O.find(K=>{var L;return K.name===((L=f.customCardPreferences)==null?void 0:L.componentName)}),b=lv(f,g)??"single",x=S.useMemo(()=>x5({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=S.useMemo(()=>{const K=x.findIndex(L=>(L==null?void 0:L.id)===e.id);return K<0?-1:Iy(e,K)},[x,e]),w=S.useMemo(()=>b!=="multiple"||y<0?e.type:Am(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),v=S.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:w!==e.type?{...e,type:w}:e,[e,w,b]),{data:C}=pk(v),N=p.useInteractionStore(K=>K.interactionStates),k=p.useDashboardStore(K=>{var L;return(L=K.dashboard)==null?void 0:L.id}),_=p.useDashboardStore(K=>K.dashboard.filters),j=p.useDashboardStore(K=>K.filterValues),I=p.useDashboardStore(K=>K.selectedSheetId),E=S.useMemo(()=>p5({card:e,sheetId:I||"",inlineFilterValues:l,setInlineFilterValue:K=>u(e.id,K),removeInlineFilterValue:K=>d(e.id,K)}),[e,I,l,u,d]),{cardFilters:T,cardFilterValues:D}=S.useMemo(()=>k0({card:e,interactionStates:N,currentDashboardId:k,filters:_,filterValues:j,selectedSheetId:I}),[e,N,k,_,j,I]),A=S.useCallback((K,L)=>{const $=v5(L);n(B=>({...B,[K]:$}))},[]),P=(Z=f.customCardPreferences)==null?void 0:Z.componentName,R=P?h(P):null,H=VC((Y=f.customCardPreferences)==null?void 0:Y.settings,f),z=S.useMemo(()=>b5(x),[x]),U=S.useMemo(()=>z.map((K,L)=>Am(K,L,g==null?void 0:g.slots)),[z,g==null?void 0:g.slots]);return P?c.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:c.jsxs(S.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[R&&b==="single"&&c.jsx(R,{editing:!0,params:s,theme:i,settings:H,cardMetadata:zse({card:e,dataMetadata:C==null?void 0:C.metadata}),onDataChange:A,data:(C==null?void 0:C.records)||[],filters:T,filterValues:[...D||[],...l||[]],inlineFilters:E}),R&&b==="multiple"&&c.jsxs(c.Fragment,{children:[x.map((K,L)=>{if(!K)return null;const $=Iy(K,L),B=Am(K,$,g==null?void 0:g.slots);return c.jsx(BO,{onDataChange:A,card:K,effectiveCardType:B},`${K.id}-${$}`)}),c.jsx("div",{className:"flex flex-col gap-2",children:c.jsx(R,{editing:!0,onDataChange:A,...w5({configCard:f,slotOrderedCards:z,slotTypes:U,multiInputData:t,params:s,theme:i,chartSettings:H,filters:T,filterValues:[...D||[],...l||[]],inlineFilters:E})})})]})]},(M=f.customCardPreferences)==null?void 0:M.componentName)}):null}const f0t=S.memo(d0t,(e,t)=>{var n,r,s,o,i,a,l,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((l=e.card.customCardPreferences)==null?void 0:l.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),h0t=p.create()(p.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var ife=["PageUp","PageDown"],afe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],lfe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Pg="Slider",[rR,m0t,p0t]=p.createCollection(Pg),[cfe]=p.createContextScope(Pg,[p0t]),[g0t,Cj]=cfe(Pg),ufe=Q.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:m=!1,form:g,...b}=e,x=Q.useRef(new Set),y=Q.useRef(0),v=i==="horizontal"?b0t:x0t,[C=[],N]=p.useControllableState({prop:d,defaultProp:u,onChange:T=>{var A;(A=[...x.current][y.current])==null||A.focus(),f(T)}}),k=Q.useRef(C);function _(T){const D=C0t(C,T);E(T,D)}function j(T){E(T,y.current)}function I(){const T=k.current[y.current];C[y.current]!==T&&h(C)}function E(T,D,{commit:A}={commit:!1}){const P=j0t(o),R=E0t(Math.round((T-r)/o)*o+r,P),H=p.clamp(R,[r,s]);N((z=[])=>{const U=w0t(z,H,D);if(_0t(U,l*o)){y.current=U.indexOf(H);const W=String(U)!==String(z);return W&&A&&h(U),W?U:z}else return z})}return c.jsx(g0t,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:y,thumbs:x.current,values:C,orientation:i,form:g,children:c.jsx(rR.Provider,{scope:e.__scopeSlider,children:c.jsx(rR.Slot,{scope:e.__scopeSlider,children:c.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:p.composeEventHandlers(b.onPointerDown,()=>{a||(k.current=C)}),min:r,max:s,inverted:m,onSlideStart:a?void 0:_,onSlideMove:a?void 0:j,onSlideEnd:a?void 0:I,onHomeKeyDown:()=>!a&&E(r,0,{commit:!0}),onEndKeyDown:()=>!a&&E(s,C.length-1,{commit:!0}),onStepKeyDown:({event:T,direction:D})=>{if(!a){const R=ife.includes(T.key)||T.shiftKey&&afe.includes(T.key)?10:1,H=y.current,z=C[H],U=o*R*D;E(z+U,H,{commit:!0})}}})})})})});ufe.displayName=Pg;var[dfe,ffe]=cfe(Pg,{startEdge:"left",endEdge:"right",size:"width",direction:1}),b0t=Q.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:u,...d}=e,[f,h]=Q.useState(null),m=p.useComposedRefs(t,v=>h(v)),g=Q.useRef(void 0),b=p.useDirection(s),x=b==="ltr",y=x&&!o||!x&&o;function w(v){const C=g.current||f.getBoundingClientRect(),N=[0,C.width],_=y3(N,y?[n,r]:[r,n]);return g.current=C,_(v-C.left)}return c.jsx(dfe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:c.jsx(hfe,{dir:b,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{const C=w(v.clientX);i==null||i(C)},onSlideMove:v=>{const C=w(v.clientX);a==null||a(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:v=>{const N=lfe[y?"from-left":"from-right"].includes(v.key);u==null||u({event:v,direction:N?-1:1})}})})}),x0t=Q.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...u}=e,d=Q.useRef(null),f=p.useComposedRefs(t,d),h=Q.useRef(void 0),m=!s;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],v=y3(y,m?[r,n]:[n,r]);return h.current=x,v(b-x.top)}return c.jsx(dfe,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:c.jsx(hfe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);o==null||o(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=lfe[m?"from-bottom":"from-top"].includes(b.key);l==null||l({event:b,direction:y?-1:1})}})})}),hfe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...u}=e,d=Cj(Pg,n);return c.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()):ife.concat(afe).includes(f.key)&&(l(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)&&s(f)}),onPointerUp:p.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),mfe="SliderTrack",pfe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=Cj(mfe,n);return c.jsx(p.Primitive.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});pfe.displayName=mfe;var sR="SliderRange",gfe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=Cj(sR,n),o=ffe(sR,n),i=Q.useRef(null),a=p.useComposedRefs(t,i),l=s.values.length,u=s.values.map(h=>yfe(h,s.min,s.max)),d=l>1?Math.min(...u):0,f=100-Math.max(...u);return c.jsx(p.Primitive.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});gfe.displayName=sR;var oR="SliderThumb",bfe=Q.forwardRef((e,t)=>{const n=m0t(e.__scopeSlider),[r,s]=Q.useState(null),o=p.useComposedRefs(t,a=>s(a)),i=Q.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return c.jsx(y0t,{...e,ref:o,index:i})}),y0t=Q.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=Cj(oR,n),a=ffe(oR,n),[l,u]=Q.useState(null),d=p.useComposedRefs(t,w=>u(w)),f=l?i.form||!!l.closest("form"):!0,h=p.useSize(l),m=i.values[r],g=m===void 0?0:yfe(m,i.min,i.max),b=S0t(r,i.values.length),x=h==null?void 0:h[a.size],y=x?N0t(x,g,a.direction):0;return Q.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),c.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[c.jsx(rR.ItemSlot,{scope:e.__scopeSlider,children:c.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,...o,ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:p.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&c.jsx(xfe,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});bfe.displayName=oR;var v0t="RadioBubbleInput",xfe=Q.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=Q.useRef(null),o=p.useComposedRefs(s,r),i=p.usePrevious(t);return Q.useEffect(()=>{const a=s.current;if(!a)return;const l=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),c.jsx(p.Primitive.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});xfe.displayName=v0t;function w0t(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function yfe(e,t,n){const o=100/(n-t)*(e-t);return p.clamp(o,[0,100])}function S0t(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function C0t(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function N0t(e,t,n){const r=e/2,o=y3([0,50],[0,r]);return(r-o(t)*n)*n}function k0t(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function _0t(e,t){if(t>0){const n=k0t(e);return Math.min(...n)>=t}return!0}function y3(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 j0t(e){return(String(e).split(".")[1]||"").length}function E0t(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var vfe=ufe,I0t=pfe,T0t=gfe,D0t=bfe;const wfe=Q.forwardRef(({className:e,...t},n)=>c.jsxs(vfe,{ref:n,className:p.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[c.jsx(I0t,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:c.jsx(T0t,{className:"absolute h-full bg-primary"})}),c.jsx(D0t,{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"})]}));wfe.displayName=vfe.displayName;const Sfe=["SUN","MON","TUE","WED","THU","FRI","SAT"],M0t=Sfe.reduce((e,t,n)=>({...e,[t]:n}),{}),Tl={repeats:"weekly",hour:9,minute:0,weekdays:[1,2,3,4,5],isCustom:!1};function A0t(e){if(!e||!e.trim())return{...Tl};const t=e.trim(),r=(t.startsWith("cron(")&&t.endsWith(")")?t.slice(5,-1):t).trim().split(/\s+/);if(r.length<5||r.length>6)return{...Tl,isCustom:!0};const[s,o,i,a,l]=r,u=Number(s),d=Number(o);if(!Number.isInteger(u)||u<0||u>59||!Number.isInteger(d)||d<0||d>23)return{...Tl,isCustom:!0};if(i==="*"&&(l==="?"||l==="*"))return{...Tl,repeats:"daily",hour:d,minute:u};if(i==="?"&&l!=="?"&&l!=="*"){const h=l.split(",").map(m=>m.toUpperCase()).map(m=>M0t[m]).filter(m=>typeof m=="number");if(h.length>0)return{...Tl,repeats:"weekly",hour:d,minute:u,weekdays:h}}return i==="1,15"&&(l==="?"||l==="*")?{...Tl,repeats:"biweekly",hour:d,minute:u}:i==="1"&&(l==="?"||l==="*")?{...Tl,repeats:"monthly",hour:d,minute:u}:{...Tl,hour:d,minute:u,isCustom:!0}}function R0t(e){const t=e.minute,n=e.hour;switch(e.repeats){case"daily":return`cron(${t} ${n} * * ? *)`;case"weekly":{const r=e.weekdays.length>0?e.weekdays.slice().sort((s,o)=>s-o).map(s=>Sfe[s]).join(","):"MON";return`cron(${t} ${n} ? * ${r} *)`}case"biweekly":return`cron(${t} ${n} 1,15 * ? *)`;case"monthly":return`cron(${t} ${n} 1 * ? *)`}}function Cfe(e,t){const n=e<12?"AM":"PM",r=e%12===0?12:e%12,s=t.toString().padStart(2,"0");return`${r}:${s} ${n}`}function F0t(e){return!e||e==="UTC"?"UTC":(e.split("/").pop()??e).replace(/_/g," ")}function P0t(e){if(e.length===7)return"every day";const t=e.slice().sort((s,o)=>s-o);if(t.length===5&&t.every(s=>s>=1&&s<=5))return"weekdays";const r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return t.map(s=>r[s]).join(", ")}function O0t(e,t,n,r){const s=Cfe(e.hour,e.minute),o=F0t(t);let i;if(e.isCustom)i=`Custom schedule · ${s} ${o}`;else switch(e.repeats){case"daily":i=`Daily at ${s} ${o}`;break;case"weekly":i=`Weekly · ${P0t(e.weekdays)} at ${s} ${o}`;break;case"biweekly":i=`Every two weeks (1st and 15th) at ${s} ${o}`;break;case"monthly":i=`Monthly on the 1st at ${s} ${o}`;break}const a=[];return n&&n!=="Today"&&a.push(`from ${n}`),r&&a.push(`until ${r}`),a.length>0?`${i}, ${a.join(" ")}`:i}const L0t=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Berlin","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];exports.Accordion=oL;exports.AccordionContent=By;exports.AccordionItem=$y;exports.AccordionTrigger=zy;exports.AddDataPicker=YL;exports.AggregateTable=Kk;exports.Alert=LF;exports.AlertDescription=$F;exports.AlertDialog=dh;exports.AlertDialogAction=Ku;exports.AlertDialogCancel=Zu;exports.AlertDialogContent=Uu;exports.AlertDialogDescription=Gu;exports.AlertDialogFooter=Wu;exports.AlertDialogHeader=qu;exports.AlertDialogTitle=Yu;exports.AlertDialogTrigger=ixe;exports.AlertTitle=nZ;exports.ArrowDown=Ns;exports.ArrowDownIcon=PHe;exports.ArrowLeft=f0;exports.ArrowRight=AN;exports.ArrowUp=Ls;exports.ArrowUpIcon=LHe;exports.AssistantContextEntityControls=VA;exports.AssistantVirtualizedMessages=Kde;exports.AtSign=oq;exports.AxisConfigurator=qp;exports.Badge=rs;exports.Bell=DS;exports.BookType=aq;exports.BulletChartIcon=Bde;exports.COMMON_TIMEZONES=L0t;exports.CSS=di;exports.CalculatedFieldEditor=Qie;exports.Calculator=cq;exports.Calendar=ti;exports.Calendar$1=s1;exports.CalendarRange=uq;exports.Card=Xm;exports.CardContent=MN;exports.CardHeader=DN;exports.CardSummary=fA;exports.CardTitle=Rp;exports.ChartArea=BD;exports.ChartColumnIncreasing=dq;exports.ChartColumnStacked=fq;exports.ChartJsVisual=J0;exports.ChartLine=hq;exports.ChartNoAxesGantt=pq;exports.ChartPie=gq;exports.ChartScatter=bq;exports.ChatInputWithContext=GL;exports.Checkbox=En;exports.ChevronLeft=lh;exports.ChevronRight=vr;exports.Circle=xR;exports.CircleAlert=Mf;exports.CircleCheck=vq;exports.CircleHelp=wq;exports.Clock=yR;exports.CodeHighlighter=If;exports.CodeXml=MS;exports.Collapsible=mc;exports.CollapsibleContent=gc;exports.CollapsibleTrigger=pc;exports.ColorField=ki;exports.Command=z_;exports.CommandEmpty=V_;exports.CommandGroup=H_;exports.CommandInput=Y5;exports.CommandItem=U_;exports.CommandList=B_;exports.CommandSeparator=xie;exports.ComparisonMetadataBadge=_J;exports.Container=qR;exports.ControlDefaultValueEditor=vae;exports.ControlDefinitionOptionsEditor=yae;exports.ControlIdInput=pae;exports.ControlVisibilitySettings=YQe;exports.Copy=yu;exports.CopyButton=bu;exports.CopyPlus=HD;exports.Cross2Icon=VHe;exports.CustomFilterPopover=h5;exports.CustomScrollArea=bl;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=IQ;exports.DEFAULT_SCHEDULE_VM=Tl;exports.Dashboard=rfe;exports.DashboardActionsMenu=LW;exports.DashboardCard=Noe;exports.DashboardCreateDialogBase=pY;exports.DashboardExportDialog=Zde;exports.DashboardPlus=Vyt;exports.DashboardWC=s0t;exports.DataTableConditionalFormattingSettings=lle;exports.DataTablePagination=Hk;exports.Database=Mi;exports.DateRangePicker=YO;exports.DefaultChatTransport=$L;exports.Dialog=yo;exports.DialogContent=Js;exports.DialogDescription=Bo;exports.DialogFooter=vc;exports.DialogHeader=Bi;exports.DialogTitle=eo;exports.DialogTrigger=fY;exports.DisplayPreferencesProvider=I_;exports.DndContext=yv;exports.Donut=Sq;exports.Download=xc;exports.DownloadPdf=Xde;exports.DragOverlay=sie;exports.DropdownMenu=po;exports.DropdownMenuCheckboxItem=Lc;exports.DropdownMenuContent=Ks;exports.DropdownMenuItem=bn;exports.DropdownMenuLabel=tc;exports.DropdownMenuRadioGroup=xge;exports.DropdownMenuRadioItem=PW;exports.DropdownMenuSeparator=fa;exports.DropdownMenuSub=OR;exports.DropdownMenuSubContent=BN;exports.DropdownMenuSubTrigger=zN;exports.DropdownMenuTrigger=go;exports.EMPTY_DATA_SOURCE=Dp;exports.Editable=UC;exports.EditableText=Oo;exports.EditorCustomVisual=f0t;exports.Ellipsis=da;exports.EllipsisVertical=ch;exports.ErrorBoundary=ba;exports.ExportError=Qp;exports.ExternalLink=Jm;exports.Eye=h0;exports.EyeOff=RN;exports.Fallback=j_;exports.FallbackVisual=Dy;exports.FeedbackCategory=Vu;exports.FeedbackDialog=e0;exports.FieldsList=hL;exports.FieldsSection=o0t;exports.FileCode=Cq;exports.FileSpreadsheet=Nq;exports.FileText=oi;exports.Filter=Af;exports.FilterComponent=v_;exports.FilterInfo=lA;exports.FilterableFieldsPanel=eae;exports.Globe=Fp;exports.Grid3x3=kq;exports.GripVertical=yc;exports.HEATMAP_PRESET_PALETTES=G2;exports.Hash=_q;exports.House=jq;exports.HoverCard=eg;exports.HoverCardContent=Iu;exports.HoverCardTrigger=tg;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=ofe;exports.INLINE_ALLOWED_TOOL_LIST=a0t;exports.INLINE_BLOCKED_MUTATING_TOOLS=i0t;exports.IconButton=ec;exports.IconForFieldType=d1;exports.InfoHover=F5;exports.InlineFilterBar=moe;exports.KPICard=Pu;exports.KeyboardSensor=bv;exports.Layers=m0;exports.LayoutDashboard=ep;exports.Link=vR;exports.LoadingDots=Du;exports.Lock=FN;exports.MAX_SELF_HEAL_ATTEMPTS=l0t;exports.Map=Tq;exports.Markdown=rde;exports.Maximize2=PN;exports.MdStackedLineChart=$de;exports.Minimize2=wR;exports.MultiInputEmptyRenderer=BO;exports.PYTHON_DEFAULT_CODE=aR;exports.PanelLeft=Dq;exports.PanelResizeHandle=aj;exports.Paperclip=Mq;exports.PenLine=UD;exports.Pencil=qD;exports.PendingMessagesDisplay=xue;exports.PersistedDynamicVisual=E_;exports.PiChartPolar=Fde;exports.PivotTableTanstack=wg;exports.Placeholders=Fle;exports.Play=Aq;exports.Plus=wr;exports.PointerSensor=jg;exports.Progress=qL;exports.RECOVERABLE_SQL_ERROR_CODES=u0t;exports.Radar=Rq;exports.RadioGroup=ma;exports.RadioGroupItem=ps;exports.RefreshCw=Rf;exports.ResizableHandle=srt;exports.ResizablePanel=TA;exports.ResizablePanelGroup=Rle;exports.ResourceEditDialog=WY;exports.ResourceType=$r;exports.SELF_HEAL_TIMELINE_STEP=c0t;exports.Search=Xs;exports.SeedQuestions=rue;exports.SemaphorContext=c0;exports.SemaphorContextProvider=mR;exports.SemaphorQueryClient=JU;exports.SemaphorReadyIndicator=x3;exports.SemaphorStyleWrapper=Sg;exports.Send=Fq;exports.Settings=SR;exports.Settings2=p0;exports.Share2=Pq;exports.ShareDialog=qY;exports.Sheet=mJ;exports.SheetContent=$P;exports.SheetDescription=BP;exports.SheetHeader=gJ;exports.SheetTitle=zP;exports.SheetTrigger=BRe;exports.Slider=wfe;exports.SortableContext=vv;exports.Sparkles=E1;exports.Square=NR;exports.SquarePen=CR;exports.Star=kR;exports.StructuralParticipantSelector=gae;exports.SummaryCard=oA;exports.TABLE_PRESENTATION_DEFAULT_STYLE=pu;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=Ei;exports.TableBody=Uf;exports.TableCell=Yn;exports.TableColumnVisibilitySettings=Zae;exports.TableHead=Mo;exports.TableHeader=Jp;exports.TablePresentationSettings=Qae;exports.TableRow=Or;exports.TableSkeleton=P5;exports.TableVisual=Tu;exports.TbChartBubble=Pde;exports.TbChartFunnel=Ode;exports.TbChartTreemap=Lde;exports.TextCard=Np;exports.Textarea=hh;exports.TiSortNumerically=zde;exports.Toggle=k_;exports.Tornado=Oq;exports.Trash2=rl;exports.TreePalm=jR;exports.TrendingUp=Lq;exports.TriangleAlert=Ai;exports.TypeGlyph=fv;exports.UXProvider=b3;exports.User=$q;exports.Users=ER;exports.applyFilterOverridesToDashboardInputSlots=SK;exports.areContextEntitiesEqual=Gn;exports.areEntitiesJoined=RQ;exports.arrayMove=Eg;exports.buildCardControlUsageById=KQe;exports.buildCustomCardTheme=av;exports.buildDashboardCardExecutionSnapshot=wK;exports.buildDashboardControlUsageById=GQe;exports.buildDashboardExecutionSnapshot=MF;exports.buildDashboardInputExecutionSnapshot=cu;exports.buildDashboardSheetsInputExecutionSnapshot=NK;exports.buildDashboardStructuralParticipantIdsByControlId=Cae;exports.buildFilterFieldMeta=J5;exports.buildFilterSemanticContext=eL;exports.buildInlineFilterNodes=p5;exports.buildMultiInputCustomVisualProps=w5;exports.buildScheduleExpr=R0t;exports.buildSchedulePreview=O0t;exports.buildSlotOrderedCards=b5;exports.calculateContextAwareFilters=k0;exports.calculateFieldState=TP;exports.canUserAccessVisuals=fye;exports.canUserCreateDashboards=KY;exports.canUserEdit=cye;exports.canUserManageDashboards=dye;exports.canUserManageGroups=hye;exports.canUserUseFilters=uye;exports.cancelExport=IAe;exports.chartSupportsDataLabels=_X;exports.chartSupportsLegend=NX;exports.chartTypes=Sj;exports.cleanupKpiMetricComparisonMode=_ie;exports.cloneDeep=Ao;exports.cloneLinkedFrameWithSourceMapping=eWe;exports.closestCenter=gv;exports.commitSharedCalculatedFields=Ad;exports.createAssistantConversationId=fm;exports.createAssistantRequestId=tue;exports.createCardsFromSlots=pUe;exports.createChartConfig=Xp;exports.createDashboardControlInputFromControl=Wtt;exports.createDefaultGlobalDateFilter=lSe;exports.createExport=eJ;exports.createUniqueDashboardInputVariableNameFromName=xu;exports.dedup=Jlt;exports.doesStoredFilterMatchField=Ip;exports.downloadDocumentPdf=RF;exports.downloadPdf=MK;exports.extractSqlParamReferences=Ere;exports.extractTableMetadata=Q5;exports.fieldAlreadyExists=PQ;exports.findCustomVisualConfigCard=y5;exports.findDashboardFrameById=Jwe;exports.flexRender=Fo;exports.formatDisplayFormula=HZe;exports.formatFileSize=MAe;exports.formatFilterLine=sZ;exports.formatTimeLabel=Cfe;exports.getAutoDetectedChartIcon=pxt;exports.getChartGridStyle=MCe;exports.getChartIconByType=gxt;exports.getColorForValue=d2;exports.getConfigSlotExpectedType=mUe;exports.getCoreRowModel=zk;exports.getCustomVisualInputCards=x5;exports.getDateFormatOptionsForGranularity=Oy;exports.getDefaultAxisConfig=h2;exports.getDefaultChartColors=xh;exports.getDefaultDataLabelsConfig=O0;exports.getDefaultExportFormat=wZ;exports.getDefaultFilterSql=QO;exports.getDefaultLegendConfig=hP;exports.getDefaultRunningTotalPartitionByFieldIds=Rx;exports.getDocumentSectionEditorCard=_Qe;exports.getDocumentSheetDashboardInputs=kv;exports.getDownloadUrl=EAe;exports.getEffectiveCardTypeForSlot=Am;exports.getEntityIcon=wN;exports.getErrorMessage=Hce;exports.getExportStatus=jAe;exports.getExports=_Ae;exports.getExpressionFieldKind=Lu;exports.getFieldExpressionAnnotation=tL;exports.getFilterCount=KC;exports.getGlobalDateFilter=$p;exports.getGlobalDateFilterCoverage=cSe;exports.getGranularityOptionsForFieldType=yL;exports.getKeys=rr;exports.getMetricDisplayLabel=GMe;exports.getNewField=BQ;exports.getObjectDiff=AU;exports.getPaginationRowModel=Bk;exports.getRoleBasedDisplayOverrides=GY;exports.getRunningTotalOrderByCandidates=fZe;exports.getSelectedDateFilterColumn=Tre;exports.getSheetScopedFilterValues=Gx;exports.getSlotDefinitionForIndex=g5;exports.getSlotExpectedChartType=C_;exports.getSlotIndexForCard=Iy;exports.getSortedRowModel=hJ;exports.getSupportedExportFormats=vZ;exports.getTableConditionalFormattingColumnOptions=nle;exports.getTableOutputColumnOptions=rle;exports.getTablePageSizeOptions=XQ;exports.handleAggregationChange=cA;exports.handleAggregationLabelChange=foe;exports.hasFlatTableTotalsBehavior=r1e;exports.horizontalListSortingStrategy=H5;exports.isCalculatedFilterField=Ly;exports.isCardSummaryVisibleOnCard=S5;exports.isCustomVisualConfigCard=rA;exports.isDefaultColor=f1e;exports.isEligibleFlatTableTotalsCard=zp;exports.isExportComplete=DAe;exports.isExportInProgress=TAe;exports.isInAiScopeArray=Qlt;exports.isManagedCalculatedExpressionField=la;exports.isMetricTransformEnabled=uZe;exports.isPromiseLike=BA;exports.isSubtotalEnabledAggregateTable=X5;exports.isSupportedDocumentTableCardType=jQe;exports.lastAssistantMessageIsCompleteWithToolCalls=$ce;exports.merge=nl;exports.mergeAxisConfig=m2;exports.normalizeConditionalFormatting=kF;exports.normalizeContextFormatMode=uZ;exports.normalizeDashboardInputVariableName=d0;exports.normalizeMultiInputPayload=v5;exports.parseScheduleExpr=A0t;exports.pivotData=T0;exports.prepareFeedbackData=wj;exports.purify=OM;exports.reindexSlotCards=hUe;exports.remarkGfm=Dde;exports.removeFromScopeArray=ect;exports.resolveDashboardInputContext=gl;exports.resolveDomainCalculatedFieldForEdit=LXe;exports.resolveMultiInputType=lv;exports.resolveMultiInputTypeFromVisual=gUe;exports.resolveTablePageSize=Ok;exports.resolveTablePresentationStyle=ZP;exports.sanitizeAIScope=Vce;exports.saveCalculatedFieldToCardScope=wA;exports.saveCalculatedFieldToSharedScope=Jie;exports.saveCalculatedFieldToSheetScope=SA;exports.seedSemanticMetricFormatDefaults=Eie;exports.setTableColumnVisibility=rJ;exports.setupEditorWithCard=gk;exports.showAllTableColumns=PAe;exports.showJoinRequiredNotification=FQ;exports.sortByColumnsToSortState=PJ;exports.sortStateToSortByColumns=OJ;exports.sortableKeyboardCoordinates=q5;exports.supportsMetricTransformForMetric=jie;exports.supportsTableConditionalFormatting=Jae;exports.toEntityArray=aa;exports.ue=tt;exports.useActiveExports=yye;exports.useActiveToolStatus=vue;exports.useAddFrameWithFreshSemanticExecutionPayload=R5;exports.useAddNewFrame=Roe;exports.useAssistantContainer=QY;exports.useAssistantContextEntities=D_;exports.useAssistantLayoutStore=hf;exports.useAssistantPanel=ZY;exports.useAssistantProfile=nue;exports.useAutoSubmitQueue=yue;exports.useBrandStudioPreview=Eyt;exports.useCard=iAe;exports.useCardFilterValues=HQ;exports.useCardSummary=C5;exports.useChat=Bce;exports.useColumns=G5;exports.useCreateVisualWithFrame=ube;exports.useCurrentUserInfo=zi;exports.useCustomVisual=Nh;exports.useCustomVisualsQuery=f5;exports.useDashboardAppearance=dl;exports.useDashboardById=qW;exports.useDashboardCreation=GW;exports.useDashboardManagement=YW;exports.useDashboardPreferences=Pp;exports.useDashboardQuery=u0;exports.useDashboardStructuralParticipants=Nae;exports.useDashboardSummary=Kse;exports.useDataColumns=Tie;exports.useDateFilterHook=YVe;exports.useDebounce=Ex;exports.useDefaultDashboardMutation=$W;exports.useDisplayPreferences=pl;exports.useDroppable=rie;exports.useEditorAside=q_;exports.useEditorCardQuery=pk;exports.useEnsureReactGlobals=rre;exports.useExportActions=JY;exports.useExportStore=ZN;exports.useFieldManagement=Iie;exports.useFilterableFields=Cie;exports.useFullscreenAssistant=XY;exports.useGroupMembers=dxe;exports.useGroups=OY;exports.useHasDashboardId=eG;exports.useInProgressExportsCount=vye;exports.useIsDashboardSelected=rme;exports.useIsVisualSelected=sme;exports.useJoinabilityMap=Z5;exports.useManagementActions=ah;exports.useManagementStore=Kr;exports.useMutation=Ys;exports.usePivotTableConfig=vh;exports.usePluginQuery=Fse;exports.useQuery=jn;exports.useQueryClient=qr;exports.useReactTable=Vk;exports.useResolveExistingFrameSemanticExecutionPayload=sWe;exports.useResourceManagement=UN;exports.useResourceUpdateState=WW;exports.useScopedFields=Sie;exports.useSelectedVisual=nme;exports.useSemaphorContext=mt;exports.useSensor=Ep;exports.useSensors=F_;exports.useSortable=Ig;exports.useStarredChartsStore=h0t;exports.useSurfaceAppearance=Sc;exports.useTableQueryState=jJ;exports.useTextFilterHook=s8e;exports.useTheme=lR;exports.useTopoJson=$0;exports.useUnifiedUsers=HR;exports.useUpdateResource=BW;exports.useUpdateVisualMutation=dbe;exports.useUserPreferences=gY;exports.useVisualById=HN;exports.useVisualManagement=cbe;exports.validateFieldForChartType=kie;exports.verticalListSortingStrategy=U5;
|
|
1361
|
+
`).trim(),j=k.map((I,E)=>{var A,P;let T="",D;if((A=I.url)!=null&&A.startsWith("data:")){const R=I.url.match(/data:[^;]+;base64,(.+)/);R&&(T=R[1],(P=I.mediaType)!=null&&P.startsWith("image/")&&(D=I.url))}return{id:`${e.id||t}-file-${E}`,name:I.filename||`File ${E+1}`,size:0,type:I.mediaType||"application/octet-stream",data:T,preview:D}});return c.jsx(Vxt,{text:_||void 0,files:j.length>0?j:void 0})}const f=((v=e.parts)==null?void 0:v.filter(N=>N.type==="reasoning"))||[],h=f.length>0,m=f.some(N=>N.state==="streaming"),g=f.filter(N=>N.text&&N.text.trim().length>0),b=h&&(g.length>0||m)?c.jsxs(mc,{className:"space-y-2",defaultOpen:!1,children:[c.jsx(pc,{asChild:!0,children:c.jsxs("button",{type:"button",className:"group inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:[c.jsx(vr,{className:"h-3 w-3 transition-transform duration-200 group-data-[state=open]:rotate-90"}),c.jsx("span",{className:m?"animate-pulse":"",children:m?"Reasoning":"Show reasoning"}),g.length>1&&c.jsxs("span",{className:"font-mono tabular-nums text-muted-foreground/70",children:["(",g.length," steps)"]})]})}),c.jsx(gc,{children:c.jsx("ol",{className:"space-y-2 border-l border-border/60 pl-3",children:g.map((N,k)=>c.jsxs("li",{className:"relative",children:[c.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:k+1}),c.jsx(nU,{className:"text-[12px] leading-[1.55] text-muted-foreground",text:N.text})]},`${e.id||t}-reasoning-${k}`))})})]},`${e.id||t}-reasoning`):null,x=(C=e.parts)==null?void 0:C.map((N,k)=>{var j;const _=`${e.id||t}-${k}`;switch(N.type){case"text":{const I=typeof N.text=="string"?N.text:JSON.stringify(N.text??"",null,2);if(e.role==="assistant"){const{cleanedText:E,quickReplies:T}=Lxt(I),D=E.trim().length>0;return c.jsxs("div",{className:"space-y-2.5",children:[D&&c.jsx(nU,{text:E,handleRun:i,onAddToDashboard:s,messageId:e.id,messages:n}),T.length>0&&a&&d&&c.jsxs("div",{className:"space-y-1.5",children:[T.length>=3&&c.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Suggested next steps"}),c.jsx("div",{className:"flex flex-wrap gap-1",children:T.map(({label:A,value:P},R)=>c.jsxs(p.Tooltip,{children:[c.jsx(p.TooltipTrigger,{asChild:!0,children:c.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:l,onClick:()=>a(P),children:c.jsx("span",{className:"truncate",children:A})})}),c.jsx(p.TooltipContent,{side:"top",align:"center",children:c.jsx("p",{className:"max-w-xs text-xs",children:P})})]},`${_}-qr-${R}`))})]})]},_)}return e.role==="system"&&o?c.jsx(Hxt,{text:I},_):null}case"error":{const I=N,E=I.errorText??I.error??I.message;return c.jsx("div",{className:"my-4",children:c.jsx(g3,{errorMessage:E})},_)}case"reasoning":return null;default:return((j=N.type)!=null&&j.startsWith("tool-")||N.type==="dynamic-tool")&&p3(N,r)?c.jsx(ba,{FallbackComponent:({error:I,resetErrorBoundary:E})=>c.jsx(Bxt,{error:I,resetErrorBoundary:E}),children:c.jsx(Axt,{part:N,idx:_,messageId:e.id,showTools:r,onAddToDashboard:s,messages:n})},_):null}});return e.role==="assistant"?Gde(e,r)?c.jsxs(Yde,{who:"Assistant",className:"space-y-2",children:[b,x]}):null:c.jsxs("div",{className:"space-y-2",children:[b,x]})}const Yxt=8,Gxt=24,Kxt=20;function Zxt(e,t,n,r){return e==="error"&&t?!0:r?!1:!!(n||e==="submitted"||e==="streaming")}function Kde({messages:e,showTools:t=!1,showSystemMessage:n=!1,handleRun:r,onAddToDashboard:s,onQuickReply:o,disableQuickReplies:i=!1,status:a,errorMessage:l,activeToolText:u,className:d,rowContentClassName:f,statusClassName:h,latestButtonClassName:m,scrollToEndSignal:g=0}){const b=S.useRef(null),x=S.useRef(null),y=S.useRef(e.length),w=S.useRef(!1),v=S.useRef(null),C=S.useRef(!1),N=S.useRef(g),[k,_]=S.useState(!0),[j,I]=S.useState(0),[E,T]=S.useState(Gxt);N.current!==g&&(N.current=g,C.current=!0);const D=e[e.length-1],A=Gde(D,t),P=Zxt(a,l,u,A),R=Gk({count:e.length,getScrollElement:()=>b.current,estimateSize:W=>{const O=e[W];return(O==null?void 0:O.role)==="user"?88:180},getItemKey:W=>{const O=e[W];return(O==null?void 0:O.id)||`message-${W}`},anchorTo:"end",followOnAppend:!0,scrollEndThreshold:Yxt,overscan:6,gap:20,paddingEnd:P?E+Kxt:0,useAnimationFrameWithResizeObserver:!0,onChange:W=>{const O=W.isAtEnd();_(Z=>Z===O?Z:O),O&&I(0)}}),H=S.useCallback((W="smooth")=>{v.current!==null&&cancelAnimationFrame(v.current),v.current=requestAnimationFrame(()=>{v.current=null,R.scrollToEnd({behavior:W})}),I(0),_(!0)},[R]);S.useLayoutEffect(()=>{w.current||(w.current=!0,H("auto"))},[H]),S.useLayoutEffect(()=>{C.current&&(C.current=!1,H("auto"))},[e.length,g,H]),S.useEffect(()=>{const W=y.current;y.current=e.length,e.length>W&&!R.isAtEnd()&&I(O=>O+e.length-W),e.length===0&&(I(0),_(!0),w.current=!1,C.current=!1)},[e.length,R]);const z=R.getVirtualItems(),U=R.getTotalSize();return S.useEffect(()=>()=>{v.current!==null&&cancelAnimationFrame(v.current)},[]),S.useLayoutEffect(()=>{const W=x.current;if(!W||!P)return;const O=()=>{const Y=Math.ceil(W.getBoundingClientRect().height);Y>0&&T(M=>M===Y?M:Y)};if(O(),typeof ResizeObserver>"u")return;const Z=new ResizeObserver(O);return Z.observe(W),()=>Z.disconnect()},[P,a,l,u]),c.jsxs(c.Fragment,{children:[c.jsx(bl,{"data-role":"assistant-virtualized-scroll-area",ref:b,className:p.cn("min-h-0 min-w-0 flex-1 basis-0",d),children:c.jsxs("div",{className:"relative w-full",style:{height:U},children:[z.map(W=>{const O=e[W.index];return O?c.jsx("div",{ref:R.measureElement,"data-index":W.index,className:"absolute left-0 top-0 w-full",style:{transform:`translateY(${W.start}px)`},children:c.jsx("div",{className:p.cn("min-w-0",f),children:c.jsx(Wxt,{message:O,messageIndex:W.index,messages:e,showTools:t,showSystemMessage:n,handleRun:r,onAddToDashboard:s,onQuickReply:o,disableQuickReplies:i})})},W.key):null}),P&&c.jsx("div",{ref:x,className:p.cn("absolute left-0 top-0 w-full",h),style:{transform:`translateY(${Math.max(U-E,0)}px)`},children:c.jsx("div",{className:p.cn("min-w-0",f),children:c.jsx(Uxt,{status:a,errorMessage:l,activeToolText:u})})})]})}),!k&&c.jsxs("button",{type:"button",onClick:()=>H("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:[c.jsx(Ns,{className:"h-3 w-3"}),"Latest",j>0&&c.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:j>9?"9+":j})]})]})}function Xxt(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 Qxt=[{title:"Show top 3 insights",subtitle:"from this dataset"},{title:"Create a bar chart for",subtitle:"sales by product category"}];function Jxt({open:e,setOpen:t,isFullscreen:n,onFullscreenChange:r,fullscreenContainer:s}){const[o,i]=S.useState(!1),[a,l]=S.useState(p.isDevEnv),[u,d]=S.useState(!1),[f,h]=S.useState("auto"),[m,g]=S.useState(!1),[b,x]=S.useState(!1),[y,w]=S.useState(0),v=n??b,{isLocalDev:C,isConsoleMode:N}=Pp(),k=C||N||a,_=S.useRef(null);p.useDashboardStore(ee=>ee.dashboard.aiScopeTables),p.useDashboardStore(ee=>ee.isDashboardEditing);const j=p.useDashboardStore(ee=>ee.selectedSheetId),{setDataSource:I}=p.useEditorActions(),{setSelectedFrameId:E,setIsDashboardEditing:T}=p.useDashboardActions(),D=R5(),{clearAssistantMessageContexts:A}=p.useAIActions(),{clearQueue:P}=p.useQueueActions(),{clearFileAttachments:R,getFileAttachments:H}=p.useFileActions(),z=p.useFileAttachments("dashboard"),U=p.useEditorStore(ee=>ee.card.dataSource),{assistantProfile:W}=nue(),O=p.useDashboardStore(ee=>ee.handleOpenAssistantProfile),{selectedEntities:Z,applyDashboardDefaultEntities:Y}=D_("dashboard"),{sendMessage:M,isLoading:K,messages:L,setMessages:$,status:B,stop:V,errorMessage:F,clearError:q}=yct({dynamicVisualMode:f}),G=S.useCallback(()=>{w(ee=>ee+1)},[]),X=S.useCallback(ee=>{r==null||r(ee),n===void 0&&x(ee)},[n,r]),J=S.useCallback(()=>{X(!v)},[v,X]);S.useEffect(()=>{if(!v)return;function ee(Ce){Ce.key==="Escape"&&X(!1)}return window.addEventListener("keydown",ee),()=>{window.removeEventListener("keydown",ee)}},[v,X]);const[fe,ue]=S.useState(""),pe=ee=>{ue(ee.target.value)};async function ye({sql:ee,cardTitle:Ce,connectionId:ve,cardType:te,python:_e,cardConfig:De,dataSource:Fe,customVisualPreferences:Ye,visualizationMode:ze,dynamicCardPreferences:Ve}){if(!j)return;const Ke=ze==="dynamic",ke=p.hasValidCardConfig(De),Xe=ve||(Fe==null?void 0:Fe.connectionId)||"",Pe=Fe?{...Fe,connectionId:Xe||Fe.connectionId,connectionType:Fe.connectionType||"",mode:Fe.mode||"database",selectedEntities:Fe.selectedEntities||[]}:Xe?{connectionId:Xe,connectionType:"",mode:"database",selectedEntities:[]}:Dp,nt=!(ke&&(!Ke||(Ve==null?void 0:Ve.provenance)==="card-config"||(Ve==null?void 0:Ve.provenance)==="query_spec")),Me=nt?Xxt(ee):"",Ee=nt?_e:"",We={id:p.v4(),title:Ce||"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}],chartOptions:{indexAxis:te==="horizontalBar"?"y":"x"},...Ke&&{displayOptions:{showChrome:!1,allowScroll:!1}}},type:te,sql:Me,python:Ee,dataSource:Pe,config:De,connectionId:Xe,visualizationMode:ze,dynamicCardPreferences:Ve,customCardPreferences:Ye?{url:Ye.url,componentName:Ye.componentName,pluginChartType:Ye.pluginChartType,settings:Ye.settings,type:"component"}:void 0},vt={id:p.v4(),cards:[We],activeCardId:We.id};try{await D(j,vt,"end"),T(!0),E(vt.id)}catch(yt){console.error("Failed to add assistant visual to dashboard:",yt),tt.error(yt instanceof Error?yt.message:"Failed to prepare semantic metadata for the new visual")}}const ie=ee=>{ee.preventDefault();const Ce=fe.trim();if(!Ce&&z.length===0)return;const ve=[];Ce&&ve.push({type:"text",text:Ce}),z.forEach(te=>{te.data&&ve.push({type:"file",mediaType:te.type,filename:te.name,url:`data:${te.type};base64,${te.data}`})}),M({role:"user",parts:ve}),ue(""),R("dashboard"),G()};S.useEffect(()=>{var ee;e&&((ee=_.current)==null||ee.focus())},[e]),yue({assistantType:"dashboard",status:B,isLoading:K,sendMessage:M});const{hasActiveTools:ae,activeToolText:se}=vue(L);function Ie(ee){const Ce={role:"user",parts:[{type:"text",text:ee.title+" "+ee.subtitle}]};M(Ce),G()}function oe(ee){M({role:"user",parts:[{type:"text",text:ee}]}),G()}function me(ee){M({role:"user",parts:[{type:"text",text:ee}]}),G()}const we=S.useCallback(async()=>{const ee=JSON.stringify(L??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(ee),tt.success("Conversation copied")}catch(Ce){console.error("Failed to copy conversation",Ce),tt.error("Unable to copy conversation")}},[L]),ge=(fe==null?void 0:fe.length)===0&&(L==null?void 0:L.filter(ee=>ee.role==="user").length)===0;function re(){return c.jsx("div",{"data-role":"header",className:"flex items-center gap-2",children:c.jsx("span",{className:"text-[13px] font-medium text-foreground",children:"Assistant"})})}function ne(){return c.jsxs(po,{children:[c.jsx(go,{asChild:!0,children:c.jsx(ec,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:c.jsx(ch,{className:"size-3.5"})})}),c.jsxs(Ks,{align:"end",children:[c.jsx(tc,{children:"Options"}),c.jsx(fa,{}),c.jsx(Lc,{checked:o,onCheckedChange:i,children:"Token Usage"}),c.jsx(Lc,{checked:a,onCheckedChange:l,children:"Tool Invocations"}),c.jsx(Lc,{checked:u,onCheckedChange:d,children:"System Message"}),(C||N)&&c.jsxs(c.Fragment,{children:[c.jsx(fa,{}),c.jsx(tc,{children:"Dynamic Visuals"}),c.jsx(Lc,{checked:f==="auto",onCheckedChange:()=>h("auto"),children:"Auto"}),c.jsx(Lc,{checked:f==="force",onCheckedChange:()=>h("force"),children:"Force Dynamic"}),c.jsx(Lc,{checked:f==="off",onCheckedChange:()=>h("off"),children:"Disable Dynamic"})]})]})]})}const he=c.jsxs("div",{"data-role":"dashboard-assistant",className:p.cn("relative flex h-full grow flex-col break-words bg-background",v&&"rounded-card border border-border/60 shadow-xl"),children:[c.jsxs("header",{"data-role":"header-section",className:"flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3",children:[re(),O&&c.jsxs("button",{type:"button",onClick:O,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:[c.jsx("span",{className:"h-1 w-1 rounded-full bg-muted-foreground/60"}),c.jsx("span",{className:"max-w-[180px] truncate",children:(W==null?void 0:W.name)||"Default profile"})]}),c.jsxs("div",{"data-role":"header-actions",className:"ml-auto flex items-center gap-0.5",children:[N&&ne(),k&&c.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"}),c.jsx(ec,{className:"grid h-6 w-6 place-items-center rounded-[4px] p-0 text-muted-foreground hover:bg-muted hover:text-foreground",tooltip:v?"Exit fullscreen":"Expand",onClick:J,children:v?c.jsx(wR,{className:"h-3.5 w-3.5"}):c.jsx(PN,{className:"h-3.5 w-3.5"})}),c.jsx(ec,{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 ee=L.filter(Ce=>Ce.role==="assistant").map(Ce=>Ce.id).filter(Ce=>!!Ce);$([]),P("dashboard"),q(),A(ee)},children:c.jsx(CR,{className:"h-3.5 w-3.5"})}),c.jsx(ec,{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:c.jsx(p.X,{className:"h-3.5 w-3.5"})})]})]}),c.jsx(Kde,{messages:L,showTools:a,showSystemMessage:u,onAddToDashboard:ye,onQuickReply:me,disableQuickReplies:K,status:B,errorMessage:F,activeToolText:K&&ae?se:void 0,className:p.cn(v?"px-6 py-5":"px-3 py-3"),rowContentClassName:p.cn(v&&"mx-auto w-full max-w-[680px]"),latestButtonClassName:e?"bottom-[148px]":"hidden",scrollToEndSignal:y}),c.jsxs("div",{className:"shrink-0 space-y-2 border-t border-border/60 px-3 pb-3 pt-2",children:[!W&&ge&&c.jsx(Fle,{onClick:Ie,placeholders:Qxt}),ge&&W&&c.jsx(rue,{seedQuestions:W.seedQuestions||[],handleSeedQuestionClick:oe}),c.jsx(xue,{assistantType:"dashboard"}),c.jsx(GL,{ref:_,setInput:ue,stop:V,input:fe,handleInputChange:pe,handleSubmit:ee=>{ie(ee)},isLoading:K,status:B,assistantType:"dashboard",onFocus:()=>{}})]}),c.jsx(YL,{incomingSelectedEntities:Z,open:m,onOpenChange:g,dataSource:U||Dp,dialogMode:"aiContext",saveAsDashboardDefault:!0,onSaveSelectedEntities:ee=>Y()})]});return v&&s?fr.createPortal(c.jsx(Sg,{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:c.jsx("div",{className:"flex h-full w-full",children:he})}),s):he}function eyt(e){const t=e.current,{getSelectedFrame:n,setSelectedFrameId:r}=p.useDashboardActions(),s=uoe(),o=p.useDashboardStore(d=>d.dashboard.sheets),a=p.useDashboardStore(d=>d.selectedSheetId)??(o==null?void 0:o[0].id),l=p.useDashboardStore(d=>d.isDashboardEditing),u=p.useDashboardStore(d=>d.isVisualEditing);S.useEffect(()=>{if(!l||u)return;async function d(m){if(tyt(m.target))return;const g=m.ctrlKey||m.metaKey;g&&m.key==="c"?(await f(),tt.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=nyt(m);if(g!=null&&g.id){const b=aoe(g),x=b.cards.findIndex(y=>y.id===b.activeCardId);x!==-1&&(b.cards[x].title=`${b.cards[x].title} (Copy)`),await s(a,b),r(b.id),tt.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)},[s,n,r,a,l,u,t])}function tyt(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 nyt(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 ryt(e,t){switch(e.interactionMode){case"drillToDetail":syt(e,t);break;case"drillThrough":oyt(e,t);break;case"drillToURL":iyt(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 syt(e,t){var l;const{targetInsightId:n,contextMode:r,displayMode:s,filterGroups:o}=e;if(!n){console.warn("drillToDetail event missing targetInsightId");return}const i=r||"full";let a=[];switch(i){case"interactionFilters":a=o.flatMap(u=>u.filters);break;case"full":{const u=((l=t.getCurrentFilters)==null?void 0:l.call(t))||[],d=o.flatMap(f=>f.filters);a=[...u,...d];break}case"none":default:a=[];break}s==="replace-card"?t.replaceCardContent({cardId:e.sourceCardId,insightId:n,filters:a,contextMode:r}):t.openInsightModal({insightId:n,filters:a,contextMode:r})}function oyt(e,t){var u,d;const{targetDashboardId:n,contextMode:r="interactionFilters",filterGroups:s,sourceCardId:o}=e;if(!n){console.warn("[DrillThrough] Event missing targetDashboardId. This interaction needs to be reconfigured with a target dashboard.",e);return}const i=s.flatMap(f=>f.filters),a=((u=t.getCurrentDashboardId)==null?void 0:u.call(t))||"",l=(d=t.getCurrentDashboardTitle)==null?void 0:d.call(t);t.setGlobalDrillContext&&t.setGlobalDrillContext({filters:i,contextMode:r,sourceDashboardId:a,sourceDashboardTitle:l,targetDashboardId:n}),t.setPendingDrillThrough&&t.setPendingDrillThrough({targetDashboardId:n,sourceDashboardId:a,sourceDashboardTitle:l,filters:i,contextMode:r})}function iyt(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 ayt({open:e,onOpenChange:t,insightId:n,filters:r,filterDefinitions:s,contextMode:o,cardTitle:i,cardDescription:a}){return c.jsx(yo,{open:e,onOpenChange:t,children:c.jsxs(Js,{className:"max-h-[90vh] max-w-[90vw] p-6",children:[c.jsxs(Bi,{children:[c.jsx(eo,{children:i||"Insight Detail"}),c.jsx(Bo,{children:a||"View detailed insight data with applied filters"})]}),c.jsx(hoe,{filters:r,filterDefinitions:s,contextMode:o}),c.jsx("div",{className:"h-[400px] flex-1 overflow-auto",children:n?c.jsx(joe,{insightId:n,filters:r,contextMode:o}):c.jsx("div",{className:"flex items-center justify-center p-12 text-muted-foreground",children:"No insight selected"})})]})})}function lyt(){const e=p.useInteractionStore(C=>C.interactionStates),t=p.useInteractionStore(C=>C.setInteractionState),n=p.useInteractionStore(C=>C.clearLastInteractionEvent),r=p.useInteractionStore(C=>C.replaceCardWithInsight),s=p.useInteractionStore(C=>C.setPendingDrillThrough),o=p.useInteractionStore(C=>C.pendingDrillThrough),i=p.useInteractionStore(C=>C.clearPendingDrillThrough),{setSelectedSheetId:a,navigateWithDrill:l}=p.useDashboardActions(),{selectDashboard:u}=ah(),d=p.useDashboardStore(C=>C.dashboard),f=p.useDashboardStore(C=>C.filterValues),{data:h,isLoading:m}=qW((o==null?void 0:o.targetDashboardId)||"",{enabled:!!(o!=null&&o.targetDashboardId)}),[g,b]=S.useState({open:!1,insightId:""}),x=Eoe(g.insightId,{enabled:g.open&&!!g.insightId}),y=S.useRef(new Set),w=S.useMemo(()=>({setSelectedSheetId:a,openInsightModal:({insightId:C,filters:N,contextMode:k})=>{b({open:!0,insightId:C,filters:N,filterDefinitions:(d==null?void 0:d.filters)||[],contextMode:k})},replaceCardContent:({cardId:C,insightId:N,filters:k,contextMode:_})=>{r(C,N,k,_)},getCurrentFilters:()=>f||[],navigateWithDrill:l,getCurrentDashboardId:()=>(d==null?void 0:d.id)||"",getCurrentDashboardTitle:()=>d==null?void 0:d.title,setPendingDrillThrough:s,setGlobalDrillContext:({filters:C,contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:j})=>{const I={filters:C},E={sourceCardId:p.DRILL_CONTEXT_CARD_ID,interactionMode:"clickFilter",filterGroups:[I]},T={...p.createInitialInteractionState(),appliedClickFilters:[E],contextMode:N,sourceDashboardId:k,sourceDashboardTitle:_,targetDashboardId:j};t(p.DRILL_CONTEXT_CARD_ID,T)}}),[a,r,f,l,d,s,t]);S.useEffect(()=>{Object.entries(e).forEach(([C,N])=>{if(N!=null&&N.lastInteractionEvent){const k=N.lastInteractionEvent,_=`${C}-${k.interactionMode}-${k.sourceCardId}-${Date.now()}`;if(y.current.has(_))return;y.current.add(_);try{ryt(k,w)}catch(j){console.error("Error executing interaction event:",j)}finally{n(C),setTimeout(()=>{y.current.delete(_)},5e3)}}})},[e,n,w]),S.useEffect(()=>{if(!(!o||!h||m))try{u(h),l(o.targetDashboardId,o.sourceDashboardId,o.sourceDashboardTitle,o.filters,o.contextMode),i()}catch(C){console.error("[DrillThrough] Error during automatic navigation:",C),i()}},[o,h,m,u,l,i]);const v=()=>{b({open:!1,insightId:""})};return c.jsxs(c.Fragment,{children:[c.jsx(ayt,{open:g.open,onOpenChange:v,insightId:g.insightId,filters:g.filters,filterDefinitions:g.filterDefinitions,contextMode:g.contextMode,cardTitle:x.title,cardDescription:x.description}),o&&m&&c.jsx("div",{className:"fixed inset-0 z-[51] flex items-center justify-center bg-background/80 backdrop-blur-sm",children:c.jsxs("div",{className:"flex flex-col items-center gap-2.5 rounded-[6px] border border-border/60 bg-background px-4 py-3 shadow-sm",children:[c.jsx(p.LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground/60"}),c.jsx("div",{className:"text-[12px] text-muted-foreground",children:"Loading dashboard..."})]})})]})}function cyt(e){return e.length===0?"":e.map(t=>{const n=t.field.label||t.field.name,r=t.operator,s=uyt(t.value);return r==="="?`${n} = ${s}`:`${n} ${r} ${s}`}).join(", ")}function uyt(e){return e==null?"null":Array.isArray(e)?e.join(", "):typeof e=="object"&&e.toString?e.toString():String(e)}function dyt(e){return e?`Back to ${e}`:"Back"}function fyt(){var y,w,v,C,N;const e=p.useInteractionStore(k=>k.interactionStates[p.DRILL_CONTEXT_CARD_ID]),t=p.useDashboardStore(k=>k.actions.goBackFromDrill),n=p.useDashboardStore(k=>k.actions.clearDrillContext),{selectDashboard:r}=ah(),[s,o]=S.useState({x:16,y:16}),[i,a]=S.useState(!1),l=S.useRef({x:0,y:0});S.useEffect(()=>{if(!i)return;const k=j=>{o({x:j.clientX-l.current.x,y:j.clientY-l.current.y})},_=()=>{a(!1)};return document.addEventListener("mousemove",k),document.addEventListener("mouseup",_),()=>{document.removeEventListener("mousemove",k),document.removeEventListener("mouseup",_)}},[i]);const u=e==null?void 0:e.sourceDashboardId,d=e==null?void 0:e.sourceDashboardTitle,f=((C=(v=(w=(y=e==null?void 0:e.appliedClickFilters)==null?void 0:y[0])==null?void 0:w.filterGroups)==null?void 0:v[0])==null?void 0:C.filters)||[],h=u?{id:u,title:d||"Previous Dashboard",description:"",isPrivate:!1,isPublic:!1,version:"",createdBy:null,createdByTenantUser:"",tenantId:"",projectId:"",createdAt:"",updatedAt:"",lastModified:"",lastModifiedBy:"",createdByUser:null,createdByTenantUserRel:{name:"",email:""},permissions:{canEdit:!0,canShare:!0,canDelete:!0},ownership:{status:"private",isOwner:!0,sharedCount:0,createdBy:{type:"user",userId:"",name:"",email:""}}}:null;if(!e||!((N=e.appliedClickFilters)!=null&&N.length))return null;const m=()=>{if(!h){console.warn("[DrillBack] No source dashboard in context");return}try{t(),r(h)}catch(k){console.error("[DrillBack] Error during back navigation:",k)}},g=()=>{n()},b=k=>{k.target.closest("button")||(a(!0),l.current={x:k.clientX-s.x,y:k.clientY-s.y})};cyt(f);const x=dyt(d);return c.jsx("div",{className:"fixed z-50 max-w-md",style:{left:0,top:0,transform:`translate(${s.x}px, ${s.y}px)`,transition:i?"none":void 0},children:c.jsxs("div",{className:"select-none rounded-lg border bg-background/95 p-3 shadow-lg backdrop-blur-sm",onMouseDown:b,style:{cursor:i?"grabbing":"grab"},children:[c.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[c.jsxs("div",{className:"flex flex-col gap-2",children:[c.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Viewing:"}),c.jsx("div",{className:"flex flex-wrap gap-2",children:f.map((k,_)=>{const j=k.field.label||k.field.name,I=String(k.value);return c.jsxs(rs,{variant:"secondary",className:"pointer-events-none text-xs",children:[j," = ",I]},_)})})]}),c.jsx(p.Button,{variant:"ghost",size:"sm",onClick:g,className:"h-6 w-6 cursor-pointer p-0",title:"Clear drill context",children:c.jsx(p.X,{className:"h-3 w-3"})})]}),c.jsx("div",{className:"flex items-center gap-2 border-t pt-2",children:c.jsxs(p.Button,{variant:"secondary",size:"sm",onClick:m,disabled:!h,className:"w-full cursor-pointer",children:[c.jsx(f0,{className:"mr-2 h-4 w-4"}),x]})})]})})}function hyt(e,t){return typeof e=="boolean"?e:typeof t=="boolean"?t:!1}function myt({filter:e,isEditing:t=!1,disabled:n=!1,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:l,onRemoveFilter:u}){const{attributes:d,listeners:f,setNodeRef:h,transform:m,transition:g,isDragging:b}=Ig({id:`filter:${e.id}`,disabled:n||!t}),x={transform:di.Translate.toString(m),transition:g,opacity:b?.5:1,zIndex:b?10:void 0};return c.jsx("div",{ref:h,style:x,...d,children:c.jsx(m5,{filter:e,isEditing:t,dragListeners:t?f:void 0,storageOptions:r,settingsVariant:s,filterQueryContext:o,inputVariableName:i,reservedInputVariableNames:a,onUpdateFilter:l,onRemoveFilter:u})})}const dU="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",pyt=[];function Zde({open:e,onOpenChange:t}){var L,$,B;const[n,r]=S.useState(!1),[s,o]=S.useState(!1),[i,a]=S.useState({sheetSelection:"current",protectPdf:!1,password:""}),l=p.useDashboardStore(V=>{var F;return(F=V.dashboard)==null?void 0:F.sheets}),u=p.useDashboardStore(V=>V.dashboard),d=p.useDashboardStore(V=>V.dashboardInputValues),f=p.useDashboardStore(V=>V.filterValues),h=p.useDashboardStore(V=>V.controlValues),m=p.useDashboardStore(V=>V.inlineFilterValuesMap),g=p.useDashboardStore(V=>V.cardControlValuesMap),b=p.useDashboardStore(V=>V.selectedSheetId),x=p.useDashboardStore(V=>V.selectedSheetId?V.documentInputRuntimeBySheetId[V.selectedSheetId]:void 0),y=p.useDashboardStore(V=>V.isDownloadingPdf),{authToken:w,tokenProps:v}=mt(),C=l==null?void 0:l.find(V=>V.id===b),N=S.useMemo(()=>p.getDashboardExportSheets(l),[l]),k=p.isDocumentSheet(C),_=k&&C?C.document:void 0,j=S.useMemo(()=>k&&C?kv(u,C.id):[],[C,k,u]),I=j.length>0,E=S.useMemo(()=>k&&C?ule(u,C.id):!1,[C,k,u]),T=S.useMemo(()=>I?j.map(_v):(_==null?void 0:_.inputs)||pyt,[_,j,I]),D=(($=(L=v==null?void 0:v.params)==null?void 0:L.calendarContext)==null?void 0:$.tz)||((B=v==null?void 0:v.params)==null?void 0:B.timezone)||(typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0),A=S.useMemo(()=>uae(T),[T]),P=S.useMemo(()=>lae(T,D),[T,D]),R=S.useMemo(()=>cae(T),[T]),H=x?x.filterValuesByInputId:P,z=x?x.controlValuesByInputId:R,U=S.useMemo(()=>k?E&&C&&_?CK({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(V=>V.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},timezone:D}):hae(T,H,z,A,A):[],[_,T,C,k,u,g,h,f,m,d,z,H,A,D,E]),W=!!C,O=N.length>0,Z=((l==null?void 0:l.length)||0)>1||k,Y=i.sheetSelection==="current"&&(!W||k&&U.length>0)||i.sheetSelection==="all"&&!O;S.useEffect(()=>{e&&i.sheetSelection==="all"&&!O&&a(V=>({...V,sheetSelection:"current"}))},[O,e,i.sheetSelection]);const M=()=>{a({sheetSelection:"current",protectPdf:!1,password:""}),r(!1),t(!1)};async function K(){if(y){tt.error("A PDF export is already in progress");return}if(i.protectPdf&&!i.password){tt.error("Please enter a password to protect the PDF");return}if(i.sheetSelection==="current"&&!W){tt.error("No sheet is selected to export");return}if(i.sheetSelection==="all"&&!O){tt.error("No dashboard sheets are available to export");return}o(!0);const V=i.sheetSelection==="current"&&k,F=V?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",q=tt.loading(F);try{if(V){if(!_||!C)throw new Error("Selected document sheet is missing document data");if(U.length>0){tt.dismiss(q),tt.error(`Set ${U.join(", ")} before exporting`);return}const X=new Date().toISOString(),J=E?kK({dashboard:u,sheetId:C.id,sheetKind:"document",sectionIds:_.sections.map(fe=>fe.id),mode:"document",runtimeValues:{dashboardInputValues:d,filterValues:f,controlValues:h,inlineFilterValuesMap:m,cardControlValuesMap:g},generatedAt:X,timezone:D}).snapshot:void 0;await RF(v.apiServiceUrl,w,{sheetId:C.id,title:C.title||"Document",pageSize:_.page.size,orientation:_.page.orientation,timezone:D,password:i.protectPdf?i.password:void 0,inputSnapshot:J,...J?{}:{inputValues:{sheetId:C.id,filterValuesByInputId:H,controlValuesByInputId:z,generatedAt:X}}})}else{const X=JQ();await MK(v.apiServiceUrl,w,i.protectPdf?i.password:void 0,i.sheetSelection,X)}tt.dismiss(q);const G=V?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!";tt.success(G,{duration:2e3}),M()}catch(G){tt.dismiss(q),tt.error("Failed to download PDF",{description:xk(G,"Please try again or contact support."),descriptionClassName:bk,closeButton:!0,duration:1/0,richColors:!0}),console.error("PDF download error:",G)}finally{o(!1)}}return c.jsx(yo,{open:e,onOpenChange:V=>{if(!V){M();return}t(!0)},children:c.jsxs(Js,{className:"rounded-control border-border/60 sm:max-w-[440px] sm:rounded-control",children:[c.jsxs(Bi,{children:[c.jsx(eo,{className:"text-[15px]",children:k?"Export document":"Export dashboard"}),c.jsx(Bo,{className:"text-[13px] leading-5",children:k?"Export this document sheet as a PDF document.":"Export this dashboard as a PDF document."})]}),c.jsxs("div",{className:"space-y-4 py-1",children:[Z&&c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"space-y-2",children:[c.jsx(p.Label,{className:dU,children:"Export scope"}),c.jsxs(ma,{value:i.sheetSelection,onValueChange:V=>a({...i,sheetSelection:V}),className:"gap-1.5",children:[c.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",!W&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[c.jsx(ps,{value:"current",id:"scope-current",disabled:!W}),k?"This document":"This sheet"," (",(C==null?void 0:C.title)||"Current",")"]}),c.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",!O&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[c.jsx(ps,{value:"all",id:"scope-all",disabled:!O}),"Dashboard sheets (",N.length," ",N.length===1?"sheet":"sheets",")"]})]}),k&&c.jsx("p",{className:"text-[12px] leading-5 text-muted-foreground",children:U.length>0?`Set ${U.join(", ")} before exporting this document.`:'"Dashboard sheets" includes dashboard sheets only. Choose "This document" to export the selected document.'})]}),c.jsx(p.Separator,{className:"bg-border/60"})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsxs(p.Label,{htmlFor:"protect-pdf",className:"flex cursor-pointer items-center gap-2 text-[13px] font-normal",children:[c.jsx(En,{id:"protect-pdf",checked:i.protectPdf,onCheckedChange:V=>{a({...i,protectPdf:V,password:V?i.password:""}),V||r(!1)}}),c.jsx(FN,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Password protect PDF"]}),i.protectPdf&&c.jsxs("div",{className:"ml-6 space-y-1.5",children:[c.jsx(p.Label,{htmlFor:"pdf-password",className:dU,children:"Password"}),c.jsxs("div",{className:"relative",children:[c.jsx(p.Input,{id:"pdf-password",size:"xs",type:n?"text":"password",value:i.password,onChange:V=>a({...i,password:V.target.value}),placeholder:"Enter password",className:"pr-8",onKeyDown:V=>{V.key==="Enter"&&i.password&&K()}}),c.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?c.jsx(RN,{className:"h-3.5 w-3.5"}):c.jsx(h0,{className:"h-3.5 w-3.5"})})]}),c.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Recipients will need this password to open the PDF."})]})]})]}),c.jsxs(vc,{children:[c.jsx(p.Button,{variant:"outline",size:"xs",onClick:M,disabled:s,children:"Cancel"}),c.jsx(p.Button,{size:"xs",onClick:K,disabled:s||y||Y,children:s?c.jsxs(c.Fragment,{children:[c.jsx(p.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Exporting…"]}):c.jsxs(c.Fragment,{children:[c.jsx(xc,{className:"h-3.5 w-3.5"}),"Export"]})})]})]})})}function Xde({iconClassName:e,open:t,onOpenChange:n}){const[r,s]=S.useState(!1),o=t!==void 0,i=o?t:r,a=u=>{o||s(u),n==null||n(u)},l=p.useDashboardStore(u=>u.isDownloadingPdf);return c.jsxs(c.Fragment,{children:[o?null:c.jsx(p.Button,{variant:"ghost",size:"sm",className:"h-7 p-2",disabled:l,onClick:()=>a(!0),children:c.jsx(xc,{className:p.cn("size-4",e)})}),c.jsx(Zde,{open:i,onOpenChange:a})]})}function fU(e,t,n){const r=new Set(t),s=[...n];return e.map(o=>r.has(o.id)?s.shift()??o.id:o.id)}function gyt({control:e,value:t,isEditing:n=!1,onChange:r}){const{attributes:s,listeners:o,setNodeRef:i,transform:a,transition:l,isDragging:u}=Ig({id:`control:${e.id}`,disabled:!n}),d={transform:di.Translate.toString(a),transition:l,opacity:u?.5:1,zIndex:u?10:void 0};return c.jsx("div",{ref:i,style:d,...s,children:c.jsx(jae,{control:e,value:t,isEditing:n,dragListeners:n?o:void 0,onChange:r})})}function hU(e){var t;return(((t=e.values)==null?void 0:t.length)??0)>0||e.operation==="is null"||e.operation==="is not null"}function mU(e,t){return[...e.map(n=>`filter:${n.id}`),...t.map(n=>`control:${n.id}`)]}function byt(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 mU(t,n);const s=e.filter(a=>r.has(a)),o=new Set(s),i=mU(t,n).filter(a=>!o.has(a));return[...s,...i]}function xyt(e,t){return p.getDashboardCardEntries({sheets:e.sheets||[]}).filter(n=>n.sheet.id===t).map(n=>n.card.id)}function yyt(e){return op(e.dashboardInput,{sheetId:e.selectedSheetId,sheetKind:"dashboard"})?!0:e.dashboardInput.scope.kind!=="cards"?!1:e.selectedSheetCardIds.some(t=>op(e.dashboardInput,{sheetId:e.selectedSheetId,cardId:t,sheetKind:"dashboard"}))}function pU(e){var t;return((t=e.compatibility)==null?void 0:t.source)!=="dashboardFilter"}function vyt(e){const t={sheetId:e.selectedSheetId},n=p.getDashboardInputRuntimeSlot(e.dashboardInputValues,e.dashboardInput,t);if(n)return n;const r=p.getDashboardInputRuntimeSlot(e.defaultInputValues,e.dashboardInput,t);return r||p.getBackingDefaultSlot(e.dashboardInput)}function wyt(e){return Qde(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 Qde(e){if(!e.selectedSheetId)return[];const t=e.selectedSheetId,n=xyt(e.dashboard,t);return HG(uk({dashboard:e.dashboard}).allInputs).filter(r=>!(r.kind!=="filter"||!yyt({dashboardInput:r,selectedSheetId:t,selectedSheetCardIds:n})))}function Syt(e,t){return"toolbar"}function Cyt(){const e=Sc("interactive"),t=p.useDashboardStore($=>$.selectedSheetId),n=p.useDashboardStore($=>$.dashboard.filters),r=p.useDashboardStore($=>$.dashboard.filterLayout),s=p.useDashboardStore($=>$.isDashboardEditing),o=p.useDashboardStore($=>$.controlValues),i=p.useDashboardStore($=>$.filterValues);p.useDashboardStore($=>$.filteringCards);const a=p.useDashboardStore($=>$.inlineFilterValuesMap),l=p.useDashboardStore($=>$.dashboardInputValues),u=p.useInteractionStore($=>$.clearAllClickFilters),d=p.useInteractionStore($=>Object.entries($.interactionStates).reduce((B,[V,F])=>{var q;return V===p.DRILL_CONTEXT_CARD_ID?B:B+(((q=F.appliedClickFilters)==null?void 0:q.length)??0)},0)),f=p.useDashboardStore($=>$.actions.removeCardInlineFilterValue),{reorderFilters:h,clearDashboardInputSlot:m,reorderDashboardControls:g,removeDashboardInput:b,setControlValue:x,setFilterLayout:y,setFilterValues:w,setFilteringCards:v,upsertDashboardInput:C}=p.useDashboardActions(),N=F_(Ep(jg,{activationConstraint:{distance:5}})),k=p.useDashboardStore($=>$.dashboard),_=wyt({dashboard:k,selectedSheetId:t}).filter($=>Syt($.filter)==="toolbar"),j=Qde({dashboard:k,selectedSheetId:t}),I=_.map($=>$.filter),E=new Map(_.map($=>[`filter:${$.filter.id}`,$])),T=DWe(k),D=T.filter($=>!$.hidden&&Ay($)==="toolbar"),A=T.filter($=>!$.hidden&&Ay($)==="advanced"),P=byt(r==null?void 0:r.toolbarItemOrder,I,D),R=new Map(I.map($=>[`filter:${$.id}`,$])),H=new Map(D.map($=>[`control:${$.id}`,$]));function z($){const{active:B,over:V}=$;if(!V||B.id===V.id)return;const F=String(B.id),q=String(V.id),G=P.findIndex(ae=>ae===F),X=P.findIndex(ae=>ae===q);if(G===-1||X===-1)return;const J=Eg(P,G,X);y({toolbarItemOrder:J});const fe=new Set((n||[]).map(ae=>ae.id)),ue=P.filter(ae=>ae.startsWith("filter:")).map(ae=>ae.replace("filter:","")).filter(ae=>fe.has(ae)),pe=J.filter(ae=>ae.startsWith("filter:")).map(ae=>ae.replace("filter:","")).filter(ae=>fe.has(ae)),ye=P.filter(ae=>ae.startsWith("control:")).map(ae=>ae.replace("control:","")),ie=J.filter(ae=>ae.startsWith("control:")).map(ae=>ae.replace("control:",""));h(fU(n||[],ue,pe)),g(fU(k.controls||[],ye,ie))}const U=(r==null?void 0:r.toolbarWrap)??!1,W=(r==null?void 0:r.showDownloadButton)??!1,O=(i==null?void 0:i.filter($=>hU($)).length)??0,Z=j.filter(pU),Y=Z.filter($=>{const B=vyt({dashboardInput:$,dashboardInputValues:l,defaultInputValues:k.defaultInputValues,selectedSheetId:t});return(B==null?void 0:B.status)==="set"&&B.value.kind==="filter"&&hU(B.value.filterValue)}).length,M=a?Object.values(a).reduce(($,B)=>$+((B==null?void 0:B.length)??0),0):0,K=O+Y+M+d,L=()=>{w([]),Z.forEach($=>{m($,{sheetId:t})}),v([]),u(),a&&Object.entries(a).forEach(([$,B])=>{B==null||B.forEach(V=>{f($,V.filterId)})})};return!I.length&&!D.length&&!A.length&&!W&&K===0?null:c.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:c.jsx(yv,{sensors:N,collisionDetection:gv,onDragEnd:z,children:c.jsxs("div",{className:p.cn("flex items-center",U?"flex-wrap":"w-0 min-w-full overflow-x-auto"),children:[c.jsx(vv,{items:P,strategy:H5,children:c.jsx(kA,{className:"gap-3 pr-0",wrap:U,children:P.map($=>{const B=R.get($);if(B){const F=E.get($),q=F&&pU(F);return c.jsx(myt,{filter:B,isEditing:s,storageOptions:q?{storageTarget:"dashboardInput",dashboardInput:F,sheetId:t??void 0}:void 0,inputVariableName:q?F.variableName:void 0,onUpdateFilter:q?(G,X)=>{C({...F,variableName:(X==null?void 0:X.variableName)||F.variableName,filter:G})}:void 0,onRemoveFilter:q?()=>{w((i||[]).filter(G=>G.filterId!==B.id)),b(F.id)}:void 0},$)}const V=H.get($);return V?c.jsx(gyt,{control:V,value:o==null?void 0:o[V.id],isEditing:s,onChange:F=>x(V.id,F)},$):null})})}),A.length>0&&c.jsx(Soe,{title:"",controls:A,values:o,onChange:($,B)=>x($.id,B),immediatePlacement:"toolbar",advancedLabel:"More controls"}),K>0&&c.jsxs("button",{type:"button",onClick:L,"aria-label":"Clear all filters",className:"ml-auto inline-flex h-7 shrink-0 items-center gap-1 rounded-control px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[c.jsx(p.X,{className:"h-3 w-3"}),"Clear all",c.jsx("span",{className:"rounded-[3px] bg-muted px-1 text-[10px] tabular-nums text-muted-foreground",children:K})]}),W&&c.jsx("div",{className:p.cn(K>0?"ml-1.5":"ml-auto"),children:c.jsx(Xde,{})})]})})})}function Jde(){var ne,he;const{showAssistant:e,tokenProps:t,renderMode:n}=mt(),r=hyt((ne=t.config)==null?void 0:ne.showDashboardAssistant,e),{preferences:s,isConsoleMode:o}=Pp(),i=(he=s==null?void 0:s.cardDisplay)==null?void 0:he.mode,a=bh(i),l=aK({displayMode:i,renderMode:n}),u=S.useRef(null),d=S.useRef(null),[f,h]=S.useState(!1),{handleDragStart:m,isDraggingRef:g,getStyle:b,getPositionClasses:x}=irt({initialPosition:"bottom-right"}),y=hf(ee=>ee.setFullscreen),w=hf(ee=>ee.setPanelOpen),v=hf(ee=>ee.setContainer),C=ZY("dashboard"),N=XY(),k=QY("dashboard"),_=C.isOpen,j=N==="dashboard",I=p.useDashboardStore(ee=>ee.isVisualEditing),E=p.useDashboardStore(ee=>ee.themeStyle),T=dl(),D=p.useDashboardStore(ee=>{var Ce;return(Ce=ee.dashboard)==null?void 0:Ce.sheets}),A=p.useDashboardStore(ee=>ee.showFilters),P=p.useDashboardStore(ee=>ee.isDashboardEditing),R=p.useDashboardStore(ee=>ee.selectedSheetId),H=D==null?void 0:D.find(ee=>ee.id===R),z=p.useDashboardStore(ee=>{var Ce,ve,te;return(te=(ve=(Ce=ee.dashboard)==null?void 0:Ce.sheets)==null?void 0:ve.find(_e=>_e.id===ee.selectedSheetId))==null?void 0:te.kind}),U=p.useDashboardStore(ee=>{var Ce,ve;return((ve=(Ce=ee.dashboard)==null?void 0:Ce.summary)==null?void 0:ve.position)||"top"}),W=z==="document",O=p.useDashboardStore(ee=>{var Ce;return(Ce=ee.dashboard)==null?void 0:Ce.id}),Z=p.useDashboardStore(ee=>ee.isDashboardPanelOpen),Y=p.useDashboardStore(ee=>ee.actions.setIsDashboardPanelOpen),{getDefaultSheetId:M,setDefaultSheetId:K,clearDefaultSheetId:L}=eq(O),[$,B]=S.useState(null);UN($r.DASHBOARD);const{setSelectedSheetId:V,setSheetTitle:F,addSheet:q,setSheets:G}=p.useDashboardActions();eyt(d);const{setActiveAssistantType:X}=p.useAIActions();S.useEffect(()=>{if(O){const ee=M();B(ee)}},[O,M]),S.useEffect(()=>{_?X("dashboard"):N==="dashboard"&&y(null)},[_,X,N,y]),S.useEffect(()=>{var ee;_||(ee=u.current)==null||ee.resize(0)},[_]);function J(ee){var Ce,ve;ee?((Ce=u.current)==null||Ce.resize(40),w("dashboard",!0),y("dashboard"),X("dashboard")):(w("dashboard",!1),y(null),(ve=u.current)==null||ve.resize(0),X(null))}function fe(ee="dashboard"){const Ce={id:p.v4(),title:ee==="document"?"New Document":"New Sheet",...ee==="document"?{kind:ee,document:p.createDefaultDocumentDefinition()}:{}};q(Ce),V(Ce.id)}function ue(ee,Ce){if(!O)return;$===ee?(L(),B(null),tt.success("Default sheet cleared")):(K(ee),B(ee),tt.success(`"${Ce}" set as default sheet`))}function pe(ee){var Ce;ee<1?(w("dashboard",!1),y(null),X(null),(Ce=u.current)==null||Ce.resize(0)):(_||w("dashboard",!0),X("dashboard"))}function ye(){return(E==null?void 0:E.canvasTheme)==="muted"||!(E!=null&&E.canvasTheme)?"hsl(var(--semaphor-muted))":(E==null?void 0:E.canvasTheme)==="clear"?"":E==null?void 0:E.canvasTheme}const ie=(ee,Ce)=>{ee.dataTransfer.setData("tabIndex",Ce.toString())},ae=ee=>{ee.preventDefault()},se=(ee,Ce)=>{const ve=ee.dataTransfer.getData("tabIndex");if(ve===Ce.toString())return;const te=Array.from(D||[]),[_e]=te.splice(parseInt(ve),1);te.splice(Ce,0,_e),G(te)},Ie=t.orgUserId||t.tenantId&&t.endUserId&&t.endUserEmail,oe=r===!0&&!a&&!_&&!I&&!A;function me(){if(D&&D.length>1||P)return c.jsxs("div",{className:"relative flex w-full items-stretch border-b border-border",children:[o&&Ie&&!Z&&c.jsx("button",{type:"button","aria-label":"Toggle dashboards panel",onClick:()=>{Y(!Z)},className:"group/panel mx-2 inline-flex h-9 shrink-0 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",children:c.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-[4px] group-hover/panel:bg-muted",children:c.jsx(Dq,{className:"h-3.5 w-3.5",strokeWidth:1.75})})}),c.jsxs("div",{className:"relative min-w-0 flex-1",children:[c.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"}),c.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"}),c.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:[D==null?void 0:D.map((ee,Ce)=>{const ve=R===ee.id,te=$===ee.id;return c.jsxs(p.TabsTrigger,{draggable:!0,onDragStart:_e=>ie(_e,Ce),onDragOver:ae,onDrop:_e=>se(_e,Ce),onClick:()=>V(ee.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:ee.id,children:[ee.kind==="document"&&c.jsx(oi,{className:"h-3 w-3 text-muted-foreground"}),c.jsx(UC,{enabled:P&&ve,text:ee.title,onSave:_e=>F(ee.id,_e),children:ee.title},ee.id),c.jsx("span",{role:"button",tabIndex:0,"aria-label":te?"Clear default sheet":"Set as default sheet",title:te?"Clear default sheet":"Set as default sheet",onClick:_e=>{_e.stopPropagation(),ue(ee.id,ee.title||"Sheet")},onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),_e.stopPropagation(),ue(ee.id,ee.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",ve||te?"opacity-100":"opacity-0 group-hover:opacity-100"),children:c.jsx(kR,{className:p.cn("h-3 w-3 transition-colors",te?"fill-current text-amber-500":"text-muted-foreground")})}),P&&ve&&D.length>1&&c.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:_e=>{_e.stopPropagation(),h(!0)},onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),_e.stopPropagation(),h(!0))},children:c.jsx(p.X,{className:"h-3 w-3"})})]},ee.id)}),P&&c.jsxs(po,{children:[c.jsx(go,{asChild:!0,children:c.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:[c.jsx(wr,{className:"h-3 w-3"}),"Sheet"]})}),c.jsxs(Ks,{align:"start",className:"w-48",children:[c.jsxs(bn,{onSelect:()=>fe("dashboard"),children:[c.jsx(ep,{className:"h-4 w-4 text-muted-foreground"}),"Dashboard sheet"]}),c.jsxs(bn,{onSelect:()=>fe("document"),children:[c.jsx(oi,{className:"h-4 w-4 text-muted-foreground"}),"Document"]})]})]})]})]})]})}function we(){return c.jsx("div",{ref:d,style:{},className:"h-full min-h-0 grow",children:D==null?void 0:D.map(ee=>c.jsx(p.TabsContent,{style:{backgroundColor:ye(),...T.dashboardCanvasStyle},className:p.cn("mt-0 h-full min-h-0",{}),value:ee.id,children:c.jsx(l7,{sheet:ee})},ee.id))})}function ge(){return c.jsxs(p.Tabs,{"data-role":"dashboard-tabs-container",className:p.cn("relative flex h-full flex-col",E==null?void 0:E.dashboardTabsContainer),onValueChange:ee=>{V(ee)},value:R||void 0,children:[me(),U==="top"&&!W&&c.jsx(oA,{}),R&&!W&&c.jsx(Cyt,{}),W?c.jsx("div",{"data-role":"dashboard-tabs-content",className:"min-h-0 flex-1 grow basis-0 overflow-hidden",children:we()}):c.jsx(bl,{"data-role":"dashboard-tabs-content",className:"flex-1 grow basis-0 overflow-y-auto",children:we()}),U==="bottom"&&!W&&c.jsx(oA,{}),c.jsx(art,{open:f,setOpen:h})]})}const re=S.useCallback(ee=>{v("dashboard",ee)},[v]);return D?l&&R&&!W?c.jsxs("div",{"data-document-render-error":"true",className:"bg-white p-8 text-sm text-zinc-700",children:['Requested document sheet "',R,'" was not found or is not a document sheet in the loaded dashboard.']}):l&&W&&H?c.jsx("div",{"data-role":"dashboard-document-print-content",className:"min-h-0 overflow-visible bg-white",children:c.jsx(l7,{sheet:H})}):c.jsxs(c.Fragment,{children:[c.jsx(lyt,{}),c.jsx(fyt,{}),c.jsxs("div",{className:"relative flex-1 basis-0 overflow-hidden",children:[c.jsxs(Rle,{className:p.cn("flex-1 basis-0 overflow-y-auto transition-opacity",j&&"pointer-events-none opacity-0"),direction:"horizontal",children:[c.jsx(TA,{children:ge()}),r===!0&&c.jsxs(c.Fragment,{children:[c.jsx(ort,{open:_,onTabClick:J,withHandle:!0,disabled:!_}),c.jsx(TA,{className:"flex grow","data-role":"dashboard-assistant-panel",onResize:pe,defaultSize:_?40:0,ref:u,children:c.jsx("div",{className:"grow overflow-y-auto",children:c.jsx(Jxt,{open:_,setOpen:J,isFullscreen:j,onFullscreenChange:ee=>y(ee?"dashboard":null),fullscreenContainer:k})})})]})]}),c.jsx("div",{ref:re,className:p.cn("absolute inset-0",!j&&"pointer-events-none")}),oe&&c.jsx("div",{className:p.cn("absolute z-50 transition-all duration-300 ease-in-out",x().horizontal,x().vertical),style:b(),children:c.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:()=>{g.current||J(!0)},onMouseDown:m,onTouchStart:m,title:"Open Assistant (drag to move)",children:c.jsx(zme,{className:"h-5 w-5"})})})]})]}):null}const efe=S.forwardRef(({appearance:e,organizationAppearance:t,tokenAppearance:n,reactAppearance:r,resolvedAppearance:s,children:o,className:i,style:a,...l},u)=>{const d=S.useId(),f=S.useMemo(()=>Nyt(d),[d]),{theme:h}=lR(),m=kyt(h),g=S.useMemo(()=>s??bc.resolveAppearance({organizationAppearance:t,tokenAppearance:n,reactAppearance:r??e}),[e,t,r,s,n]),b=S.useMemo(()=>p.compileAppearance({spec:g,systemMode:m}),[g,m]),x=S.useMemo(()=>p.createAppearanceContextValue(f,b),[b,f]);return c.jsx(p.AppearanceContext.Provider,{value:x,children:c.jsx(Sg,{...l,ref:u,className:i,style:a,children:o})})});efe.displayName="AppearanceProvider";function Nyt(e){return`semaphor-appearance-${e.replace(/[^a-zA-Z0-9_-]/g,"")}`}function kyt(e){const t=S1(e),[n,r]=S.useState(()=>_yt());return S.useEffect(()=>{var i,a;if(t!=="system"||typeof window>"u")return;const s=(i=window.matchMedia)==null?void 0:i.call(window,"(prefers-color-scheme: dark)");if(!s)return;const o=()=>{r(s.matches?"dark":"light")};return o(),typeof s.addEventListener=="function"?(s.addEventListener("change",o),()=>s.removeEventListener("change",o)):((a=s.addListener)==null||a.call(s,o),()=>{var l;return(l=s.removeListener)==null?void 0:l.call(s,o)})},[t]),t==="system"?n:t}function _yt(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}const tfe=S.createContext({openBrandStudioPreview:()=>{}}),jyt=tfe.Provider;function Eyt(){return S.useContext(tfe)}function Iyt({children:e,defaultTheme:t="system",storageKey:n="vite-ui-theme",...r}){const s=S1(t),[o,i]=S.useState(()=>Tyt(n)||s),a=S.useCallback(u=>{const d=S1(u);Dyt(n,d),i(d)},[n]),l=S.useMemo(()=>({theme:o,setTheme:a}),[o,a]);return c.jsx(MU.Provider,{...r,value:l,children:e})}function Tyt(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const n=S1(t,"system");return n===t?n:null}catch{return null}}function Dyt(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}}const Myt=S.lazy(()=>Promise.resolve().then(()=>require("../brand-studio/index.cjs")).then(e=>({default:e.BrandStudioEditor})));function b3({appearance:e,children:t}){var T,D;const{authToken:n,id:r,tokenProps:s}=mt(),o=u0(),i=(T=o.data)==null?void 0:T.organizationAppearance,a=(D=s.config)==null?void 0:D.appearance,[l,u]=S.useState(!1),[d,f]=S.useState(null),[h,m]=S.useState(null),[g,b]=S.useState(null),[x,y]=S.useState(null),w=`${s.apiServiceUrl??""}:${(n==null?void 0:n.accessToken)??""}`,v=jn({queryKey:zW({resourceType:$r.DASHBOARD,apiServiceUrl:s.apiServiceUrl,accessToken:n==null?void 0:n.accessToken}),queryFn:async()=>p.getRequest(`${s.apiServiceUrl}/management/v1/dashboards`,(n==null?void 0:n.accessToken)||""),select:A=>(A==null?void 0:A.organizationAppearance)??null,enabled:!o.dashboardIdToFetch&&i===void 0&&!!(n!=null&&n.accessToken)});S.useEffect(()=>{i!==void 0&&y({scopeKey:w,appearance:i})},[i,w]),S.useEffect(()=>{v.data!==void 0&&y({scopeKey:w,appearance:v.data})},[v.data,w]);const C=(x==null?void 0:x.scopeKey)===w?x.appearance:null,N=i!==void 0?i:v.data!==void 0?v.data:C,k=S.useMemo(()=>bc.resolveAppearance({organizationAppearance:N,tokenAppearance:a,reactAppearance:e}),[e,N,a]),_=S.useCallback(()=>{f(g??h??k),u(!0)},[g,h,k]),j=S.useCallback(()=>{u(!1)},[]);S.useEffect(()=>{f(null),m(null),b(null),u(!1)},[r]);const I=S.useMemo(()=>({openBrandStudioPreview:_}),[_]),E=g??h??e;return c.jsx(Iyt,{defaultTheme:"system",storageKey:"vite-ui-theme",children:c.jsx(jyt,{value:I,children:c.jsx(efe,{organizationAppearance:N,tokenAppearance:a,reactAppearance:E,style:{height:"100%",width:"100%"},children:c.jsxs(p.TooltipProvider,{delayDuration:0,children:[t,l&&c.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:c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"flex h-full items-center justify-center text-[12px] text-muted-foreground",children:"Loading Brand Studio..."}),children:c.jsx(Myt,{appearance:d,onDraftChange:b,onSave:A=>{m(A),b(A),f(A)},onCancel:j})})})]})})})})}function nfe({children:e,preferences:t}){const{currentUser:n}=zi(),r=S.useMemo(()=>{var s,o;return{preferences:t||{},isLocalDev:((s=t==null?void 0:t.uiMode)==null?void 0:s.developer)||!1,isConsoleMode:((o=t==null?void 0:t.uiMode)==null?void 0:o.console)||!1}},[t]);return c.jsx(OW.Provider,{value:r,children:c.jsx(I_,{displayPreferences:t==null?void 0:t.cardDisplay,currentUser:n,children:e})})}function Ayt(e=2e3,t=500){const n=Jhe(),[r,s]=S.useState(!1),[o,i]=S.useState(!1),a=S.useRef(null);return S.useEffect(()=>{const l=setTimeout(()=>s(!0),e);return()=>clearTimeout(l)},[e]),S.useEffect(()=>{if(r){if(n>0){i(!1),a.current&&(clearTimeout(a.current),a.current=null);return}return a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!0)},t),()=>{a.current&&clearTimeout(a.current)}}},[r,n,t]),o}function x3({delayMs:e=2e3,quietMs:t=500,componentType:n,componentId:r}){const s=Ayt(e,t);return S.useEffect(()=>(s&&(window.__SEMAPHOR_READY__={ready:!0,type:n,componentId:r||null,timestamp:Date.now()}),()=>{window.__SEMAPHOR_READY__={ready:!1,type:n,componentId:r||null,timestamp:Date.now()}}),[s,n,r]),c.jsx("div",{id:"idle-check","aria-hidden":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s?"ready":""})}function rfe(e){if(typeof window>"u")return null;const{preferences:t}=e;return c.jsx(ba,{FallbackComponent:j_,children:c.jsxs(mR,{dashboardProps:e,children:[c.jsx(x3,{componentType:"dashboard",componentId:e.id}),c.jsx(b3,{appearance:e.appearance,children:c.jsx(nfe,{preferences:t,children:c.jsx("main",{className:"flex h-full flex-col",children:c.jsx(qR,{...e,type:"dashboard",children:c.jsx(Jde,{})})})})})]})})}function Ryt(e=[]){const t=S.useRef(null),n=S.useRef(null),r=S.useRef(null),[s,o]=S.useState(),i=S.useCallback(()=>{var m,g,b;const a=((m=t.current)==null?void 0:m.clientWidth)??0,l=((g=r.current)==null?void 0:g.offsetWidth)??0,u=((b=n.current)==null?void 0:b.offsetWidth)??0,f=a-l-u-8,h=Math.max(f,0);o(x=>x===h?x:h)},[]);return S.useEffect(()=>{const a=t.current;if(!a||typeof ResizeObserver>"u")return;const l=new ResizeObserver(()=>i());return l.observe(a),i(),()=>l.disconnect()},[i,...e]),{headerRef:t,leftActionsRef:n,rightActionsRef:r,titleMaxWidth:s,updateAvailableWidth:i}}function Fyt({filter:e}){var g;const t=p.useDashboardStore(b=>b.isDashboardEditing),{preferences:n}=Pp(),r=bh((g=n==null?void 0:n.cardDisplay)==null?void 0:g.mode),s=p.useDashboardStore(b=>b.filterValues),o=s==null?void 0:s.some(b=>b.filterId===e.id),{removeFilterValues:i,removeFilter:a,updateFilter:l}=p.useDashboardActions(),{headerRef:u,leftActionsRef:d,rightActionsRef:f,titleMaxWidth:h,updateAvailableWidth:m}=Ryt([t,o,r]);return S.useEffect(()=>{m()},[e.title,m]),c.jsxs("div",{ref:u,className:"group mb-1 flex h-5 items-center justify-between",children:[c.jsxs("div",{className:"flex grow items-center gap-2 min-w-0",children:[c.jsx("div",{className:"min-w-0 flex-1",style:h!==void 0?{maxWidth:h}:void 0,children:c.jsx(p.Label,{className:"my-1 block w-full text-sm",children:c.jsx(Oo,{value:e.title||e.column,onSave:b=>l({...e,title:b}),isEditable:t,placeholder:"Filter",displayClassName:"text-sm truncate",inputClassName:"text-sm"})})}),c.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",ref:d,children:[t&&c.jsx(h5,{filter:e,isEditing:t}),t&&c.jsx("button",{onClick:()=>{i(e.id),a(e.id)},className:"text-muted-foreground hover:text-foreground",children:c.jsx(p.X,{className:"size-3.5"})})]})]}),c.jsx("div",{className:"hidden",ref:f})]})}function Pyt(){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?c.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=>c.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[c.jsx(Fyt,{filter:r}),c.jsx(v_,{filter:r})]},r.id))}):null}function Oyt(){var i;const e=p.useDashboardStore(a=>a.dashboard),t=p.useDashboardStore(a=>a.selectedSheetId),n=p.useDashboardStore(a=>a.isVisualEditing),r=p.useDashboardStore(a=>a.isDashboardEditing),s=(i=e.sheets)==null?void 0:i.find(a=>a.id===t),o=p.isDocumentSheet(s);return c.jsx("div",{role:"dashboard-plus-main",className:p.cn("",{"max-h-0 overflow-hidden":n,"flex min-h-0 grow basis-0 overflow-hidden":!n}),children:c.jsxs("section",{className:"flex min-h-0 grow basis-0 flex-col overflow-hidden",children:[r&&!o&&c.jsx(Pyt,{}),c.jsx(Jde,{})]})})}const Lyt=S.lazy(()=>Promise.resolve().then(()=>require("./dashboard-controls-DcXMFgGR.js"))),$yt=S.lazy(()=>Promise.resolve().then(()=>require("./edit-dashboard-visual-BD2AJLiT.js"))),zyt=S.lazy(()=>Promise.resolve().then(()=>require("./dashboard-json-CFURS_OR.js"))),Byt=S.lazy(()=>Promise.resolve().then(()=>require("./resource-management-panel-DytUMSGA.js")).then(e=>({default:e.ResourceManagementPanel})));function Vyt({showControls:e=!1,showFooter:t=!0,...n}){const r=p.useDashboardStore(u=>u.isDashboardPanelOpen),s=p.useDashboardStore(u=>u.isVisualEditing),o=p.useDashboardStore(u=>u.showDashboardJSON),i=p.useDashboardStore(u=>u.actions.setIsDashboardPanelOpen),{appearance:a,preferences:l}=n;return c.jsx(ba,{FallbackComponent:j_,children:c.jsxs(mR,{dashboardProps:n,children:[c.jsx(x3,{componentType:"surfboard",componentId:n.id}),c.jsxs(b3,{appearance:a,children:[c.jsx(qge,{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"}}}),c.jsxs(nfe,{preferences:l,children:[o&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(zyt,{})}),c.jsxs("main",{className:"relative flex h-full w-full flex-col overflow-hidden",children:[e&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(Lyt,{})}),c.jsxs("div",{className:"flex grow overflow-hidden",children:[r&&c.jsx(S.Suspense,{fallback:null,children:c.jsx(Byt,{isOpen:r,onClose:()=>i(!1),variant:"inline"})}),c.jsx("div",{className:"flex min-w-0 flex-1",children:c.jsxs(qR,{...n,type:"dashboard",children:[s&&c.jsx(S.Suspense,{fallback:null,children:c.jsx($yt,{})}),c.jsx(Oyt,{})]})})]})]})]})]})]})})}var Hyt=Object.defineProperty,Uyt=(e,t,n)=>t in e?Hyt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,jS=(e,t,n)=>Uyt(e,typeof t!="symbol"?t+"":t,n);const qyt={stringify:e=>e?"true":"false",parse:e=>/^[ty1-9]/i.test(e)},Wyt={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}},Yyt={stringify:e=>JSON.stringify(e),parse:e=>JSON.parse(e)};function Gyt(e){return e.replace(/([a-z0-9])([A-Z])/g,(t,n,r)=>`${n}-${r.toLowerCase()}`)}function sfe(e){return e.replace(/[-:]([a-z])/g,(t,n)=>`${n.toUpperCase()}`)}const Kyt={stringify:e=>e.name,parse:(e,t,n)=>{const r=(()=>{const s=sfe(t);if(typeof n<"u"&&s in n.container)return n.container[s]})();return typeof r=="function"?r.bind(n):void 0}},Zyt={stringify:e=>`${e}`,parse:e=>parseFloat(e)},Xyt={stringify:e=>e,parse:e=>e},bD={string:Xyt,number:Zyt,boolean:qyt,function:Wyt,method:Kyt,json:Yyt},jb=Symbol.for("r2wc.render"),ES=Symbol.for("r2wc.connected"),Nd=Symbol.for("r2wc.context"),Yo=Symbol.for("r2wc.props");function Qyt(e,t,n){var r,s,o;t.props||(t.props=e.propTypes?Object.keys(e.propTypes):[]),t.events||(t.events=[]);const i=Array.isArray(t.props)?t.props.slice():Object.keys(t.props),a=Array.isArray(t.events)?t.events.slice():Object.keys(t.events),l={},u={},d={},f={};for(const m of i){l[m]=Array.isArray(t.props)?"string":t.props[m];const g=Gyt(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(),jS(this,o,!0),jS(this,s),jS(this,r,{}),jS(this,"container"),t.shadow?this.container=this.attachShadow({mode:t.shadow}):this.container=this,this[Yo].container=this.container;for(const g of i){const b=d[g],x=this.getAttribute(b),y=l[g],w=y?bD[y]:null;if(y==="method"){const v=sfe(b);Object.defineProperty(this[Yo].container,v,{enumerable:!0,configurable:!0,get(){return this[Yo][v]},set(C){this[Yo][v]=C,this[jb]()}}),this[Yo][g]=w.parse(x,b,this)}w!=null&&w.parse&&x&&(this[Yo][g]=w.parse(x,b,this))}for(const g of a)this[Yo][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[ES]=!0,this[jb]()}disconnectedCallback(){this[ES]=!1,this[Nd]&&n.unmount(this[Nd]),delete this[Nd]}attributeChangedCallback(g,b,x){const y=f[g],w=l[y],v=w?bD[w]:null;y in l&&v!=null&&v.parse&&x&&(this[Yo][y]=v.parse(x,g,this),this[jb]())}[(o=ES,s=Nd,r=Yo,jb)](){this[ES]&&(this[Nd]?n.update(this[Nd],this[Yo]):this[Nd]=n.mount(this.container,e,this[Yo]))}}for(const m of i){const g=d[m],b=l[m];Object.defineProperty(h.prototype,m,{enumerable:!0,configurable:!0,get(){return this[Yo][m]},set(x){this[Yo][m]=x;const y=b?bD[b]:null;if(y!=null&&y.stringify){const w=y.stringify(x,g,this);this.getAttribute(g)!==w&&this.setAttribute(g,w)}else this[jb]()}})}return h}function Jyt(e,t,n){const r=Lfe.createRoot(e),s=S.createElement(t,n);return r.render(s),{root:r,ReactComponent:t}}function e0t({root:e,ReactComponent:t},n){const r=S.createElement(t,n);e.render(r)}function t0t({root:e}){e.unmount()}function n0t(e,t={}){return Qyt(e,t,{mount:Jyt,update:e0t,unmount:t0t})}const r0t={id:"string",version:"string",authToken:"json",placeholders:"json",defaultFilterValues:"json",defaultControlValues:"json",controlContractOverrides:"json",documentInputValues:"json",dashboardInputExecutionSnapshot:"json",renderMode:"string",currentTheme:"string",customCards:"json",customStyle:"json",appearance:"json",onChartElementClicked:"function",onFilterValuesChange:"function",onEvent:"function",onSave:"function",LoadingComponent:"function",ErrorComponent:"function",showAssistant:"boolean",showBriefings:"boolean",selectedSheetId:"string",eventHandlers:"json",preferences:"json"},s0t=n0t(rfe,{props:r0t}),o0t=S.memo(function({context:t="editor"}={}){return c.jsxs("div",{"data-content":"fields-section",className:"flex h-full grow flex-col items-center overflow-hidden",children:[" ",c.jsx(hL,{context:t})," "]})}),ofe=new Set(["askForMoreInfo","getAvailableChartTypes","getChartSQLSyntax","getDomainRelationships","getTableColumns","getUserSql","validateCardConfigFormat"]),i0t=new Set(["createChartFromSql","createForecast","generateQueryConfig","getChartDataFromCardConfig","getChartDataFromSqlAndPython","getForecastDataFromSqlAndPython"]),a0t=Array.from(ofe).join(", "),l0t=3,c0t="Self-heal",u0t=new Set(["SQL_PARSE_ERROR","SQL_EXPLAIN_ERROR"]);function d0t({card:e}){var W,O,Z,Y,M;const[t,n]=S.useState({}),{authToken:r}=mt(),s=p.getTokenParams(r==null?void 0:r.accessToken),{compiledAppearance:o}=p.useAppearance(),i=S.useMemo(()=>av(o),[o]),a=p.useEditorStore(K=>K.frame),l=p.useEditorStore(K=>K.inlineFilterValuesMap[e.id]),u=p.useEditorStore(K=>K.actions.setCardInlineFilterValue),d=p.useEditorStore(K=>K.actions.removeCardInlineFilterValue),f=e,{getCard:h,manifest:m}=Nh(((W=f.customCardPreferences)==null?void 0:W.url)||""),g=(O=m==null?void 0:m.visuals)==null?void 0:O.find(K=>{var L;return K.name===((L=f.customCardPreferences)==null?void 0:L.componentName)}),b=lv(f,g)??"single",x=S.useMemo(()=>x5({frame:a,configCard:f,isMultiInputVisual:b==="multiple"}),[a,f,b]),y=S.useMemo(()=>{const K=x.findIndex(L=>(L==null?void 0:L.id)===e.id);return K<0?-1:Iy(e,K)},[x,e]),w=S.useMemo(()=>b!=="multiple"||y<0?e.type:Am(e,y,g==null?void 0:g.slots)??e.type,[b,y,e,g==null?void 0:g.slots]),v=S.useMemo(()=>b==="multiple"?{...e,connectionId:void 0,dataSource:void 0,sql:"",python:"",config:void 0,queryConfig:void 0}:w!==e.type?{...e,type:w}:e,[e,w,b]),{data:C}=pk(v),N=p.useInteractionStore(K=>K.interactionStates),k=p.useDashboardStore(K=>{var L;return(L=K.dashboard)==null?void 0:L.id}),_=p.useDashboardStore(K=>K.dashboard.filters),j=p.useDashboardStore(K=>K.filterValues),I=p.useDashboardStore(K=>K.selectedSheetId),E=S.useMemo(()=>p5({card:e,sheetId:I||"",inlineFilterValues:l,setInlineFilterValue:K=>u(e.id,K),removeInlineFilterValue:K=>d(e.id,K)}),[e,I,l,u,d]),{cardFilters:T,cardFilterValues:D}=S.useMemo(()=>k0({card:e,interactionStates:N,currentDashboardId:k,filters:_,filterValues:j,selectedSheetId:I}),[e,N,k,_,j,I]),A=S.useCallback((K,L)=>{const $=v5(L);n(B=>({...B,[K]:$}))},[]),P=(Z=f.customCardPreferences)==null?void 0:Z.componentName,R=P?h(P):null,H=VC((Y=f.customCardPreferences)==null?void 0:Y.settings,f),z=S.useMemo(()=>b5(x),[x]),U=S.useMemo(()=>z.map((K,L)=>Am(K,L,g==null?void 0:g.slots)),[z,g==null?void 0:g.slots]);return P?c.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:c.jsxs(S.Suspense,{fallback:c.jsx(c.Fragment,{}),children:[R&&b==="single"&&c.jsx(R,{editing:!0,params:s,theme:i,settings:H,cardMetadata:zse({card:e,dataMetadata:C==null?void 0:C.metadata}),onDataChange:A,data:(C==null?void 0:C.records)||[],filters:T,filterValues:[...D||[],...l||[]],inlineFilters:E}),R&&b==="multiple"&&c.jsxs(c.Fragment,{children:[x.map((K,L)=>{if(!K)return null;const $=Iy(K,L),B=Am(K,$,g==null?void 0:g.slots);return c.jsx(BO,{onDataChange:A,card:K,effectiveCardType:B},`${K.id}-${$}`)}),c.jsx("div",{className:"flex flex-col gap-2",children:c.jsx(R,{editing:!0,onDataChange:A,...w5({configCard:f,slotOrderedCards:z,slotTypes:U,multiInputData:t,params:s,theme:i,chartSettings:H,filters:T,filterValues:[...D||[],...l||[]],inlineFilters:E})})})]})]},(M=f.customCardPreferences)==null?void 0:M.componentName)}):null}const f0t=S.memo(d0t,(e,t)=>{var n,r,s,o,i,a,l,u;return e.card.id===t.card.id&&e.card.inlineFilters===t.card.inlineFilters&&((n=e.card.customCardPreferences)==null?void 0:n.settings)===((r=t.card.customCardPreferences)==null?void 0:r.settings)&&((s=e.card.customCardPreferences)==null?void 0:s.slotSettings)===((o=t.card.customCardPreferences)==null?void 0:o.slotSettings)&&((i=e.card.customCardPreferences)==null?void 0:i.url)===((a=t.card.customCardPreferences)==null?void 0:a.url)&&((l=e.card.customCardPreferences)==null?void 0:l.componentName)===((u=t.card.customCardPreferences)==null?void 0:u.componentName)}),h0t=p.create()(p.persist((e,t)=>({starredCharts:[],isStarred:(n,r)=>t().starredCharts.some(s=>s.type===n&&s.id===r),toggleStar:n=>{e(r=>{const s=r.starredCharts.findIndex(o=>o.type===n.type&&o.id===n.id);return s>=0?{starredCharts:r.starredCharts.filter((o,i)=>i!==s)}:{starredCharts:[...r.starredCharts,n]}})},getStarredChart:(n,r)=>t().starredCharts.find(s=>s.type===n&&s.id===r)}),{name:"semaphor-starred-charts"}));var ife=["PageUp","PageDown"],afe=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],lfe={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Pg="Slider",[rR,m0t,p0t]=p.createCollection(Pg),[cfe]=p.createContextScope(Pg,[p0t]),[g0t,Cj]=cfe(Pg),ufe=Q.forwardRef((e,t)=>{const{name:n,min:r=0,max:s=100,step:o=1,orientation:i="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:u=[r],value:d,onValueChange:f=()=>{},onValueCommit:h=()=>{},inverted:m=!1,form:g,...b}=e,x=Q.useRef(new Set),y=Q.useRef(0),v=i==="horizontal"?b0t:x0t,[C=[],N]=p.useControllableState({prop:d,defaultProp:u,onChange:T=>{var A;(A=[...x.current][y.current])==null||A.focus(),f(T)}}),k=Q.useRef(C);function _(T){const D=C0t(C,T);E(T,D)}function j(T){E(T,y.current)}function I(){const T=k.current[y.current];C[y.current]!==T&&h(C)}function E(T,D,{commit:A}={commit:!1}){const P=j0t(o),R=E0t(Math.round((T-r)/o)*o+r,P),H=p.clamp(R,[r,s]);N((z=[])=>{const U=w0t(z,H,D);if(_0t(U,l*o)){y.current=U.indexOf(H);const W=String(U)!==String(z);return W&&A&&h(U),W?U:z}else return z})}return c.jsx(g0t,{scope:e.__scopeSlider,name:n,disabled:a,min:r,max:s,valueIndexToChangeRef:y,thumbs:x.current,values:C,orientation:i,form:g,children:c.jsx(rR.Provider,{scope:e.__scopeSlider,children:c.jsx(rR.Slot,{scope:e.__scopeSlider,children:c.jsx(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...b,ref:t,onPointerDown:p.composeEventHandlers(b.onPointerDown,()=>{a||(k.current=C)}),min:r,max:s,inverted:m,onSlideStart:a?void 0:_,onSlideMove:a?void 0:j,onSlideEnd:a?void 0:I,onHomeKeyDown:()=>!a&&E(r,0,{commit:!0}),onEndKeyDown:()=>!a&&E(s,C.length-1,{commit:!0}),onStepKeyDown:({event:T,direction:D})=>{if(!a){const R=ife.includes(T.key)||T.shiftKey&&afe.includes(T.key)?10:1,H=y.current,z=C[H],U=o*R*D;E(z+U,H,{commit:!0})}}})})})})});ufe.displayName=Pg;var[dfe,ffe]=cfe(Pg,{startEdge:"left",endEdge:"right",size:"width",direction:1}),b0t=Q.forwardRef((e,t)=>{const{min:n,max:r,dir:s,inverted:o,onSlideStart:i,onSlideMove:a,onSlideEnd:l,onStepKeyDown:u,...d}=e,[f,h]=Q.useState(null),m=p.useComposedRefs(t,v=>h(v)),g=Q.useRef(void 0),b=p.useDirection(s),x=b==="ltr",y=x&&!o||!x&&o;function w(v){const C=g.current||f.getBoundingClientRect(),N=[0,C.width],_=y3(N,y?[n,r]:[r,n]);return g.current=C,_(v-C.left)}return c.jsx(dfe,{scope:e.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:c.jsx(hfe,{dir:b,"data-orientation":"horizontal",...d,ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{const C=w(v.clientX);i==null||i(C)},onSlideMove:v=>{const C=w(v.clientX);a==null||a(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:v=>{const N=lfe[y?"from-left":"from-right"].includes(v.key);u==null||u({event:v,direction:N?-1:1})}})})}),x0t=Q.forwardRef((e,t)=>{const{min:n,max:r,inverted:s,onSlideStart:o,onSlideMove:i,onSlideEnd:a,onStepKeyDown:l,...u}=e,d=Q.useRef(null),f=p.useComposedRefs(t,d),h=Q.useRef(void 0),m=!s;function g(b){const x=h.current||d.current.getBoundingClientRect(),y=[0,x.height],v=y3(y,m?[r,n]:[n,r]);return h.current=x,v(b-x.top)}return c.jsx(dfe,{scope:e.__scopeSlider,startEdge:m?"bottom":"top",endEdge:m?"top":"bottom",size:"height",direction:m?1:-1,children:c.jsx(hfe,{"data-orientation":"vertical",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:b=>{const x=g(b.clientY);o==null||o(x)},onSlideMove:b=>{const x=g(b.clientY);i==null||i(x)},onSlideEnd:()=>{h.current=void 0,a==null||a()},onStepKeyDown:b=>{const y=lfe[m?"from-bottom":"from-top"].includes(b.key);l==null||l({event:b,direction:y?-1:1})}})})}),hfe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:s,onSlideEnd:o,onHomeKeyDown:i,onEndKeyDown:a,onStepKeyDown:l,...u}=e,d=Cj(Pg,n);return c.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()):ife.concat(afe).includes(f.key)&&(l(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)&&s(f)}),onPointerUp:p.composeEventHandlers(e.onPointerUp,f=>{const h=f.target;h.hasPointerCapture(f.pointerId)&&(h.releasePointerCapture(f.pointerId),o(f))})})}),mfe="SliderTrack",pfe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=Cj(mfe,n);return c.jsx(p.Primitive.span,{"data-disabled":s.disabled?"":void 0,"data-orientation":s.orientation,...r,ref:t})});pfe.displayName=mfe;var sR="SliderRange",gfe=Q.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,s=Cj(sR,n),o=ffe(sR,n),i=Q.useRef(null),a=p.useComposedRefs(t,i),l=s.values.length,u=s.values.map(h=>yfe(h,s.min,s.max)),d=l>1?Math.min(...u):0,f=100-Math.max(...u);return c.jsx(p.Primitive.span,{"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,...r,ref:a,style:{...e.style,[o.startEdge]:d+"%",[o.endEdge]:f+"%"}})});gfe.displayName=sR;var oR="SliderThumb",bfe=Q.forwardRef((e,t)=>{const n=m0t(e.__scopeSlider),[r,s]=Q.useState(null),o=p.useComposedRefs(t,a=>s(a)),i=Q.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return c.jsx(y0t,{...e,ref:o,index:i})}),y0t=Q.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,name:s,...o}=e,i=Cj(oR,n),a=ffe(oR,n),[l,u]=Q.useState(null),d=p.useComposedRefs(t,w=>u(w)),f=l?i.form||!!l.closest("form"):!0,h=p.useSize(l),m=i.values[r],g=m===void 0?0:yfe(m,i.min,i.max),b=S0t(r,i.values.length),x=h==null?void 0:h[a.size],y=x?N0t(x,g,a.direction):0;return Q.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),c.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${g}% + ${y}px)`},children:[c.jsx(rR.ItemSlot,{scope:e.__scopeSlider,children:c.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,...o,ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:p.composeEventHandlers(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})})}),f&&c.jsx(xfe,{name:s??(i.name?i.name+(i.values.length>1?"[]":""):void 0),form:i.form,value:m},r)]})});bfe.displayName=oR;var v0t="RadioBubbleInput",xfe=Q.forwardRef(({__scopeSlider:e,value:t,...n},r)=>{const s=Q.useRef(null),o=p.useComposedRefs(s,r),i=p.usePrevious(t);return Q.useEffect(()=>{const a=s.current;if(!a)return;const l=window.HTMLInputElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const f=new Event("input",{bubbles:!0});d.call(a,t),a.dispatchEvent(f)}},[i,t]),c.jsx(p.Primitive.input,{style:{display:"none"},...n,ref:o,defaultValue:t})});xfe.displayName=v0t;function w0t(e=[],t,n){const r=[...e];return r[n]=t,r.sort((s,o)=>s-o)}function yfe(e,t,n){const o=100/(n-t)*(e-t);return p.clamp(o,[0,100])}function S0t(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function C0t(e,t){if(e.length===1)return 0;const n=e.map(s=>Math.abs(s-t)),r=Math.min(...n);return n.indexOf(r)}function N0t(e,t,n){const r=e/2,o=y3([0,50],[0,r]);return(r-o(t)*n)*n}function k0t(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function _0t(e,t){if(t>0){const n=k0t(e);return Math.min(...n)>=t}return!0}function y3(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 j0t(e){return(String(e).split(".")[1]||"").length}function E0t(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}var vfe=ufe,I0t=pfe,T0t=gfe,D0t=bfe;const wfe=Q.forwardRef(({className:e,...t},n)=>c.jsxs(vfe,{ref:n,className:p.cn("relative flex w-full touch-none select-none items-center",e),...t,children:[c.jsx(I0t,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:c.jsx(T0t,{className:"absolute h-full bg-primary"})}),c.jsx(D0t,{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"})]}));wfe.displayName=vfe.displayName;const Sfe=["SUN","MON","TUE","WED","THU","FRI","SAT"],M0t=Sfe.reduce((e,t,n)=>({...e,[t]:n}),{}),Tl={repeats:"weekly",hour:9,minute:0,weekdays:[1,2,3,4,5],isCustom:!1};function A0t(e){if(!e||!e.trim())return{...Tl};const t=e.trim(),r=(t.startsWith("cron(")&&t.endsWith(")")?t.slice(5,-1):t).trim().split(/\s+/);if(r.length<5||r.length>6)return{...Tl,isCustom:!0};const[s,o,i,a,l]=r,u=Number(s),d=Number(o);if(!Number.isInteger(u)||u<0||u>59||!Number.isInteger(d)||d<0||d>23)return{...Tl,isCustom:!0};if(i==="*"&&(l==="?"||l==="*"))return{...Tl,repeats:"daily",hour:d,minute:u};if(i==="?"&&l!=="?"&&l!=="*"){const h=l.split(",").map(m=>m.toUpperCase()).map(m=>M0t[m]).filter(m=>typeof m=="number");if(h.length>0)return{...Tl,repeats:"weekly",hour:d,minute:u,weekdays:h}}return i==="1,15"&&(l==="?"||l==="*")?{...Tl,repeats:"biweekly",hour:d,minute:u}:i==="1"&&(l==="?"||l==="*")?{...Tl,repeats:"monthly",hour:d,minute:u}:{...Tl,hour:d,minute:u,isCustom:!0}}function R0t(e){const t=e.minute,n=e.hour;switch(e.repeats){case"daily":return`cron(${t} ${n} * * ? *)`;case"weekly":{const r=e.weekdays.length>0?e.weekdays.slice().sort((s,o)=>s-o).map(s=>Sfe[s]).join(","):"MON";return`cron(${t} ${n} ? * ${r} *)`}case"biweekly":return`cron(${t} ${n} 1,15 * ? *)`;case"monthly":return`cron(${t} ${n} 1 * ? *)`}}function Cfe(e,t){const n=e<12?"AM":"PM",r=e%12===0?12:e%12,s=t.toString().padStart(2,"0");return`${r}:${s} ${n}`}function F0t(e){return!e||e==="UTC"?"UTC":(e.split("/").pop()??e).replace(/_/g," ")}function P0t(e){if(e.length===7)return"every day";const t=e.slice().sort((s,o)=>s-o);if(t.length===5&&t.every(s=>s>=1&&s<=5))return"weekdays";const r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return t.map(s=>r[s]).join(", ")}function O0t(e,t,n,r){const s=Cfe(e.hour,e.minute),o=F0t(t);let i;if(e.isCustom)i=`Custom schedule · ${s} ${o}`;else switch(e.repeats){case"daily":i=`Daily at ${s} ${o}`;break;case"weekly":i=`Weekly · ${P0t(e.weekdays)} at ${s} ${o}`;break;case"biweekly":i=`Every two weeks (1st and 15th) at ${s} ${o}`;break;case"monthly":i=`Monthly on the 1st at ${s} ${o}`;break}const a=[];return n&&n!=="Today"&&a.push(`from ${n}`),r&&a.push(`until ${r}`),a.length>0?`${i}, ${a.join(" ")}`:i}const L0t=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","Europe/London","Europe/Berlin","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];exports.Accordion=oL;exports.AccordionContent=By;exports.AccordionItem=$y;exports.AccordionTrigger=zy;exports.AddDataPicker=YL;exports.AggregateTable=Kk;exports.Alert=LF;exports.AlertDescription=$F;exports.AlertDialog=dh;exports.AlertDialogAction=Ku;exports.AlertDialogCancel=Zu;exports.AlertDialogContent=Uu;exports.AlertDialogDescription=Gu;exports.AlertDialogFooter=Wu;exports.AlertDialogHeader=qu;exports.AlertDialogTitle=Yu;exports.AlertDialogTrigger=ixe;exports.AlertTitle=nZ;exports.ArrowDown=Ns;exports.ArrowDownIcon=PHe;exports.ArrowLeft=f0;exports.ArrowRight=AN;exports.ArrowUp=Ls;exports.ArrowUpIcon=LHe;exports.AssistantContextEntityControls=VA;exports.AssistantVirtualizedMessages=Kde;exports.AtSign=oq;exports.AxisConfigurator=qp;exports.Badge=rs;exports.Bell=DS;exports.BookType=aq;exports.BulletChartIcon=Bde;exports.COMMON_TIMEZONES=L0t;exports.CSS=di;exports.CalculatedFieldEditor=Qie;exports.Calculator=cq;exports.Calendar=ti;exports.Calendar$1=s1;exports.CalendarRange=uq;exports.Card=Xm;exports.CardContent=MN;exports.CardHeader=DN;exports.CardSummary=fA;exports.CardTitle=Rp;exports.ChartArea=BD;exports.ChartColumnIncreasing=dq;exports.ChartColumnStacked=fq;exports.ChartJsVisual=J0;exports.ChartLine=hq;exports.ChartNoAxesGantt=pq;exports.ChartPie=gq;exports.ChartScatter=bq;exports.ChatInputWithContext=GL;exports.Checkbox=En;exports.ChevronLeft=lh;exports.ChevronRight=vr;exports.Circle=xR;exports.CircleAlert=Mf;exports.CircleCheck=vq;exports.CircleHelp=wq;exports.Clock=yR;exports.CodeHighlighter=If;exports.CodeXml=MS;exports.Collapsible=mc;exports.CollapsibleContent=gc;exports.CollapsibleTrigger=pc;exports.ColorField=ki;exports.Command=z_;exports.CommandEmpty=V_;exports.CommandGroup=H_;exports.CommandInput=Y5;exports.CommandItem=U_;exports.CommandList=B_;exports.CommandSeparator=xie;exports.ComparisonMetadataBadge=_J;exports.Container=qR;exports.ControlDefaultValueEditor=vae;exports.ControlDefinitionOptionsEditor=yae;exports.ControlIdInput=pae;exports.ControlVisibilitySettings=YQe;exports.Copy=yu;exports.CopyButton=bu;exports.CopyPlus=HD;exports.Cross2Icon=VHe;exports.CustomFilterPopover=h5;exports.CustomScrollArea=bl;exports.DEFAULT_HEATMAP_CUSTOM_RANGE=IQ;exports.DEFAULT_SCHEDULE_VM=Tl;exports.Dashboard=rfe;exports.DashboardActionsMenu=LW;exports.DashboardCard=Noe;exports.DashboardCreateDialogBase=pY;exports.DashboardExportDialog=Zde;exports.DashboardPlus=Vyt;exports.DashboardWC=s0t;exports.DataTableConditionalFormattingSettings=lle;exports.DataTablePagination=Hk;exports.Database=Mi;exports.DateRangePicker=YO;exports.DefaultChatTransport=$L;exports.Dialog=yo;exports.DialogContent=Js;exports.DialogDescription=Bo;exports.DialogFooter=vc;exports.DialogHeader=Bi;exports.DialogTitle=eo;exports.DialogTrigger=fY;exports.DisplayPreferencesProvider=I_;exports.DndContext=yv;exports.Donut=Sq;exports.Download=xc;exports.DownloadPdf=Xde;exports.DragOverlay=sie;exports.DropdownMenu=po;exports.DropdownMenuCheckboxItem=Lc;exports.DropdownMenuContent=Ks;exports.DropdownMenuItem=bn;exports.DropdownMenuLabel=tc;exports.DropdownMenuRadioGroup=xge;exports.DropdownMenuRadioItem=PW;exports.DropdownMenuSeparator=fa;exports.DropdownMenuSub=OR;exports.DropdownMenuSubContent=BN;exports.DropdownMenuSubTrigger=zN;exports.DropdownMenuTrigger=go;exports.EMPTY_DATA_SOURCE=Dp;exports.Editable=UC;exports.EditableText=Oo;exports.EditorCustomVisual=f0t;exports.Ellipsis=da;exports.EllipsisVertical=ch;exports.ErrorBoundary=ba;exports.ExportError=Qp;exports.ExternalLink=Jm;exports.Eye=h0;exports.EyeOff=RN;exports.Fallback=j_;exports.FallbackVisual=Dy;exports.FeedbackCategory=Vu;exports.FeedbackDialog=e0;exports.FieldsList=hL;exports.FieldsSection=o0t;exports.FileCode=Cq;exports.FileSpreadsheet=Nq;exports.FileText=oi;exports.Filter=Af;exports.FilterComponent=v_;exports.FilterInfo=lA;exports.FilterableFieldsPanel=eae;exports.Globe=Fp;exports.Grid3x3=kq;exports.GripVertical=yc;exports.HEATMAP_PRESET_PALETTES=G2;exports.Hash=_q;exports.House=jq;exports.HoverCard=eg;exports.HoverCardContent=Iu;exports.HoverCardTrigger=tg;exports.INLINE_ALLOWED_READ_ONLY_TOOLS=ofe;exports.INLINE_ALLOWED_TOOL_LIST=a0t;exports.INLINE_BLOCKED_MUTATING_TOOLS=i0t;exports.IconButton=ec;exports.IconForFieldType=d1;exports.InfoHover=F5;exports.InlineFilterBar=moe;exports.KPICard=Pu;exports.KeyboardSensor=bv;exports.Layers=m0;exports.LayoutDashboard=ep;exports.Link=vR;exports.LoadingDots=Du;exports.Lock=FN;exports.MAX_SELF_HEAL_ATTEMPTS=l0t;exports.Map=Tq;exports.Markdown=rde;exports.Maximize2=PN;exports.MdStackedLineChart=$de;exports.Minimize2=wR;exports.MultiInputEmptyRenderer=BO;exports.PYTHON_DEFAULT_CODE=aR;exports.PanelLeft=Dq;exports.PanelResizeHandle=aj;exports.Paperclip=Mq;exports.PenLine=UD;exports.Pencil=qD;exports.PendingMessagesDisplay=xue;exports.PersistedDynamicVisual=E_;exports.PiChartPolar=Fde;exports.PivotTableTanstack=wg;exports.Placeholders=Fle;exports.Play=Aq;exports.Plus=wr;exports.PointerSensor=jg;exports.Progress=qL;exports.RECOVERABLE_SQL_ERROR_CODES=u0t;exports.Radar=Rq;exports.RadioGroup=ma;exports.RadioGroupItem=ps;exports.RefreshCw=Rf;exports.ResizableHandle=srt;exports.ResizablePanel=TA;exports.ResizablePanelGroup=Rle;exports.ResourceEditDialog=WY;exports.ResourceType=$r;exports.SELF_HEAL_TIMELINE_STEP=c0t;exports.Search=Xs;exports.SeedQuestions=rue;exports.SemaphorContext=c0;exports.SemaphorContextProvider=mR;exports.SemaphorQueryClient=JU;exports.SemaphorReadyIndicator=x3;exports.SemaphorStyleWrapper=Sg;exports.Send=Fq;exports.Settings=SR;exports.Settings2=p0;exports.Share2=Pq;exports.ShareDialog=qY;exports.Sheet=mJ;exports.SheetContent=$P;exports.SheetDescription=BP;exports.SheetHeader=gJ;exports.SheetTitle=zP;exports.SheetTrigger=BRe;exports.Slider=wfe;exports.SortableContext=vv;exports.Sparkles=E1;exports.Square=NR;exports.SquarePen=CR;exports.Star=kR;exports.StructuralParticipantSelector=gae;exports.SummaryCard=oA;exports.TABLE_PRESENTATION_DEFAULT_STYLE=pu;exports.TABLE_PRESENTATION_DEFAULT_TOTALS_STYLE=Ei;exports.TableBody=Uf;exports.TableCell=Yn;exports.TableColumnVisibilitySettings=Zae;exports.TableHead=Mo;exports.TableHeader=Jp;exports.TablePresentationSettings=Qae;exports.TableRow=Or;exports.TableSkeleton=P5;exports.TableVisual=Tu;exports.TbChartBubble=Pde;exports.TbChartFunnel=Ode;exports.TbChartTreemap=Lde;exports.TextCard=Np;exports.Textarea=hh;exports.TiSortNumerically=zde;exports.Toggle=k_;exports.Tornado=Oq;exports.Trash2=rl;exports.TreePalm=jR;exports.TrendingUp=Lq;exports.TriangleAlert=Ai;exports.TypeGlyph=fv;exports.UXProvider=b3;exports.User=$q;exports.Users=ER;exports.applyFilterOverridesToDashboardInputSlots=SK;exports.areContextEntitiesEqual=Gn;exports.areEntitiesJoined=RQ;exports.arrayMove=Eg;exports.buildCardControlUsageById=KQe;exports.buildCustomCardTheme=av;exports.buildDashboardCardExecutionSnapshot=wK;exports.buildDashboardControlUsageById=GQe;exports.buildDashboardExecutionSnapshot=MF;exports.buildDashboardInputExecutionSnapshot=cu;exports.buildDashboardSheetsInputExecutionSnapshot=NK;exports.buildDashboardStructuralParticipantIdsByControlId=Cae;exports.buildFilterFieldMeta=J5;exports.buildFilterSemanticContext=eL;exports.buildInlineFilterNodes=p5;exports.buildMultiInputCustomVisualProps=w5;exports.buildScheduleExpr=R0t;exports.buildSchedulePreview=O0t;exports.buildSlotOrderedCards=b5;exports.calculateContextAwareFilters=k0;exports.calculateFieldState=TP;exports.canUserAccessVisuals=fye;exports.canUserCreateDashboards=KY;exports.canUserEdit=cye;exports.canUserManageDashboards=dye;exports.canUserManageGroups=hye;exports.canUserUseFilters=uye;exports.cancelExport=IAe;exports.chartSupportsDataLabels=_X;exports.chartSupportsLegend=NX;exports.chartTypes=Sj;exports.cleanupKpiMetricComparisonMode=_ie;exports.cloneDeep=Ao;exports.cloneLinkedFrameWithSourceMapping=eWe;exports.closestCenter=gv;exports.commitSharedCalculatedFields=Ad;exports.createAssistantConversationId=fm;exports.createAssistantRequestId=tue;exports.createCardsFromSlots=pUe;exports.createChartConfig=Xp;exports.createDashboardControlInputFromControl=Wtt;exports.createDefaultGlobalDateFilter=lSe;exports.createExport=eJ;exports.createUniqueDashboardInputVariableNameFromName=xu;exports.dedup=Jlt;exports.doesStoredFilterMatchField=Ip;exports.downloadDocumentPdf=RF;exports.downloadPdf=MK;exports.extractSqlParamReferences=Ere;exports.extractTableMetadata=Q5;exports.fieldAlreadyExists=PQ;exports.findCustomVisualConfigCard=y5;exports.findDashboardFrameById=Jwe;exports.flexRender=Fo;exports.formatDisplayFormula=HZe;exports.formatFileSize=MAe;exports.formatFilterLine=sZ;exports.formatTimeLabel=Cfe;exports.getAutoDetectedChartIcon=pxt;exports.getChartGridStyle=MCe;exports.getChartIconByType=gxt;exports.getColorForValue=d2;exports.getConfigSlotExpectedType=mUe;exports.getCoreRowModel=zk;exports.getCustomVisualInputCards=x5;exports.getDateFormatOptionsForGranularity=Oy;exports.getDefaultAxisConfig=h2;exports.getDefaultChartColors=xh;exports.getDefaultDataLabelsConfig=O0;exports.getDefaultExportFormat=wZ;exports.getDefaultFilterSql=QO;exports.getDefaultLegendConfig=hP;exports.getDefaultRunningTotalPartitionByFieldIds=Rx;exports.getDocumentSectionEditorCard=_Qe;exports.getDocumentSheetDashboardInputs=kv;exports.getDownloadUrl=EAe;exports.getEffectiveCardTypeForSlot=Am;exports.getEntityIcon=wN;exports.getErrorMessage=Hce;exports.getExportStatus=jAe;exports.getExports=_Ae;exports.getExpressionFieldKind=Lu;exports.getFieldExpressionAnnotation=tL;exports.getFilterCount=KC;exports.getGlobalDateFilter=$p;exports.getGlobalDateFilterCoverage=cSe;exports.getGranularityOptionsForFieldType=yL;exports.getKeys=rr;exports.getMetricDisplayLabel=GMe;exports.getNewField=BQ;exports.getObjectDiff=AU;exports.getPaginationRowModel=Bk;exports.getRoleBasedDisplayOverrides=GY;exports.getRunningTotalOrderByCandidates=fZe;exports.getSelectedDateFilterColumn=Tre;exports.getSheetScopedFilterValues=Gx;exports.getSlotDefinitionForIndex=g5;exports.getSlotExpectedChartType=C_;exports.getSlotIndexForCard=Iy;exports.getSortedRowModel=hJ;exports.getSupportedExportFormats=vZ;exports.getTableConditionalFormattingColumnOptions=nle;exports.getTableOutputColumnOptions=rle;exports.getTablePageSizeOptions=XQ;exports.handleAggregationChange=cA;exports.handleAggregationLabelChange=foe;exports.hasFlatTableTotalsBehavior=r1e;exports.horizontalListSortingStrategy=H5;exports.isCalculatedFilterField=Ly;exports.isCardSummaryVisibleOnCard=S5;exports.isCustomVisualConfigCard=rA;exports.isDefaultColor=f1e;exports.isEligibleFlatTableTotalsCard=zp;exports.isExportComplete=DAe;exports.isExportInProgress=TAe;exports.isInAiScopeArray=Qlt;exports.isManagedCalculatedExpressionField=la;exports.isMetricTransformEnabled=uZe;exports.isPromiseLike=BA;exports.isSubtotalEnabledAggregateTable=X5;exports.isSupportedDocumentTableCardType=jQe;exports.lastAssistantMessageIsCompleteWithToolCalls=$ce;exports.merge=nl;exports.mergeAxisConfig=m2;exports.normalizeConditionalFormatting=kF;exports.normalizeContextFormatMode=uZ;exports.normalizeDashboardInputVariableName=d0;exports.normalizeMultiInputPayload=v5;exports.parseScheduleExpr=A0t;exports.pivotData=T0;exports.prepareFeedbackData=wj;exports.purify=OM;exports.reindexSlotCards=hUe;exports.remarkGfm=Dde;exports.removeFromScopeArray=ect;exports.resolveDashboardInputContext=gl;exports.resolveDomainCalculatedFieldForEdit=LXe;exports.resolveMultiInputType=lv;exports.resolveMultiInputTypeFromVisual=gUe;exports.resolveTablePageSize=Ok;exports.resolveTablePresentationStyle=ZP;exports.sanitizeAIScope=Vce;exports.saveCalculatedFieldToCardScope=wA;exports.saveCalculatedFieldToSharedScope=Jie;exports.saveCalculatedFieldToSheetScope=SA;exports.seedSemanticMetricFormatDefaults=Eie;exports.setTableColumnVisibility=rJ;exports.setupEditorWithCard=gk;exports.showAllTableColumns=PAe;exports.showJoinRequiredNotification=FQ;exports.sortByColumnsToSortState=PJ;exports.sortStateToSortByColumns=OJ;exports.sortableKeyboardCoordinates=q5;exports.supportsMetricTransformForMetric=jie;exports.supportsTableConditionalFormatting=Jae;exports.toEntityArray=aa;exports.ue=tt;exports.useActiveExports=yye;exports.useActiveToolStatus=vue;exports.useAddFrameWithFreshSemanticExecutionPayload=R5;exports.useAddNewFrame=Roe;exports.useAssistantContainer=QY;exports.useAssistantContextEntities=D_;exports.useAssistantLayoutStore=hf;exports.useAssistantPanel=ZY;exports.useAssistantProfile=nue;exports.useAutoSubmitQueue=yue;exports.useBrandStudioPreview=Eyt;exports.useCard=iAe;exports.useCardFilterValues=HQ;exports.useCardSummary=C5;exports.useChat=Bce;exports.useColumns=G5;exports.useCreateVisualWithFrame=ube;exports.useCurrentUserInfo=zi;exports.useCustomVisual=Nh;exports.useCustomVisualsQuery=f5;exports.useDashboardAppearance=dl;exports.useDashboardById=qW;exports.useDashboardCreation=GW;exports.useDashboardManagement=YW;exports.useDashboardPreferences=Pp;exports.useDashboardQuery=u0;exports.useDashboardStructuralParticipants=Nae;exports.useDashboardSummary=Kse;exports.useDataColumns=Tie;exports.useDateFilterHook=YVe;exports.useDebounce=Ex;exports.useDefaultDashboardMutation=$W;exports.useDisplayPreferences=pl;exports.useDroppable=rie;exports.useEditorAside=q_;exports.useEditorCardQuery=pk;exports.useEnsureReactGlobals=rre;exports.useExportActions=JY;exports.useExportStore=ZN;exports.useFieldManagement=Iie;exports.useFilterableFields=Cie;exports.useFullscreenAssistant=XY;exports.useGroupMembers=dxe;exports.useGroups=OY;exports.useHasDashboardId=eG;exports.useInProgressExportsCount=vye;exports.useIsDashboardSelected=rme;exports.useIsVisualSelected=sme;exports.useJoinabilityMap=Z5;exports.useManagementActions=ah;exports.useManagementStore=Kr;exports.useMutation=Ys;exports.usePivotTableConfig=vh;exports.usePluginQuery=Fse;exports.useQuery=jn;exports.useQueryClient=qr;exports.useReactTable=Vk;exports.useResolveExistingFrameSemanticExecutionPayload=sWe;exports.useResourceManagement=UN;exports.useResourceUpdateState=WW;exports.useScopedFields=Sie;exports.useSelectedVisual=nme;exports.useSemaphorContext=mt;exports.useSensor=Ep;exports.useSensors=F_;exports.useSortable=Ig;exports.useStarredChartsStore=h0t;exports.useSurfaceAppearance=Sc;exports.useTableQueryState=jJ;exports.useTextFilterHook=s8e;exports.useTheme=lR;exports.useTopoJson=$0;exports.useUnifiedUsers=HR;exports.useUpdateResource=BW;exports.useUpdateVisualMutation=dbe;exports.useUserPreferences=gY;exports.useVisualById=HN;exports.useVisualManagement=cbe;exports.validateFieldForChartType=kie;exports.verticalListSortingStrategy=U5;
|